1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VariadicFunction.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
56 using namespace dwarf;
58 STATISTIC(NumTailCalls, "Number of tail calls");
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static SDValue Insert128BitVector(SDValue Result,
70 static SDValue Extract128BitVector(SDValue Vec,
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference. Idx is an index in the 128 bits we
78 /// want. It need not be aligned to a 128-bit bounday. That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
84 EVT VT = Vec.getValueType();
85 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86 EVT ElVT = VT.getVectorElementType();
87 int Factor = VT.getSizeInBits()/128;
88 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89 VT.getVectorNumElements()/Factor);
91 // Extract from UNDEF is UNDEF.
92 if (Vec.getOpcode() == ISD::UNDEF)
93 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
95 if (isa<ConstantSDNode>(Idx)) {
96 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
98 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
99 // we can match to VEXTRACTF128.
100 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
102 // This is the index of the first element of the 128-bit chunk
104 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
117 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference. Idx is an index in the 128 bits
120 /// we want. It need not be aligned to a 128-bit bounday. That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
127 if (isa<ConstantSDNode>(Idx)) {
128 EVT VT = Vec.getValueType();
129 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
131 EVT ElVT = VT.getVectorElementType();
132 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133 EVT ResultVT = Result.getValueType();
135 // Insert the relevant 128 bits.
136 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
138 // This is the index of the first element of the 128-bit chunk
140 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154 bool is64Bit = Subtarget->is64Bit();
156 if (Subtarget->isTargetEnvMacho()) {
158 return new X8664_MachoTargetObjectFile();
159 return new TargetLoweringObjectFileMachO();
162 if (Subtarget->isTargetELF())
163 return new TargetLoweringObjectFileELF();
164 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165 return new TargetLoweringObjectFileCOFF();
166 llvm_unreachable("unknown subtarget type");
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<X86Subtarget>();
172 X86ScalarSSEf64 = Subtarget->hasXMMInt();
173 X86ScalarSSEf32 = Subtarget->hasXMM();
174 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
176 RegInfo = TM.getRegisterInfo();
177 TD = getTargetData();
179 // Set up the TargetLowering object.
180 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
182 // X86 is weird, it always uses i8 for shift amounts and setcc results.
183 setBooleanContents(ZeroOrOneBooleanContent);
184 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
187 // For 64-bit since we have so many registers use the ILP scheduler, for
188 // 32-bit code use the register pressure specific scheduling.
189 if (Subtarget->is64Bit())
190 setSchedulingPreference(Sched::ILP);
192 setSchedulingPreference(Sched::RegPressure);
193 setStackPointerRegisterToSaveRestore(X86StackPtr);
195 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196 // Setup Windows compiler runtime calls.
197 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199 setLibcallName(RTLIB::SREM_I64, "_allrem");
200 setLibcallName(RTLIB::UREM_I64, "_aullrem");
201 setLibcallName(RTLIB::MUL_I64, "_allmul");
202 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
213 if (Subtarget->isTargetDarwin()) {
214 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215 setUseUnderscoreSetJmp(false);
216 setUseUnderscoreLongJmp(false);
217 } else if (Subtarget->isTargetMingw()) {
218 // MS runtime is weird: it exports _setjmp, but longjmp!
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(false);
222 setUseUnderscoreSetJmp(true);
223 setUseUnderscoreLongJmp(true);
226 // Set up the register classes.
227 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230 if (Subtarget->is64Bit())
231 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
233 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
235 // We don't accept any truncstore of integer registers.
236 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
243 // SETOEQ and SETUNE require checking two conditions.
244 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
251 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
253 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
260 } else if (!TM.Options.UseSoftFloat) {
261 // We have an algorithm for SSE2->double, and we turn this into a
262 // 64-bit FILD followed by conditional FADD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
264 // We have an algorithm for SSE2, and we turn this into a 64-bit
265 // FILD for other targets.
266 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
269 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
271 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
272 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
274 if (!TM.Options.UseSoftFloat) {
275 // SSE has no i16 to fp conversion, only i32
276 if (X86ScalarSSEf32) {
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
278 // f32 and f64 cases are Legal, f80 case is not
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
286 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
289 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
290 // are Legal, f80 is custom lowered.
291 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
292 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
294 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
296 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
299 if (X86ScalarSSEf32) {
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
301 // f32 and f64 cases are Legal, f80 case is not
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
305 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
308 // Handle FP_TO_UINT by promoting the destination to a larger signed
310 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
314 if (Subtarget->is64Bit()) {
315 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
317 } else if (!TM.Options.UseSoftFloat) {
318 // Since AVX is a superset of SSE3, only check for SSE here.
319 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320 // Expand FP_TO_UINT into a select.
321 // FIXME: We would like to use a Custom expander here eventually to do
322 // the optimal thing for SSE vs. the default expansion in the legalizer.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
325 // With SSE3 we can use fisttpll to convert to a signed i64; without
326 // SSE, we're stuck with a fistpll.
327 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
330 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331 if (!X86ScalarSSEf64) {
332 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
333 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
334 if (Subtarget->is64Bit()) {
335 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
336 // Without SSE, i64->f64 goes through memory.
337 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
341 // Scalar integer divide and remainder are lowered to use operations that
342 // produce two results, to match the available instructions. This exposes
343 // the two-result form to trivial CSE, which is able to combine x/y and x%y
344 // into a single instruction.
346 // Scalar integer multiply-high is also lowered to use two-result
347 // operations, to match the available instructions. However, plain multiply
348 // (low) operations are left as Legal, as there are single-result
349 // instructions for this in x86. Using the two-result multiply instructions
350 // when both high and low results are needed must be arranged by dagcombine.
351 for (unsigned i = 0, e = 4; i != e; ++i) {
353 setOperationAction(ISD::MULHS, VT, Expand);
354 setOperationAction(ISD::MULHU, VT, Expand);
355 setOperationAction(ISD::SDIV, VT, Expand);
356 setOperationAction(ISD::UDIV, VT, Expand);
357 setOperationAction(ISD::SREM, VT, Expand);
358 setOperationAction(ISD::UREM, VT, Expand);
360 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361 setOperationAction(ISD::ADDC, VT, Custom);
362 setOperationAction(ISD::ADDE, VT, Custom);
363 setOperationAction(ISD::SUBC, VT, Custom);
364 setOperationAction(ISD::SUBE, VT, Custom);
367 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
368 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
369 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
370 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
376 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f32 , Expand);
378 setOperationAction(ISD::FREM , MVT::f64 , Expand);
379 setOperationAction(ISD::FREM , MVT::f80 , Expand);
380 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
382 // Promote the i8 variants and force them on up to i32 which has a shorter
384 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
385 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
386 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
387 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
388 if (Subtarget->hasBMI()) {
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
390 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
391 if (Subtarget->is64Bit())
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
394 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
395 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
396 if (Subtarget->is64Bit())
397 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
400 if (Subtarget->hasLZCNT()) {
401 // When promoting the i8 variants, force them to i32 for a shorter
403 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
404 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
405 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
406 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
409 if (Subtarget->is64Bit())
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
412 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
413 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
414 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
416 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
418 if (Subtarget->is64Bit()) {
419 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424 if (Subtarget->hasPOPCNT()) {
425 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
427 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
428 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
429 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
430 if (Subtarget->is64Bit())
431 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
434 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
435 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
437 // These should be promoted to a larger select which is supported.
438 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
439 // X86 wants to expand cmov itself.
440 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
441 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
442 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
443 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
446 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
449 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
450 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
452 if (Subtarget->is64Bit()) {
453 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
456 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
460 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
461 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
462 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
463 if (Subtarget->is64Bit())
464 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
465 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
466 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
467 if (Subtarget->is64Bit()) {
468 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
469 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
470 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
471 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
472 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
474 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
475 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
476 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
477 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
478 if (Subtarget->is64Bit()) {
479 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
480 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
481 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
484 if (Subtarget->hasXMM())
485 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
487 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
488 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
490 // On X86 and X86-64, atomic operations are lowered to locked instructions.
491 // Locked instructions, in turn, have implicit fence semantics (all memory
492 // operations are flushed before issuing the locked instruction, and they
493 // are not buffered), so we can fold away the common pattern of
494 // fence-atomic-fence.
495 setShouldFoldAtomicFences(true);
497 // Expand certain atomics
498 for (unsigned i = 0, e = 4; i != e; ++i) {
500 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
501 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
502 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
505 if (!Subtarget->is64Bit()) {
506 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
513 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
516 if (Subtarget->hasCmpxchg16b()) {
517 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
520 // FIXME - use subtarget debug flags
521 if (!Subtarget->isTargetDarwin() &&
522 !Subtarget->isTargetELF() &&
523 !Subtarget->isTargetCygMing()) {
524 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
527 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
528 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
529 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
530 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
531 if (Subtarget->is64Bit()) {
532 setExceptionPointerRegister(X86::RAX);
533 setExceptionSelectorRegister(X86::RDX);
535 setExceptionPointerRegister(X86::EAX);
536 setExceptionSelectorRegister(X86::EDX);
538 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
539 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
541 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
542 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
544 setOperationAction(ISD::TRAP, MVT::Other, Legal);
546 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
547 setOperationAction(ISD::VASTART , MVT::Other, Custom);
548 setOperationAction(ISD::VAEND , MVT::Other, Expand);
549 if (Subtarget->is64Bit()) {
550 setOperationAction(ISD::VAARG , MVT::Other, Custom);
551 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
553 setOperationAction(ISD::VAARG , MVT::Other, Expand);
554 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
557 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
558 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
560 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
561 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
562 MVT::i64 : MVT::i32, Custom);
563 else if (TM.Options.EnableSegmentedStacks)
564 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565 MVT::i64 : MVT::i32, Custom);
567 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568 MVT::i64 : MVT::i32, Expand);
570 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
571 // f32 and f64 use SSE.
572 // Set up the FP register classes.
573 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
574 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
576 // Use ANDPD to simulate FABS.
577 setOperationAction(ISD::FABS , MVT::f64, Custom);
578 setOperationAction(ISD::FABS , MVT::f32, Custom);
580 // Use XORP to simulate FNEG.
581 setOperationAction(ISD::FNEG , MVT::f64, Custom);
582 setOperationAction(ISD::FNEG , MVT::f32, Custom);
584 // Use ANDPD and ORPD to simulate FCOPYSIGN.
585 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
586 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
588 // Lower this to FGETSIGNx86 plus an AND.
589 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
590 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
592 // We don't support sin/cos/fmod
593 setOperationAction(ISD::FSIN , MVT::f64, Expand);
594 setOperationAction(ISD::FCOS , MVT::f64, Expand);
595 setOperationAction(ISD::FSIN , MVT::f32, Expand);
596 setOperationAction(ISD::FCOS , MVT::f32, Expand);
598 // Expand FP immediates into loads from the stack, except for the special
600 addLegalFPImmediate(APFloat(+0.0)); // xorpd
601 addLegalFPImmediate(APFloat(+0.0f)); // xorps
602 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
603 // Use SSE for f32, x87 for f64.
604 // Set up the FP register classes.
605 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
606 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
608 // Use ANDPS to simulate FABS.
609 setOperationAction(ISD::FABS , MVT::f32, Custom);
611 // Use XORP to simulate FNEG.
612 setOperationAction(ISD::FNEG , MVT::f32, Custom);
614 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
616 // Use ANDPS and ORPS to simulate FCOPYSIGN.
617 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
618 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
620 // We don't support sin/cos/fmod
621 setOperationAction(ISD::FSIN , MVT::f32, Expand);
622 setOperationAction(ISD::FCOS , MVT::f32, Expand);
624 // Special cases we handle for FP constants.
625 addLegalFPImmediate(APFloat(+0.0f)); // xorps
626 addLegalFPImmediate(APFloat(+0.0)); // FLD0
627 addLegalFPImmediate(APFloat(+1.0)); // FLD1
628 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
629 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631 if (!TM.Options.UnsafeFPMath) {
632 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
633 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
635 } else if (!TM.Options.UseSoftFloat) {
636 // f32 and f64 in x87.
637 // Set up the FP register classes.
638 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
639 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
641 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
642 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
643 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
644 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 addLegalFPImmediate(APFloat(+0.0)); // FLD0
651 addLegalFPImmediate(APFloat(+1.0)); // FLD1
652 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
653 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
654 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
655 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
656 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
657 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
660 // We don't support FMA.
661 setOperationAction(ISD::FMA, MVT::f64, Expand);
662 setOperationAction(ISD::FMA, MVT::f32, Expand);
664 // Long double always uses X87.
665 if (!TM.Options.UseSoftFloat) {
666 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
667 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
668 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
670 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
671 addLegalFPImmediate(TmpFlt); // FLD0
673 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
676 APFloat TmpFlt2(+1.0);
677 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
679 addLegalFPImmediate(TmpFlt2); // FLD1
680 TmpFlt2.changeSign();
681 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
684 if (!TM.Options.UnsafeFPMath) {
685 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
686 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
689 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
690 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
691 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
692 setOperationAction(ISD::FRINT, MVT::f80, Expand);
693 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
694 setOperationAction(ISD::FMA, MVT::f80, Expand);
697 // Always use a library call for pow.
698 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
699 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
700 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
702 setOperationAction(ISD::FLOG, MVT::f80, Expand);
703 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
704 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
705 setOperationAction(ISD::FEXP, MVT::f80, Expand);
706 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
708 // First set operation action for all vector types to either promote
709 // (for widening) or expand (for scalarization). Then we will selectively
710 // turn on ones that can be effectively codegen'd.
711 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
712 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
713 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
728 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
731 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
765 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
770 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
771 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
772 setTruncStoreAction((MVT::SimpleValueType)VT,
773 (MVT::SimpleValueType)InnerVT, Expand);
774 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
775 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
776 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
779 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
780 // with -msoft-float, disable use of MMX as well.
781 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
782 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
783 // No operations on x86mmx supported, everything uses intrinsics.
786 // MMX-sized vectors (other than x86mmx) are expected to be expanded
787 // into smaller operations.
788 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
789 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
790 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
791 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
792 setOperationAction(ISD::AND, MVT::v8i8, Expand);
793 setOperationAction(ISD::AND, MVT::v4i16, Expand);
794 setOperationAction(ISD::AND, MVT::v2i32, Expand);
795 setOperationAction(ISD::AND, MVT::v1i64, Expand);
796 setOperationAction(ISD::OR, MVT::v8i8, Expand);
797 setOperationAction(ISD::OR, MVT::v4i16, Expand);
798 setOperationAction(ISD::OR, MVT::v2i32, Expand);
799 setOperationAction(ISD::OR, MVT::v1i64, Expand);
800 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
801 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
802 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
803 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
804 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
805 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
806 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
807 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
808 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
809 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
810 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
811 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
812 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
813 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
814 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
815 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
816 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
818 if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
819 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
821 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
822 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
823 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
824 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
825 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
826 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
827 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
828 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
829 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
830 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
831 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
832 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
835 if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
836 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
838 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
839 // registers cannot be used even for integer operations.
840 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
841 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
842 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
843 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
845 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
846 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
847 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
848 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
849 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
850 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
851 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
852 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
853 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
854 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
855 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
856 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
857 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
858 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
859 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
860 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
862 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
863 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
864 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
865 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
867 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
868 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
873 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
874 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
875 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
876 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
877 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
879 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
881 EVT VT = (MVT::SimpleValueType)i;
882 // Do not attempt to custom lower non-power-of-2 vectors
883 if (!isPowerOf2_32(VT.getVectorNumElements()))
885 // Do not attempt to custom lower non-128-bit vectors
886 if (!VT.is128BitVector())
888 setOperationAction(ISD::BUILD_VECTOR,
889 VT.getSimpleVT().SimpleTy, Custom);
890 setOperationAction(ISD::VECTOR_SHUFFLE,
891 VT.getSimpleVT().SimpleTy, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
893 VT.getSimpleVT().SimpleTy, Custom);
896 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
897 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
898 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
899 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
901 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
903 if (Subtarget->is64Bit()) {
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
908 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
910 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
913 // Do not attempt to promote non-128-bit vectors
914 if (!VT.is128BitVector())
917 setOperationAction(ISD::AND, SVT, Promote);
918 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
919 setOperationAction(ISD::OR, SVT, Promote);
920 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
921 setOperationAction(ISD::XOR, SVT, Promote);
922 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
923 setOperationAction(ISD::LOAD, SVT, Promote);
924 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
925 setOperationAction(ISD::SELECT, SVT, Promote);
926 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
929 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
931 // Custom lower v2i64 and v2f64 selects.
932 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
933 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
934 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
935 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
937 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
938 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
941 if (Subtarget->hasSSE41orAVX()) {
942 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
943 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
944 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
945 setOperationAction(ISD::FRINT, MVT::f32, Legal);
946 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
947 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
948 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
949 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
950 setOperationAction(ISD::FRINT, MVT::f64, Legal);
951 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
953 // FIXME: Do we need to handle scalar-to-vector here?
954 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
956 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
957 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
958 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
959 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
960 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
962 // i8 and i16 vectors are custom , because the source register and source
963 // source memory operand types are not the same width. f32 vectors are
964 // custom since the immediate controlling the insert encodes additional
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
974 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
976 // FIXME: these should be Legal but thats only for the case where
977 // the index is constant. For now custom expand to deal with that.
978 if (Subtarget->is64Bit()) {
979 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
984 if (Subtarget->hasXMMInt()) {
985 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
986 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
988 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
989 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
991 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
992 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
994 if (Subtarget->hasAVX2()) {
995 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
996 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
998 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
999 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1001 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1003 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1004 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1006 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1007 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1009 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1013 if (Subtarget->hasSSE42orAVX())
1014 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1016 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1017 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
1018 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
1019 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
1020 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
1021 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
1022 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
1024 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1025 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1026 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1028 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1029 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1030 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1031 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1032 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1033 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1035 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1036 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1037 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1038 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1039 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1040 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1042 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1043 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1044 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1046 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1047 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1048 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1049 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1050 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1051 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1053 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1054 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1056 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1057 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1059 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1060 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1062 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1063 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1064 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1065 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1067 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1068 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1069 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1071 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1073 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1074 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1076 if (Subtarget->hasAVX2()) {
1077 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1078 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1079 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1080 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1082 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1083 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1084 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1085 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1087 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1088 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1089 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1090 // Don't lower v32i8 because there is no 128-bit byte mul
1092 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1094 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1095 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1097 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1098 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1100 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1102 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1103 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1104 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1105 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1107 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1108 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1109 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1110 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1112 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1113 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1114 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1115 // Don't lower v32i8 because there is no 128-bit byte mul
1117 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1118 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1120 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1121 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1123 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1126 // Custom lower several nodes for 256-bit types.
1127 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1128 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1129 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1132 // Extract subvector is special because the value type
1133 // (result) is 128-bit but the source is 256-bit wide.
1134 if (VT.is128BitVector())
1135 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1137 // Do not attempt to custom lower other non-256-bit vectors
1138 if (!VT.is256BitVector())
1141 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1142 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1143 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1144 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1145 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1146 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1149 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1150 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1151 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1154 // Do not attempt to promote non-256-bit vectors
1155 if (!VT.is256BitVector())
1158 setOperationAction(ISD::AND, SVT, Promote);
1159 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1160 setOperationAction(ISD::OR, SVT, Promote);
1161 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1162 setOperationAction(ISD::XOR, SVT, Promote);
1163 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1164 setOperationAction(ISD::LOAD, SVT, Promote);
1165 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1166 setOperationAction(ISD::SELECT, SVT, Promote);
1167 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1171 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1172 // of this type with custom code.
1173 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1174 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1175 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1179 // We want to custom lower some of our intrinsics.
1180 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1183 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1184 // handle type legalization for these operations here.
1186 // FIXME: We really should do custom legalization for addition and
1187 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1188 // than generic legalization for 64-bit multiplication-with-overflow, though.
1189 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1190 // Add/Sub/Mul with overflow operations are custom lowered.
1192 setOperationAction(ISD::SADDO, VT, Custom);
1193 setOperationAction(ISD::UADDO, VT, Custom);
1194 setOperationAction(ISD::SSUBO, VT, Custom);
1195 setOperationAction(ISD::USUBO, VT, Custom);
1196 setOperationAction(ISD::SMULO, VT, Custom);
1197 setOperationAction(ISD::UMULO, VT, Custom);
1200 // There are no 8-bit 3-address imul/mul instructions
1201 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1202 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1204 if (!Subtarget->is64Bit()) {
1205 // These libcalls are not available in 32-bit.
1206 setLibcallName(RTLIB::SHL_I128, 0);
1207 setLibcallName(RTLIB::SRL_I128, 0);
1208 setLibcallName(RTLIB::SRA_I128, 0);
1211 // We have target-specific dag combine patterns for the following nodes:
1212 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1213 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1214 setTargetDAGCombine(ISD::VSELECT);
1215 setTargetDAGCombine(ISD::SELECT);
1216 setTargetDAGCombine(ISD::SHL);
1217 setTargetDAGCombine(ISD::SRA);
1218 setTargetDAGCombine(ISD::SRL);
1219 setTargetDAGCombine(ISD::OR);
1220 setTargetDAGCombine(ISD::AND);
1221 setTargetDAGCombine(ISD::ADD);
1222 setTargetDAGCombine(ISD::FADD);
1223 setTargetDAGCombine(ISD::FSUB);
1224 setTargetDAGCombine(ISD::SUB);
1225 setTargetDAGCombine(ISD::LOAD);
1226 setTargetDAGCombine(ISD::STORE);
1227 setTargetDAGCombine(ISD::ZERO_EXTEND);
1228 setTargetDAGCombine(ISD::SINT_TO_FP);
1229 if (Subtarget->is64Bit())
1230 setTargetDAGCombine(ISD::MUL);
1231 if (Subtarget->hasBMI())
1232 setTargetDAGCombine(ISD::XOR);
1234 computeRegisterProperties();
1236 // On Darwin, -Os means optimize for size without hurting performance,
1237 // do not reduce the limit.
1238 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1239 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1240 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1241 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1242 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1243 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1244 setPrefLoopAlignment(4); // 2^4 bytes.
1245 benefitFromCodePlacementOpt = true;
1247 setPrefFunctionAlignment(4); // 2^4 bytes.
1251 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1252 if (!VT.isVector()) return MVT::i8;
1253 return VT.changeVectorElementTypeToInteger();
1257 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1258 /// the desired ByVal argument alignment.
1259 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1262 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1263 if (VTy->getBitWidth() == 128)
1265 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1266 unsigned EltAlign = 0;
1267 getMaxByValAlign(ATy->getElementType(), EltAlign);
1268 if (EltAlign > MaxAlign)
1269 MaxAlign = EltAlign;
1270 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1271 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1272 unsigned EltAlign = 0;
1273 getMaxByValAlign(STy->getElementType(i), EltAlign);
1274 if (EltAlign > MaxAlign)
1275 MaxAlign = EltAlign;
1283 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1284 /// function arguments in the caller parameter area. For X86, aggregates
1285 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1286 /// are at 4-byte boundaries.
1287 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1288 if (Subtarget->is64Bit()) {
1289 // Max of 8 and alignment of type.
1290 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1297 if (Subtarget->hasXMM())
1298 getMaxByValAlign(Ty, Align);
1302 /// getOptimalMemOpType - Returns the target specific optimal type for load
1303 /// and store operations as a result of memset, memcpy, and memmove
1304 /// lowering. If DstAlign is zero that means it's safe to destination
1305 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1306 /// means there isn't a need to check it against alignment requirement,
1307 /// probably because the source does not need to be loaded. If
1308 /// 'IsZeroVal' is true, that means it's safe to return a
1309 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1310 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1311 /// constant so it does not need to be loaded.
1312 /// It returns EVT::Other if the type should be determined using generic
1313 /// target-independent logic.
1315 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1316 unsigned DstAlign, unsigned SrcAlign,
1319 MachineFunction &MF) const {
1320 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1321 // linux. This is because the stack realignment code can't handle certain
1322 // cases like PR2962. This should be removed when PR2962 is fixed.
1323 const Function *F = MF.getFunction();
1325 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1327 (Subtarget->isUnalignedMemAccessFast() ||
1328 ((DstAlign == 0 || DstAlign >= 16) &&
1329 (SrcAlign == 0 || SrcAlign >= 16))) &&
1330 Subtarget->getStackAlignment() >= 16) {
1331 if (Subtarget->hasAVX() &&
1332 Subtarget->getStackAlignment() >= 32)
1334 if (Subtarget->hasXMMInt())
1336 if (Subtarget->hasXMM())
1338 } else if (!MemcpyStrSrc && Size >= 8 &&
1339 !Subtarget->is64Bit() &&
1340 Subtarget->getStackAlignment() >= 8 &&
1341 Subtarget->hasXMMInt()) {
1342 // Do not use f64 to lower memcpy if source is string constant. It's
1343 // better to use i32 to avoid the loads.
1347 if (Subtarget->is64Bit() && Size >= 8)
1352 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1353 /// current function. The returned value is a member of the
1354 /// MachineJumpTableInfo::JTEntryKind enum.
1355 unsigned X86TargetLowering::getJumpTableEncoding() const {
1356 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1358 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1359 Subtarget->isPICStyleGOT())
1360 return MachineJumpTableInfo::EK_Custom32;
1362 // Otherwise, use the normal jump table encoding heuristics.
1363 return TargetLowering::getJumpTableEncoding();
1367 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1368 const MachineBasicBlock *MBB,
1369 unsigned uid,MCContext &Ctx) const{
1370 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1371 Subtarget->isPICStyleGOT());
1372 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1374 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1375 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1378 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1380 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1381 SelectionDAG &DAG) const {
1382 if (!Subtarget->is64Bit())
1383 // This doesn't have DebugLoc associated with it, but is not really the
1384 // same as a Register.
1385 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1389 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1390 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1392 const MCExpr *X86TargetLowering::
1393 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1394 MCContext &Ctx) const {
1395 // X86-64 uses RIP relative addressing based on the jump table label.
1396 if (Subtarget->isPICStyleRIPRel())
1397 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1399 // Otherwise, the reference is relative to the PIC base.
1400 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1403 // FIXME: Why this routine is here? Move to RegInfo!
1404 std::pair<const TargetRegisterClass*, uint8_t>
1405 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1406 const TargetRegisterClass *RRC = 0;
1408 switch (VT.getSimpleVT().SimpleTy) {
1410 return TargetLowering::findRepresentativeClass(VT);
1411 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1412 RRC = (Subtarget->is64Bit()
1413 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1416 RRC = X86::VR64RegisterClass;
1418 case MVT::f32: case MVT::f64:
1419 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1420 case MVT::v4f32: case MVT::v2f64:
1421 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1423 RRC = X86::VR128RegisterClass;
1426 return std::make_pair(RRC, Cost);
1429 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1430 unsigned &Offset) const {
1431 if (!Subtarget->isTargetLinux())
1434 if (Subtarget->is64Bit()) {
1435 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1437 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1450 //===----------------------------------------------------------------------===//
1451 // Return Value Calling Convention Implementation
1452 //===----------------------------------------------------------------------===//
1454 #include "X86GenCallingConv.inc"
1457 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1458 MachineFunction &MF, bool isVarArg,
1459 const SmallVectorImpl<ISD::OutputArg> &Outs,
1460 LLVMContext &Context) const {
1461 SmallVector<CCValAssign, 16> RVLocs;
1462 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1464 return CCInfo.CheckReturn(Outs, RetCC_X86);
1468 X86TargetLowering::LowerReturn(SDValue Chain,
1469 CallingConv::ID CallConv, bool isVarArg,
1470 const SmallVectorImpl<ISD::OutputArg> &Outs,
1471 const SmallVectorImpl<SDValue> &OutVals,
1472 DebugLoc dl, SelectionDAG &DAG) const {
1473 MachineFunction &MF = DAG.getMachineFunction();
1474 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1476 SmallVector<CCValAssign, 16> RVLocs;
1477 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1478 RVLocs, *DAG.getContext());
1479 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1481 // Add the regs to the liveout set for the function.
1482 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1483 for (unsigned i = 0; i != RVLocs.size(); ++i)
1484 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1485 MRI.addLiveOut(RVLocs[i].getLocReg());
1489 SmallVector<SDValue, 6> RetOps;
1490 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1491 // Operand #1 = Bytes To Pop
1492 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1495 // Copy the result values into the output registers.
1496 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1497 CCValAssign &VA = RVLocs[i];
1498 assert(VA.isRegLoc() && "Can only return in registers!");
1499 SDValue ValToCopy = OutVals[i];
1500 EVT ValVT = ValToCopy.getValueType();
1502 // If this is x86-64, and we disabled SSE, we can't return FP values,
1503 // or SSE or MMX vectors.
1504 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1505 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1506 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1507 report_fatal_error("SSE register return with SSE disabled");
1509 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1510 // llvm-gcc has never done it right and no one has noticed, so this
1511 // should be OK for now.
1512 if (ValVT == MVT::f64 &&
1513 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1514 report_fatal_error("SSE2 register return with SSE2 disabled");
1516 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1517 // the RET instruction and handled by the FP Stackifier.
1518 if (VA.getLocReg() == X86::ST0 ||
1519 VA.getLocReg() == X86::ST1) {
1520 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1521 // change the value to the FP stack register class.
1522 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1523 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1524 RetOps.push_back(ValToCopy);
1525 // Don't emit a copytoreg.
1529 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1530 // which is returned in RAX / RDX.
1531 if (Subtarget->is64Bit()) {
1532 if (ValVT == MVT::x86mmx) {
1533 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1534 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1535 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1537 // If we don't have SSE2 available, convert to v4f32 so the generated
1538 // register is legal.
1539 if (!Subtarget->hasXMMInt())
1540 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1545 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1546 Flag = Chain.getValue(1);
1549 // The x86-64 ABI for returning structs by value requires that we copy
1550 // the sret argument into %rax for the return. We saved the argument into
1551 // a virtual register in the entry block, so now we copy the value out
1553 if (Subtarget->is64Bit() &&
1554 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1555 MachineFunction &MF = DAG.getMachineFunction();
1556 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1557 unsigned Reg = FuncInfo->getSRetReturnReg();
1559 "SRetReturnReg should have been set in LowerFormalArguments().");
1560 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1562 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1563 Flag = Chain.getValue(1);
1565 // RAX now acts like a return value.
1566 MRI.addLiveOut(X86::RAX);
1569 RetOps[0] = Chain; // Update chain.
1571 // Add the flag if we have it.
1573 RetOps.push_back(Flag);
1575 return DAG.getNode(X86ISD::RET_FLAG, dl,
1576 MVT::Other, &RetOps[0], RetOps.size());
1579 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1580 if (N->getNumValues() != 1)
1582 if (!N->hasNUsesOfValue(1, 0))
1585 SDNode *Copy = *N->use_begin();
1586 if (Copy->getOpcode() != ISD::CopyToReg &&
1587 Copy->getOpcode() != ISD::FP_EXTEND)
1590 bool HasRet = false;
1591 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1593 if (UI->getOpcode() != X86ISD::RET_FLAG)
1602 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1603 ISD::NodeType ExtendKind) const {
1605 // TODO: Is this also valid on 32-bit?
1606 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1607 ReturnMVT = MVT::i8;
1609 ReturnMVT = MVT::i32;
1611 EVT MinVT = getRegisterType(Context, ReturnMVT);
1612 return VT.bitsLT(MinVT) ? MinVT : VT;
1615 /// LowerCallResult - Lower the result values of a call into the
1616 /// appropriate copies out of appropriate physical registers.
1619 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1620 CallingConv::ID CallConv, bool isVarArg,
1621 const SmallVectorImpl<ISD::InputArg> &Ins,
1622 DebugLoc dl, SelectionDAG &DAG,
1623 SmallVectorImpl<SDValue> &InVals) const {
1625 // Assign locations to each value returned by this call.
1626 SmallVector<CCValAssign, 16> RVLocs;
1627 bool Is64Bit = Subtarget->is64Bit();
1628 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1629 getTargetMachine(), RVLocs, *DAG.getContext());
1630 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1632 // Copy all of the result registers out of their specified physreg.
1633 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1634 CCValAssign &VA = RVLocs[i];
1635 EVT CopyVT = VA.getValVT();
1637 // If this is x86-64, and we disabled SSE, we can't return FP values
1638 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1639 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1640 report_fatal_error("SSE register return with SSE disabled");
1645 // If this is a call to a function that returns an fp value on the floating
1646 // point stack, we must guarantee the the value is popped from the stack, so
1647 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1648 // if the return value is not used. We use the FpPOP_RETVAL instruction
1650 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1651 // If we prefer to use the value in xmm registers, copy it out as f80 and
1652 // use a truncate to move it from fp stack reg to xmm reg.
1653 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1654 SDValue Ops[] = { Chain, InFlag };
1655 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1656 MVT::Other, MVT::Glue, Ops, 2), 1);
1657 Val = Chain.getValue(0);
1659 // Round the f80 to the right size, which also moves it to the appropriate
1661 if (CopyVT != VA.getValVT())
1662 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1663 // This truncation won't change the value.
1664 DAG.getIntPtrConstant(1));
1666 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1667 CopyVT, InFlag).getValue(1);
1668 Val = Chain.getValue(0);
1670 InFlag = Chain.getValue(2);
1671 InVals.push_back(Val);
1678 //===----------------------------------------------------------------------===//
1679 // C & StdCall & Fast Calling Convention implementation
1680 //===----------------------------------------------------------------------===//
1681 // StdCall calling convention seems to be standard for many Windows' API
1682 // routines and around. It differs from C calling convention just a little:
1683 // callee should clean up the stack, not caller. Symbols should be also
1684 // decorated in some fancy way :) It doesn't support any vector arguments.
1685 // For info on fast calling convention see Fast Calling Convention (tail call)
1686 // implementation LowerX86_32FastCCCallTo.
1688 /// CallIsStructReturn - Determines whether a call uses struct return
1690 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1694 return Outs[0].Flags.isSRet();
1697 /// ArgsAreStructReturn - Determines whether a function uses struct
1698 /// return semantics.
1700 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1704 return Ins[0].Flags.isSRet();
1707 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1708 /// by "Src" to address "Dst" with size and alignment information specified by
1709 /// the specific parameter attribute. The copy will be passed as a byval
1710 /// function parameter.
1712 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1713 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1715 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1717 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1718 /*isVolatile*/false, /*AlwaysInline=*/true,
1719 MachinePointerInfo(), MachinePointerInfo());
1722 /// IsTailCallConvention - Return true if the calling convention is one that
1723 /// supports tail call optimization.
1724 static bool IsTailCallConvention(CallingConv::ID CC) {
1725 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1728 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1729 if (!CI->isTailCall())
1733 CallingConv::ID CalleeCC = CS.getCallingConv();
1734 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1740 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1741 /// a tailcall target by changing its ABI.
1742 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1743 bool GuaranteedTailCallOpt) {
1744 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1748 X86TargetLowering::LowerMemArgument(SDValue Chain,
1749 CallingConv::ID CallConv,
1750 const SmallVectorImpl<ISD::InputArg> &Ins,
1751 DebugLoc dl, SelectionDAG &DAG,
1752 const CCValAssign &VA,
1753 MachineFrameInfo *MFI,
1755 // Create the nodes corresponding to a load from this parameter slot.
1756 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1757 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1758 getTargetMachine().Options.GuaranteedTailCallOpt);
1759 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1762 // If value is passed by pointer we have address passed instead of the value
1764 if (VA.getLocInfo() == CCValAssign::Indirect)
1765 ValVT = VA.getLocVT();
1767 ValVT = VA.getValVT();
1769 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1770 // changed with more analysis.
1771 // In case of tail call optimization mark all arguments mutable. Since they
1772 // could be overwritten by lowering of arguments in case of a tail call.
1773 if (Flags.isByVal()) {
1774 unsigned Bytes = Flags.getByValSize();
1775 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1776 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1777 return DAG.getFrameIndex(FI, getPointerTy());
1779 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1780 VA.getLocMemOffset(), isImmutable);
1781 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1782 return DAG.getLoad(ValVT, dl, Chain, FIN,
1783 MachinePointerInfo::getFixedStack(FI),
1784 false, false, false, 0);
1789 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1790 CallingConv::ID CallConv,
1792 const SmallVectorImpl<ISD::InputArg> &Ins,
1795 SmallVectorImpl<SDValue> &InVals)
1797 MachineFunction &MF = DAG.getMachineFunction();
1798 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1800 const Function* Fn = MF.getFunction();
1801 if (Fn->hasExternalLinkage() &&
1802 Subtarget->isTargetCygMing() &&
1803 Fn->getName() == "main")
1804 FuncInfo->setForceFramePointer(true);
1806 MachineFrameInfo *MFI = MF.getFrameInfo();
1807 bool Is64Bit = Subtarget->is64Bit();
1808 bool IsWin64 = Subtarget->isTargetWin64();
1810 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1811 "Var args not supported with calling convention fastcc or ghc");
1813 // Assign locations to all of the incoming arguments.
1814 SmallVector<CCValAssign, 16> ArgLocs;
1815 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1816 ArgLocs, *DAG.getContext());
1818 // Allocate shadow area for Win64
1820 CCInfo.AllocateStack(32, 8);
1823 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1825 unsigned LastVal = ~0U;
1827 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1828 CCValAssign &VA = ArgLocs[i];
1829 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1831 assert(VA.getValNo() != LastVal &&
1832 "Don't support value assigned to multiple locs yet");
1834 LastVal = VA.getValNo();
1836 if (VA.isRegLoc()) {
1837 EVT RegVT = VA.getLocVT();
1838 TargetRegisterClass *RC = NULL;
1839 if (RegVT == MVT::i32)
1840 RC = X86::GR32RegisterClass;
1841 else if (Is64Bit && RegVT == MVT::i64)
1842 RC = X86::GR64RegisterClass;
1843 else if (RegVT == MVT::f32)
1844 RC = X86::FR32RegisterClass;
1845 else if (RegVT == MVT::f64)
1846 RC = X86::FR64RegisterClass;
1847 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1848 RC = X86::VR256RegisterClass;
1849 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1850 RC = X86::VR128RegisterClass;
1851 else if (RegVT == MVT::x86mmx)
1852 RC = X86::VR64RegisterClass;
1854 llvm_unreachable("Unknown argument type!");
1856 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1857 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1859 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1860 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1862 if (VA.getLocInfo() == CCValAssign::SExt)
1863 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1864 DAG.getValueType(VA.getValVT()));
1865 else if (VA.getLocInfo() == CCValAssign::ZExt)
1866 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1867 DAG.getValueType(VA.getValVT()));
1868 else if (VA.getLocInfo() == CCValAssign::BCvt)
1869 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1871 if (VA.isExtInLoc()) {
1872 // Handle MMX values passed in XMM regs.
1873 if (RegVT.isVector()) {
1874 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1877 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1880 assert(VA.isMemLoc());
1881 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1884 // If value is passed via pointer - do a load.
1885 if (VA.getLocInfo() == CCValAssign::Indirect)
1886 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1887 MachinePointerInfo(), false, false, false, 0);
1889 InVals.push_back(ArgValue);
1892 // The x86-64 ABI for returning structs by value requires that we copy
1893 // the sret argument into %rax for the return. Save the argument into
1894 // a virtual register so that we can access it from the return points.
1895 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1896 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1897 unsigned Reg = FuncInfo->getSRetReturnReg();
1899 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1900 FuncInfo->setSRetReturnReg(Reg);
1902 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1903 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1906 unsigned StackSize = CCInfo.getNextStackOffset();
1907 // Align stack specially for tail calls.
1908 if (FuncIsMadeTailCallSafe(CallConv,
1909 MF.getTarget().Options.GuaranteedTailCallOpt))
1910 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1912 // If the function takes variable number of arguments, make a frame index for
1913 // the start of the first vararg value... for expansion of llvm.va_start.
1915 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1916 CallConv != CallingConv::X86_ThisCall)) {
1917 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1920 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1922 // FIXME: We should really autogenerate these arrays
1923 static const unsigned GPR64ArgRegsWin64[] = {
1924 X86::RCX, X86::RDX, X86::R8, X86::R9
1926 static const unsigned GPR64ArgRegs64Bit[] = {
1927 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1929 static const unsigned XMMArgRegs64Bit[] = {
1930 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1931 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1933 const unsigned *GPR64ArgRegs;
1934 unsigned NumXMMRegs = 0;
1937 // The XMM registers which might contain var arg parameters are shadowed
1938 // in their paired GPR. So we only need to save the GPR to their home
1940 TotalNumIntRegs = 4;
1941 GPR64ArgRegs = GPR64ArgRegsWin64;
1943 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1944 GPR64ArgRegs = GPR64ArgRegs64Bit;
1946 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1949 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1952 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1953 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1954 "SSE register cannot be used when SSE is disabled!");
1955 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1956 NoImplicitFloatOps) &&
1957 "SSE register cannot be used when SSE is disabled!");
1958 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1959 !Subtarget->hasXMM())
1960 // Kernel mode asks for SSE to be disabled, so don't push them
1962 TotalNumXMMRegs = 0;
1965 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1966 // Get to the caller-allocated home save location. Add 8 to account
1967 // for the return address.
1968 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1969 FuncInfo->setRegSaveFrameIndex(
1970 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1971 // Fixup to set vararg frame on shadow area (4 x i64).
1973 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1975 // For X86-64, if there are vararg parameters that are passed via
1976 // registers, then we must store them to their spots on the stack so
1977 // they may be loaded by deferencing the result of va_next.
1978 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1979 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1980 FuncInfo->setRegSaveFrameIndex(
1981 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1985 // Store the integer parameter registers.
1986 SmallVector<SDValue, 8> MemOps;
1987 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1989 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1990 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1991 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1992 DAG.getIntPtrConstant(Offset));
1993 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1994 X86::GR64RegisterClass);
1995 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1997 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1998 MachinePointerInfo::getFixedStack(
1999 FuncInfo->getRegSaveFrameIndex(), Offset),
2001 MemOps.push_back(Store);
2005 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2006 // Now store the XMM (fp + vector) parameter registers.
2007 SmallVector<SDValue, 11> SaveXMMOps;
2008 SaveXMMOps.push_back(Chain);
2010 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
2011 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2012 SaveXMMOps.push_back(ALVal);
2014 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2015 FuncInfo->getRegSaveFrameIndex()));
2016 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2017 FuncInfo->getVarArgsFPOffset()));
2019 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2020 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2021 X86::VR128RegisterClass);
2022 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2023 SaveXMMOps.push_back(Val);
2025 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2027 &SaveXMMOps[0], SaveXMMOps.size()));
2030 if (!MemOps.empty())
2031 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2032 &MemOps[0], MemOps.size());
2036 // Some CCs need callee pop.
2037 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2038 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2039 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2041 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2042 // If this is an sret function, the return should pop the hidden pointer.
2043 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2044 FuncInfo->setBytesToPopOnReturn(4);
2048 // RegSaveFrameIndex is X86-64 only.
2049 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2050 if (CallConv == CallingConv::X86_FastCall ||
2051 CallConv == CallingConv::X86_ThisCall)
2052 // fastcc functions can't have varargs.
2053 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2056 FuncInfo->setArgumentStackSize(StackSize);
2062 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2063 SDValue StackPtr, SDValue Arg,
2064 DebugLoc dl, SelectionDAG &DAG,
2065 const CCValAssign &VA,
2066 ISD::ArgFlagsTy Flags) const {
2067 unsigned LocMemOffset = VA.getLocMemOffset();
2068 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2069 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2070 if (Flags.isByVal())
2071 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2073 return DAG.getStore(Chain, dl, Arg, PtrOff,
2074 MachinePointerInfo::getStack(LocMemOffset),
2078 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2079 /// optimization is performed and it is required.
2081 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2082 SDValue &OutRetAddr, SDValue Chain,
2083 bool IsTailCall, bool Is64Bit,
2084 int FPDiff, DebugLoc dl) const {
2085 // Adjust the Return address stack slot.
2086 EVT VT = getPointerTy();
2087 OutRetAddr = getReturnAddressFrameIndex(DAG);
2089 // Load the "old" Return address.
2090 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2091 false, false, false, 0);
2092 return SDValue(OutRetAddr.getNode(), 1);
2095 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2096 /// optimization is performed and it is required (FPDiff!=0).
2098 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2099 SDValue Chain, SDValue RetAddrFrIdx,
2100 bool Is64Bit, int FPDiff, DebugLoc dl) {
2101 // Store the return address to the appropriate stack slot.
2102 if (!FPDiff) return Chain;
2103 // Calculate the new stack slot for the return address.
2104 int SlotSize = Is64Bit ? 8 : 4;
2105 int NewReturnAddrFI =
2106 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2107 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2108 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2109 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2110 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2116 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2117 CallingConv::ID CallConv, bool isVarArg,
2119 const SmallVectorImpl<ISD::OutputArg> &Outs,
2120 const SmallVectorImpl<SDValue> &OutVals,
2121 const SmallVectorImpl<ISD::InputArg> &Ins,
2122 DebugLoc dl, SelectionDAG &DAG,
2123 SmallVectorImpl<SDValue> &InVals) const {
2124 MachineFunction &MF = DAG.getMachineFunction();
2125 bool Is64Bit = Subtarget->is64Bit();
2126 bool IsWin64 = Subtarget->isTargetWin64();
2127 bool IsStructRet = CallIsStructReturn(Outs);
2128 bool IsSibcall = false;
2131 // Check if it's really possible to do a tail call.
2132 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2133 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2134 Outs, OutVals, Ins, DAG);
2136 // Sibcalls are automatically detected tailcalls which do not require
2138 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2145 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2146 "Var args not supported with calling convention fastcc or ghc");
2148 // Analyze operands of the call, assigning locations to each operand.
2149 SmallVector<CCValAssign, 16> ArgLocs;
2150 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2151 ArgLocs, *DAG.getContext());
2153 // Allocate shadow area for Win64
2155 CCInfo.AllocateStack(32, 8);
2158 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2160 // Get a count of how many bytes are to be pushed on the stack.
2161 unsigned NumBytes = CCInfo.getNextStackOffset();
2163 // This is a sibcall. The memory operands are available in caller's
2164 // own caller's stack.
2166 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2167 IsTailCallConvention(CallConv))
2168 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2171 if (isTailCall && !IsSibcall) {
2172 // Lower arguments at fp - stackoffset + fpdiff.
2173 unsigned NumBytesCallerPushed =
2174 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2175 FPDiff = NumBytesCallerPushed - NumBytes;
2177 // Set the delta of movement of the returnaddr stackslot.
2178 // But only set if delta is greater than previous delta.
2179 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2180 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2184 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2186 SDValue RetAddrFrIdx;
2187 // Load return address for tail calls.
2188 if (isTailCall && FPDiff)
2189 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2190 Is64Bit, FPDiff, dl);
2192 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2193 SmallVector<SDValue, 8> MemOpChains;
2196 // Walk the register/memloc assignments, inserting copies/loads. In the case
2197 // of tail call optimization arguments are handle later.
2198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2199 CCValAssign &VA = ArgLocs[i];
2200 EVT RegVT = VA.getLocVT();
2201 SDValue Arg = OutVals[i];
2202 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2203 bool isByVal = Flags.isByVal();
2205 // Promote the value if needed.
2206 switch (VA.getLocInfo()) {
2207 default: llvm_unreachable("Unknown loc info!");
2208 case CCValAssign::Full: break;
2209 case CCValAssign::SExt:
2210 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2212 case CCValAssign::ZExt:
2213 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2215 case CCValAssign::AExt:
2216 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2217 // Special case: passing MMX values in XMM registers.
2218 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2219 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2220 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2222 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2224 case CCValAssign::BCvt:
2225 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2227 case CCValAssign::Indirect: {
2228 // Store the argument.
2229 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2230 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2231 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2232 MachinePointerInfo::getFixedStack(FI),
2239 if (VA.isRegLoc()) {
2240 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2241 if (isVarArg && IsWin64) {
2242 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2243 // shadow reg if callee is a varargs function.
2244 unsigned ShadowReg = 0;
2245 switch (VA.getLocReg()) {
2246 case X86::XMM0: ShadowReg = X86::RCX; break;
2247 case X86::XMM1: ShadowReg = X86::RDX; break;
2248 case X86::XMM2: ShadowReg = X86::R8; break;
2249 case X86::XMM3: ShadowReg = X86::R9; break;
2252 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2254 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2255 assert(VA.isMemLoc());
2256 if (StackPtr.getNode() == 0)
2257 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2258 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2259 dl, DAG, VA, Flags));
2263 if (!MemOpChains.empty())
2264 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2265 &MemOpChains[0], MemOpChains.size());
2267 // Build a sequence of copy-to-reg nodes chained together with token chain
2268 // and flag operands which copy the outgoing args into registers.
2270 // Tail call byval lowering might overwrite argument registers so in case of
2271 // tail call optimization the copies to registers are lowered later.
2273 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2274 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2275 RegsToPass[i].second, InFlag);
2276 InFlag = Chain.getValue(1);
2279 if (Subtarget->isPICStyleGOT()) {
2280 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2283 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2284 DAG.getNode(X86ISD::GlobalBaseReg,
2285 DebugLoc(), getPointerTy()),
2287 InFlag = Chain.getValue(1);
2289 // If we are tail calling and generating PIC/GOT style code load the
2290 // address of the callee into ECX. The value in ecx is used as target of
2291 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2292 // for tail calls on PIC/GOT architectures. Normally we would just put the
2293 // address of GOT into ebx and then call target@PLT. But for tail calls
2294 // ebx would be restored (since ebx is callee saved) before jumping to the
2297 // Note: The actual moving to ECX is done further down.
2298 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2299 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2300 !G->getGlobal()->hasProtectedVisibility())
2301 Callee = LowerGlobalAddress(Callee, DAG);
2302 else if (isa<ExternalSymbolSDNode>(Callee))
2303 Callee = LowerExternalSymbol(Callee, DAG);
2307 if (Is64Bit && isVarArg && !IsWin64) {
2308 // From AMD64 ABI document:
2309 // For calls that may call functions that use varargs or stdargs
2310 // (prototype-less calls or calls to functions containing ellipsis (...) in
2311 // the declaration) %al is used as hidden argument to specify the number
2312 // of SSE registers used. The contents of %al do not need to match exactly
2313 // the number of registers, but must be an ubound on the number of SSE
2314 // registers used and is in the range 0 - 8 inclusive.
2316 // Count the number of XMM registers allocated.
2317 static const unsigned XMMArgRegs[] = {
2318 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2319 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2321 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2322 assert((Subtarget->hasXMM() || !NumXMMRegs)
2323 && "SSE registers cannot be used when SSE is disabled");
2325 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2326 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2327 InFlag = Chain.getValue(1);
2331 // For tail calls lower the arguments to the 'real' stack slot.
2333 // Force all the incoming stack arguments to be loaded from the stack
2334 // before any new outgoing arguments are stored to the stack, because the
2335 // outgoing stack slots may alias the incoming argument stack slots, and
2336 // the alias isn't otherwise explicit. This is slightly more conservative
2337 // than necessary, because it means that each store effectively depends
2338 // on every argument instead of just those arguments it would clobber.
2339 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2341 SmallVector<SDValue, 8> MemOpChains2;
2344 // Do not flag preceding copytoreg stuff together with the following stuff.
2346 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2347 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2348 CCValAssign &VA = ArgLocs[i];
2351 assert(VA.isMemLoc());
2352 SDValue Arg = OutVals[i];
2353 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2354 // Create frame index.
2355 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2356 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2357 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2358 FIN = DAG.getFrameIndex(FI, getPointerTy());
2360 if (Flags.isByVal()) {
2361 // Copy relative to framepointer.
2362 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2363 if (StackPtr.getNode() == 0)
2364 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2366 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2368 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2372 // Store relative to framepointer.
2373 MemOpChains2.push_back(
2374 DAG.getStore(ArgChain, dl, Arg, FIN,
2375 MachinePointerInfo::getFixedStack(FI),
2381 if (!MemOpChains2.empty())
2382 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2383 &MemOpChains2[0], MemOpChains2.size());
2385 // Copy arguments to their registers.
2386 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2387 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2388 RegsToPass[i].second, InFlag);
2389 InFlag = Chain.getValue(1);
2393 // Store the return address to the appropriate stack slot.
2394 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2398 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2399 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2400 // In the 64-bit large code model, we have to make all calls
2401 // through a register, since the call instruction's 32-bit
2402 // pc-relative offset may not be large enough to hold the whole
2404 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2405 // If the callee is a GlobalAddress node (quite common, every direct call
2406 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2409 // We should use extra load for direct calls to dllimported functions in
2411 const GlobalValue *GV = G->getGlobal();
2412 if (!GV->hasDLLImportLinkage()) {
2413 unsigned char OpFlags = 0;
2414 bool ExtraLoad = false;
2415 unsigned WrapperKind = ISD::DELETED_NODE;
2417 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2418 // external symbols most go through the PLT in PIC mode. If the symbol
2419 // has hidden or protected visibility, or if it is static or local, then
2420 // we don't need to use the PLT - we can directly call it.
2421 if (Subtarget->isTargetELF() &&
2422 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2423 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2424 OpFlags = X86II::MO_PLT;
2425 } else if (Subtarget->isPICStyleStubAny() &&
2426 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2427 (!Subtarget->getTargetTriple().isMacOSX() ||
2428 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429 // PC-relative references to external symbols should go through $stub,
2430 // unless we're building with the leopard linker or later, which
2431 // automatically synthesizes these stubs.
2432 OpFlags = X86II::MO_DARWIN_STUB;
2433 } else if (Subtarget->isPICStyleRIPRel() &&
2434 isa<Function>(GV) &&
2435 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2436 // If the function is marked as non-lazy, generate an indirect call
2437 // which loads from the GOT directly. This avoids runtime overhead
2438 // at the cost of eager binding (and one extra byte of encoding).
2439 OpFlags = X86II::MO_GOTPCREL;
2440 WrapperKind = X86ISD::WrapperRIP;
2444 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2445 G->getOffset(), OpFlags);
2447 // Add a wrapper if needed.
2448 if (WrapperKind != ISD::DELETED_NODE)
2449 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2450 // Add extra indirection if needed.
2452 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2453 MachinePointerInfo::getGOT(),
2454 false, false, false, 0);
2456 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2457 unsigned char OpFlags = 0;
2459 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2460 // external symbols should go through the PLT.
2461 if (Subtarget->isTargetELF() &&
2462 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2463 OpFlags = X86II::MO_PLT;
2464 } else if (Subtarget->isPICStyleStubAny() &&
2465 (!Subtarget->getTargetTriple().isMacOSX() ||
2466 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2467 // PC-relative references to external symbols should go through $stub,
2468 // unless we're building with the leopard linker or later, which
2469 // automatically synthesizes these stubs.
2470 OpFlags = X86II::MO_DARWIN_STUB;
2473 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2477 // Returns a chain & a flag for retval copy to use.
2478 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2479 SmallVector<SDValue, 8> Ops;
2481 if (!IsSibcall && isTailCall) {
2482 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2483 DAG.getIntPtrConstant(0, true), InFlag);
2484 InFlag = Chain.getValue(1);
2487 Ops.push_back(Chain);
2488 Ops.push_back(Callee);
2491 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2493 // Add argument registers to the end of the list so that they are known live
2495 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2496 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2497 RegsToPass[i].second.getValueType()));
2499 // Add an implicit use GOT pointer in EBX.
2500 if (!isTailCall && Subtarget->isPICStyleGOT())
2501 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2503 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2504 if (Is64Bit && isVarArg && !IsWin64)
2505 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2507 if (InFlag.getNode())
2508 Ops.push_back(InFlag);
2512 //// If this is the first return lowered for this function, add the regs
2513 //// to the liveout set for the function.
2514 // This isn't right, although it's probably harmless on x86; liveouts
2515 // should be computed from returns not tail calls. Consider a void
2516 // function making a tail call to a function returning int.
2517 return DAG.getNode(X86ISD::TC_RETURN, dl,
2518 NodeTys, &Ops[0], Ops.size());
2521 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2522 InFlag = Chain.getValue(1);
2524 // Create the CALLSEQ_END node.
2525 unsigned NumBytesForCalleeToPush;
2526 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2527 getTargetMachine().Options.GuaranteedTailCallOpt))
2528 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2529 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2530 // If this is a call to a struct-return function, the callee
2531 // pops the hidden struct pointer, so we have to push it back.
2532 // This is common for Darwin/X86, Linux & Mingw32 targets.
2533 NumBytesForCalleeToPush = 4;
2535 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2537 // Returns a flag for retval copy to use.
2539 Chain = DAG.getCALLSEQ_END(Chain,
2540 DAG.getIntPtrConstant(NumBytes, true),
2541 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2544 InFlag = Chain.getValue(1);
2547 // Handle result values, copying them out of physregs into vregs that we
2549 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2550 Ins, dl, DAG, InVals);
2554 //===----------------------------------------------------------------------===//
2555 // Fast Calling Convention (tail call) implementation
2556 //===----------------------------------------------------------------------===//
2558 // Like std call, callee cleans arguments, convention except that ECX is
2559 // reserved for storing the tail called function address. Only 2 registers are
2560 // free for argument passing (inreg). Tail call optimization is performed
2562 // * tailcallopt is enabled
2563 // * caller/callee are fastcc
2564 // On X86_64 architecture with GOT-style position independent code only local
2565 // (within module) calls are supported at the moment.
2566 // To keep the stack aligned according to platform abi the function
2567 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2568 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2569 // If a tail called function callee has more arguments than the caller the
2570 // caller needs to make sure that there is room to move the RETADDR to. This is
2571 // achieved by reserving an area the size of the argument delta right after the
2572 // original REtADDR, but before the saved framepointer or the spilled registers
2573 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2585 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2586 /// for a 16 byte align requirement.
2588 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2589 SelectionDAG& DAG) const {
2590 MachineFunction &MF = DAG.getMachineFunction();
2591 const TargetMachine &TM = MF.getTarget();
2592 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2593 unsigned StackAlignment = TFI.getStackAlignment();
2594 uint64_t AlignMask = StackAlignment - 1;
2595 int64_t Offset = StackSize;
2596 uint64_t SlotSize = TD->getPointerSize();
2597 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2598 // Number smaller than 12 so just add the difference.
2599 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2601 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2602 Offset = ((~AlignMask) & Offset) + StackAlignment +
2603 (StackAlignment-SlotSize);
2608 /// MatchingStackOffset - Return true if the given stack call argument is
2609 /// already available in the same position (relatively) of the caller's
2610 /// incoming argument stack.
2612 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2613 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2614 const X86InstrInfo *TII) {
2615 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2617 if (Arg.getOpcode() == ISD::CopyFromReg) {
2618 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2619 if (!TargetRegisterInfo::isVirtualRegister(VR))
2621 MachineInstr *Def = MRI->getVRegDef(VR);
2624 if (!Flags.isByVal()) {
2625 if (!TII->isLoadFromStackSlot(Def, FI))
2628 unsigned Opcode = Def->getOpcode();
2629 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2630 Def->getOperand(1).isFI()) {
2631 FI = Def->getOperand(1).getIndex();
2632 Bytes = Flags.getByValSize();
2636 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2637 if (Flags.isByVal())
2638 // ByVal argument is passed in as a pointer but it's now being
2639 // dereferenced. e.g.
2640 // define @foo(%struct.X* %A) {
2641 // tail call @bar(%struct.X* byval %A)
2644 SDValue Ptr = Ld->getBasePtr();
2645 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2648 FI = FINode->getIndex();
2649 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2650 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2651 FI = FINode->getIndex();
2652 Bytes = Flags.getByValSize();
2656 assert(FI != INT_MAX);
2657 if (!MFI->isFixedObjectIndex(FI))
2659 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2662 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2663 /// for tail call optimization. Targets which want to do tail call
2664 /// optimization should implement this function.
2666 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2667 CallingConv::ID CalleeCC,
2669 bool isCalleeStructRet,
2670 bool isCallerStructRet,
2671 const SmallVectorImpl<ISD::OutputArg> &Outs,
2672 const SmallVectorImpl<SDValue> &OutVals,
2673 const SmallVectorImpl<ISD::InputArg> &Ins,
2674 SelectionDAG& DAG) const {
2675 if (!IsTailCallConvention(CalleeCC) &&
2676 CalleeCC != CallingConv::C)
2679 // If -tailcallopt is specified, make fastcc functions tail-callable.
2680 const MachineFunction &MF = DAG.getMachineFunction();
2681 const Function *CallerF = DAG.getMachineFunction().getFunction();
2682 CallingConv::ID CallerCC = CallerF->getCallingConv();
2683 bool CCMatch = CallerCC == CalleeCC;
2685 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2686 if (IsTailCallConvention(CalleeCC) && CCMatch)
2691 // Look for obvious safe cases to perform tail call optimization that do not
2692 // require ABI changes. This is what gcc calls sibcall.
2694 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2695 // emit a special epilogue.
2696 if (RegInfo->needsStackRealignment(MF))
2699 // Also avoid sibcall optimization if either caller or callee uses struct
2700 // return semantics.
2701 if (isCalleeStructRet || isCallerStructRet)
2704 // An stdcall caller is expected to clean up its arguments; the callee
2705 // isn't going to do that.
2706 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2709 // Do not sibcall optimize vararg calls unless all arguments are passed via
2711 if (isVarArg && !Outs.empty()) {
2713 // Optimizing for varargs on Win64 is unlikely to be safe without
2714 // additional testing.
2715 if (Subtarget->isTargetWin64())
2718 SmallVector<CCValAssign, 16> ArgLocs;
2719 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2720 getTargetMachine(), ArgLocs, *DAG.getContext());
2722 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2723 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2724 if (!ArgLocs[i].isRegLoc())
2728 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2729 // stack. Therefore, if it's not used by the call it is not safe to optimize
2730 // this into a sibcall.
2731 bool Unused = false;
2732 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2739 SmallVector<CCValAssign, 16> RVLocs;
2740 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2741 getTargetMachine(), RVLocs, *DAG.getContext());
2742 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2743 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2744 CCValAssign &VA = RVLocs[i];
2745 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2750 // If the calling conventions do not match, then we'd better make sure the
2751 // results are returned in the same way as what the caller expects.
2753 SmallVector<CCValAssign, 16> RVLocs1;
2754 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2755 getTargetMachine(), RVLocs1, *DAG.getContext());
2756 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2758 SmallVector<CCValAssign, 16> RVLocs2;
2759 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2760 getTargetMachine(), RVLocs2, *DAG.getContext());
2761 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2763 if (RVLocs1.size() != RVLocs2.size())
2765 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2766 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2768 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2770 if (RVLocs1[i].isRegLoc()) {
2771 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2774 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2780 // If the callee takes no arguments then go on to check the results of the
2782 if (!Outs.empty()) {
2783 // Check if stack adjustment is needed. For now, do not do this if any
2784 // argument is passed on the stack.
2785 SmallVector<CCValAssign, 16> ArgLocs;
2786 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2787 getTargetMachine(), ArgLocs, *DAG.getContext());
2789 // Allocate shadow area for Win64
2790 if (Subtarget->isTargetWin64()) {
2791 CCInfo.AllocateStack(32, 8);
2794 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2795 if (CCInfo.getNextStackOffset()) {
2796 MachineFunction &MF = DAG.getMachineFunction();
2797 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2800 // Check if the arguments are already laid out in the right way as
2801 // the caller's fixed stack objects.
2802 MachineFrameInfo *MFI = MF.getFrameInfo();
2803 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2804 const X86InstrInfo *TII =
2805 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2806 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2807 CCValAssign &VA = ArgLocs[i];
2808 SDValue Arg = OutVals[i];
2809 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2810 if (VA.getLocInfo() == CCValAssign::Indirect)
2812 if (!VA.isRegLoc()) {
2813 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2820 // If the tailcall address may be in a register, then make sure it's
2821 // possible to register allocate for it. In 32-bit, the call address can
2822 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2823 // callee-saved registers are restored. These happen to be the same
2824 // registers used to pass 'inreg' arguments so watch out for those.
2825 if (!Subtarget->is64Bit() &&
2826 !isa<GlobalAddressSDNode>(Callee) &&
2827 !isa<ExternalSymbolSDNode>(Callee)) {
2828 unsigned NumInRegs = 0;
2829 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2830 CCValAssign &VA = ArgLocs[i];
2833 unsigned Reg = VA.getLocReg();
2836 case X86::EAX: case X86::EDX: case X86::ECX:
2837 if (++NumInRegs == 3)
2849 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2850 return X86::createFastISel(funcInfo);
2854 //===----------------------------------------------------------------------===//
2855 // Other Lowering Hooks
2856 //===----------------------------------------------------------------------===//
2858 static bool MayFoldLoad(SDValue Op) {
2859 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2862 static bool MayFoldIntoStore(SDValue Op) {
2863 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2866 static bool isTargetShuffle(unsigned Opcode) {
2868 default: return false;
2869 case X86ISD::PSHUFD:
2870 case X86ISD::PSHUFHW:
2871 case X86ISD::PSHUFLW:
2873 case X86ISD::PALIGN:
2874 case X86ISD::MOVLHPS:
2875 case X86ISD::MOVLHPD:
2876 case X86ISD::MOVHLPS:
2877 case X86ISD::MOVLPS:
2878 case X86ISD::MOVLPD:
2879 case X86ISD::MOVSHDUP:
2880 case X86ISD::MOVSLDUP:
2881 case X86ISD::MOVDDUP:
2884 case X86ISD::UNPCKL:
2885 case X86ISD::UNPCKH:
2886 case X86ISD::VPERMILP:
2887 case X86ISD::VPERM2X128:
2893 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2894 SDValue V1, SelectionDAG &DAG) {
2896 default: llvm_unreachable("Unknown x86 shuffle node");
2897 case X86ISD::MOVSHDUP:
2898 case X86ISD::MOVSLDUP:
2899 case X86ISD::MOVDDUP:
2900 return DAG.getNode(Opc, dl, VT, V1);
2906 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2907 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2909 default: llvm_unreachable("Unknown x86 shuffle node");
2910 case X86ISD::PSHUFD:
2911 case X86ISD::PSHUFHW:
2912 case X86ISD::PSHUFLW:
2913 case X86ISD::VPERMILP:
2914 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2920 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2921 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2923 default: llvm_unreachable("Unknown x86 shuffle node");
2924 case X86ISD::PALIGN:
2926 case X86ISD::VPERM2X128:
2927 return DAG.getNode(Opc, dl, VT, V1, V2,
2928 DAG.getConstant(TargetMask, MVT::i8));
2933 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2934 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2936 default: llvm_unreachable("Unknown x86 shuffle node");
2937 case X86ISD::MOVLHPS:
2938 case X86ISD::MOVLHPD:
2939 case X86ISD::MOVHLPS:
2940 case X86ISD::MOVLPS:
2941 case X86ISD::MOVLPD:
2944 case X86ISD::UNPCKL:
2945 case X86ISD::UNPCKH:
2946 return DAG.getNode(Opc, dl, VT, V1, V2);
2951 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2952 MachineFunction &MF = DAG.getMachineFunction();
2953 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2954 int ReturnAddrIndex = FuncInfo->getRAIndex();
2956 if (ReturnAddrIndex == 0) {
2957 // Set up a frame object for the return address.
2958 uint64_t SlotSize = TD->getPointerSize();
2959 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2961 FuncInfo->setRAIndex(ReturnAddrIndex);
2964 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2968 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2969 bool hasSymbolicDisplacement) {
2970 // Offset should fit into 32 bit immediate field.
2971 if (!isInt<32>(Offset))
2974 // If we don't have a symbolic displacement - we don't have any extra
2976 if (!hasSymbolicDisplacement)
2979 // FIXME: Some tweaks might be needed for medium code model.
2980 if (M != CodeModel::Small && M != CodeModel::Kernel)
2983 // For small code model we assume that latest object is 16MB before end of 31
2984 // bits boundary. We may also accept pretty large negative constants knowing
2985 // that all objects are in the positive half of address space.
2986 if (M == CodeModel::Small && Offset < 16*1024*1024)
2989 // For kernel code model we know that all object resist in the negative half
2990 // of 32bits address space. We may not accept negative offsets, since they may
2991 // be just off and we may accept pretty large positive ones.
2992 if (M == CodeModel::Kernel && Offset > 0)
2998 /// isCalleePop - Determines whether the callee is required to pop its
2999 /// own arguments. Callee pop is necessary to support tail calls.
3000 bool X86::isCalleePop(CallingConv::ID CallingConv,
3001 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3005 switch (CallingConv) {
3008 case CallingConv::X86_StdCall:
3010 case CallingConv::X86_FastCall:
3012 case CallingConv::X86_ThisCall:
3014 case CallingConv::Fast:
3016 case CallingConv::GHC:
3021 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3022 /// specific condition code, returning the condition code and the LHS/RHS of the
3023 /// comparison to make.
3024 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3025 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3027 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3028 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3029 // X > -1 -> X == 0, jump !sign.
3030 RHS = DAG.getConstant(0, RHS.getValueType());
3031 return X86::COND_NS;
3032 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3033 // X < 0 -> X == 0, jump on sign.
3035 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3037 RHS = DAG.getConstant(0, RHS.getValueType());
3038 return X86::COND_LE;
3042 switch (SetCCOpcode) {
3043 default: llvm_unreachable("Invalid integer condition!");
3044 case ISD::SETEQ: return X86::COND_E;
3045 case ISD::SETGT: return X86::COND_G;
3046 case ISD::SETGE: return X86::COND_GE;
3047 case ISD::SETLT: return X86::COND_L;
3048 case ISD::SETLE: return X86::COND_LE;
3049 case ISD::SETNE: return X86::COND_NE;
3050 case ISD::SETULT: return X86::COND_B;
3051 case ISD::SETUGT: return X86::COND_A;
3052 case ISD::SETULE: return X86::COND_BE;
3053 case ISD::SETUGE: return X86::COND_AE;
3057 // First determine if it is required or is profitable to flip the operands.
3059 // If LHS is a foldable load, but RHS is not, flip the condition.
3060 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3061 !ISD::isNON_EXTLoad(RHS.getNode())) {
3062 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3063 std::swap(LHS, RHS);
3066 switch (SetCCOpcode) {
3072 std::swap(LHS, RHS);
3076 // On a floating point condition, the flags are set as follows:
3078 // 0 | 0 | 0 | X > Y
3079 // 0 | 0 | 1 | X < Y
3080 // 1 | 0 | 0 | X == Y
3081 // 1 | 1 | 1 | unordered
3082 switch (SetCCOpcode) {
3083 default: llvm_unreachable("Condcode should be pre-legalized away");
3085 case ISD::SETEQ: return X86::COND_E;
3086 case ISD::SETOLT: // flipped
3088 case ISD::SETGT: return X86::COND_A;
3089 case ISD::SETOLE: // flipped
3091 case ISD::SETGE: return X86::COND_AE;
3092 case ISD::SETUGT: // flipped
3094 case ISD::SETLT: return X86::COND_B;
3095 case ISD::SETUGE: // flipped
3097 case ISD::SETLE: return X86::COND_BE;
3099 case ISD::SETNE: return X86::COND_NE;
3100 case ISD::SETUO: return X86::COND_P;
3101 case ISD::SETO: return X86::COND_NP;
3103 case ISD::SETUNE: return X86::COND_INVALID;
3107 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3108 /// code. Current x86 isa includes the following FP cmov instructions:
3109 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3110 static bool hasFPCMov(unsigned X86CC) {
3126 /// isFPImmLegal - Returns true if the target can instruction select the
3127 /// specified FP immediate natively. If false, the legalizer will
3128 /// materialize the FP immediate as a load from a constant pool.
3129 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3130 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3131 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3137 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3138 /// the specified range (L, H].
3139 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3140 return (Val < 0) || (Val >= Low && Val < Hi);
3143 /// isUndefOrInRange - Return true if every element in Mask, begining
3144 /// from position Pos and ending in Pos+Size, falls within the specified
3145 /// range (L, L+Pos]. or is undef.
3146 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3147 int Pos, int Size, int Low, int Hi) {
3148 for (int i = Pos, e = Pos+Size; i != e; ++i)
3149 if (!isUndefOrInRange(Mask[i], Low, Hi))
3154 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3155 /// specified value.
3156 static bool isUndefOrEqual(int Val, int CmpVal) {
3157 if (Val < 0 || Val == CmpVal)
3162 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3163 /// from position Pos and ending in Pos+Size, falls within the specified
3164 /// sequential range (L, L+Pos]. or is undef.
3165 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3166 int Pos, int Size, int Low) {
3167 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3168 if (!isUndefOrEqual(Mask[i], Low))
3173 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3174 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3175 /// the second operand.
3176 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3177 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3178 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3179 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3180 return (Mask[0] < 2 && Mask[1] < 2);
3184 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3185 SmallVector<int, 8> M;
3187 return ::isPSHUFDMask(M, N->getValueType(0));
3190 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3191 /// is suitable for input to PSHUFHW.
3192 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3193 if (VT != MVT::v8i16)
3196 // Lower quadword copied in order or undef.
3197 for (int i = 0; i != 4; ++i)
3198 if (Mask[i] >= 0 && Mask[i] != i)
3201 // Upper quadword shuffled.
3202 for (int i = 4; i != 8; ++i)
3203 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3209 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3210 SmallVector<int, 8> M;
3212 return ::isPSHUFHWMask(M, N->getValueType(0));
3215 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3216 /// is suitable for input to PSHUFLW.
3217 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3218 if (VT != MVT::v8i16)
3221 // Upper quadword copied in order.
3222 for (int i = 4; i != 8; ++i)
3223 if (Mask[i] >= 0 && Mask[i] != i)
3226 // Lower quadword shuffled.
3227 for (int i = 0; i != 4; ++i)
3234 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3235 SmallVector<int, 8> M;
3237 return ::isPSHUFLWMask(M, N->getValueType(0));
3240 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3241 /// is suitable for input to PALIGNR.
3242 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3243 bool hasSSSE3OrAVX) {
3244 int i, e = VT.getVectorNumElements();
3245 if (VT.getSizeInBits() != 128)
3248 // Do not handle v2i64 / v2f64 shuffles with palignr.
3249 if (e < 4 || !hasSSSE3OrAVX)
3252 for (i = 0; i != e; ++i)
3256 // All undef, not a palignr.
3260 // Make sure we're shifting in the right direction.
3264 int s = Mask[i] - i;
3266 // Check the rest of the elements to see if they are consecutive.
3267 for (++i; i != e; ++i) {
3269 if (m >= 0 && m != s+i)
3275 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3276 /// specifies a shuffle of elements that is suitable for input to 256-bit
3278 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3279 bool HasAVX, bool Commuted = false) {
3280 int NumElems = VT.getVectorNumElements();
3282 if (!HasAVX || VT.getSizeInBits() != 256)
3285 if (NumElems != 4 && NumElems != 8)
3288 // VSHUFPSY divides the resulting vector into 4 chunks.
3289 // The sources are also splitted into 4 chunks, and each destination
3290 // chunk must come from a different source chunk.
3292 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3293 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3295 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3296 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3298 // VSHUFPDY divides the resulting vector into 4 chunks.
3299 // The sources are also splitted into 4 chunks, and each destination
3300 // chunk must come from a different source chunk.
3302 // SRC1 => X3 X2 X1 X0
3303 // SRC2 => Y3 Y2 Y1 Y0
3305 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3307 unsigned QuarterSize = NumElems/4;
3308 unsigned HalfSize = QuarterSize*2;
3309 for (unsigned l = 0; l != 2; ++l) {
3310 unsigned LaneStart = l*HalfSize;
3311 for (unsigned s = 0; s != 2; ++s) {
3312 unsigned QuarterStart = s*QuarterSize;
3313 unsigned Src = (Commuted) ? (1-s) : s;
3314 unsigned SrcStart = Src*NumElems + LaneStart;
3315 for (unsigned i = 0; i != QuarterSize; ++i) {
3316 int Idx = Mask[i+QuarterStart+LaneStart];
3317 if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3319 // For VSHUFPSY, the mask of the second half must be the same as the
3320 // first but with the appropriate offsets. This works in the same way as
3321 // VPERMILPS works with masks.
3322 if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3324 if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3333 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3334 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3335 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3336 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3337 EVT VT = SVOp->getValueType(0);
3338 int NumElems = VT.getVectorNumElements();
3340 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3341 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3343 int HalfSize = NumElems/2;
3344 unsigned Mul = (NumElems == 8) ? 2 : 1;
3346 for (int i = 0; i != NumElems; ++i) {
3347 int Elt = SVOp->getMaskElt(i);
3352 // For VSHUFPSY, the mask of the first half must be equal to the second one.
3353 if (NumElems == 8) Shamt %= HalfSize;
3354 Mask |= Elt << (Shamt*Mul);
3360 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3361 /// the two vector operands have swapped position.
3362 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3363 unsigned NumElems) {
3364 for (unsigned i = 0; i != NumElems; ++i) {
3368 else if (idx < (int)NumElems)
3369 Mask[i] = idx + NumElems;
3371 Mask[i] = idx - NumElems;
3375 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3376 /// specifies a shuffle of elements that is suitable for input to 128-bit
3377 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3378 /// reverse of what x86 shuffles want.
3379 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3380 bool Commuted = false) {
3381 unsigned NumElems = VT.getVectorNumElements();
3383 if (VT.getSizeInBits() != 128)
3386 if (NumElems != 2 && NumElems != 4)
3389 unsigned Half = NumElems / 2;
3390 unsigned SrcStart = Commuted ? NumElems : 0;
3391 for (unsigned i = 0; i != Half; ++i)
3392 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3394 SrcStart = Commuted ? 0 : NumElems;
3395 for (unsigned i = Half; i != NumElems; ++i)
3396 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3402 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3403 SmallVector<int, 8> M;
3405 return ::isSHUFPMask(M, N->getValueType(0));
3408 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3409 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3410 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3411 EVT VT = N->getValueType(0);
3412 unsigned NumElems = VT.getVectorNumElements();
3414 if (VT.getSizeInBits() != 128)
3420 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3421 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3422 isUndefOrEqual(N->getMaskElt(1), 7) &&
3423 isUndefOrEqual(N->getMaskElt(2), 2) &&
3424 isUndefOrEqual(N->getMaskElt(3), 3);
3427 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3428 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3430 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3431 EVT VT = N->getValueType(0);
3432 unsigned NumElems = VT.getVectorNumElements();
3434 if (VT.getSizeInBits() != 128)
3440 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3441 isUndefOrEqual(N->getMaskElt(1), 3) &&
3442 isUndefOrEqual(N->getMaskElt(2), 2) &&
3443 isUndefOrEqual(N->getMaskElt(3), 3);
3446 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3447 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3448 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3449 EVT VT = N->getValueType(0);
3451 if (VT.getSizeInBits() != 128)
3454 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3456 if (NumElems != 2 && NumElems != 4)
3459 for (unsigned i = 0; i < NumElems/2; ++i)
3460 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3463 for (unsigned i = NumElems/2; i < NumElems; ++i)
3464 if (!isUndefOrEqual(N->getMaskElt(i), i))
3470 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3471 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3472 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3473 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3475 if ((NumElems != 2 && NumElems != 4)
3476 || N->getValueType(0).getSizeInBits() > 128)
3479 for (unsigned i = 0; i < NumElems/2; ++i)
3480 if (!isUndefOrEqual(N->getMaskElt(i), i))
3483 for (unsigned i = 0; i < NumElems/2; ++i)
3484 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3490 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3491 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3492 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3493 bool HasAVX2, bool V2IsSplat = false) {
3494 unsigned NumElts = VT.getVectorNumElements();
3496 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3497 "Unsupported vector type for unpckh");
3499 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3500 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3503 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3504 // independently on 128-bit lanes.
3505 unsigned NumLanes = VT.getSizeInBits()/128;
3506 unsigned NumLaneElts = NumElts/NumLanes;
3508 for (unsigned l = 0; l != NumLanes; ++l) {
3509 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3510 i != (l+1)*NumLaneElts;
3513 int BitI1 = Mask[i+1];
3514 if (!isUndefOrEqual(BitI, j))
3517 if (!isUndefOrEqual(BitI1, NumElts))
3520 if (!isUndefOrEqual(BitI1, j + NumElts))
3529 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3530 SmallVector<int, 8> M;
3532 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3535 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3536 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3537 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3538 bool HasAVX2, bool V2IsSplat = false) {
3539 unsigned NumElts = VT.getVectorNumElements();
3541 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3542 "Unsupported vector type for unpckh");
3544 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3545 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3548 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3549 // independently on 128-bit lanes.
3550 unsigned NumLanes = VT.getSizeInBits()/128;
3551 unsigned NumLaneElts = NumElts/NumLanes;
3553 for (unsigned l = 0; l != NumLanes; ++l) {
3554 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3555 i != (l+1)*NumLaneElts; i += 2, ++j) {
3557 int BitI1 = Mask[i+1];
3558 if (!isUndefOrEqual(BitI, j))
3561 if (isUndefOrEqual(BitI1, NumElts))
3564 if (!isUndefOrEqual(BitI1, j+NumElts))
3572 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3573 SmallVector<int, 8> M;
3575 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3578 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3579 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3581 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3583 unsigned NumElts = VT.getVectorNumElements();
3585 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3586 "Unsupported vector type for unpckh");
3588 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3589 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3592 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3593 // FIXME: Need a better way to get rid of this, there's no latency difference
3594 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3595 // the former later. We should also remove the "_undef" special mask.
3596 if (NumElts == 4 && VT.getSizeInBits() == 256)
3599 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3600 // independently on 128-bit lanes.
3601 unsigned NumLanes = VT.getSizeInBits()/128;
3602 unsigned NumLaneElts = NumElts/NumLanes;
3604 for (unsigned l = 0; l != NumLanes; ++l) {
3605 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3606 i != (l+1)*NumLaneElts;
3609 int BitI1 = Mask[i+1];
3611 if (!isUndefOrEqual(BitI, j))
3613 if (!isUndefOrEqual(BitI1, j))
3621 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3622 SmallVector<int, 8> M;
3624 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3627 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3628 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3630 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3632 unsigned NumElts = VT.getVectorNumElements();
3634 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3635 "Unsupported vector type for unpckh");
3637 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3638 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3641 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3642 // independently on 128-bit lanes.
3643 unsigned NumLanes = VT.getSizeInBits()/128;
3644 unsigned NumLaneElts = NumElts/NumLanes;
3646 for (unsigned l = 0; l != NumLanes; ++l) {
3647 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3648 i != (l+1)*NumLaneElts; i += 2, ++j) {
3650 int BitI1 = Mask[i+1];
3651 if (!isUndefOrEqual(BitI, j))
3653 if (!isUndefOrEqual(BitI1, j))
3660 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3661 SmallVector<int, 8> M;
3663 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3666 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3667 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3668 /// MOVSD, and MOVD, i.e. setting the lowest element.
3669 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3670 if (VT.getVectorElementType().getSizeInBits() < 32)
3672 if (VT.getSizeInBits() == 256)
3675 int NumElts = VT.getVectorNumElements();
3677 if (!isUndefOrEqual(Mask[0], NumElts))
3680 for (int i = 1; i < NumElts; ++i)
3681 if (!isUndefOrEqual(Mask[i], i))
3687 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3688 SmallVector<int, 8> M;
3690 return ::isMOVLMask(M, N->getValueType(0));
3693 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3694 /// as permutations between 128-bit chunks or halves. As an example: this
3696 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3697 /// The first half comes from the second half of V1 and the second half from the
3698 /// the second half of V2.
3699 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3701 if (!HasAVX || VT.getSizeInBits() != 256)
3704 // The shuffle result is divided into half A and half B. In total the two
3705 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3706 // B must come from C, D, E or F.
3707 int HalfSize = VT.getVectorNumElements()/2;
3708 bool MatchA = false, MatchB = false;
3710 // Check if A comes from one of C, D, E, F.
3711 for (int Half = 0; Half < 4; ++Half) {
3712 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3718 // Check if B comes from one of C, D, E, F.
3719 for (int Half = 0; Half < 4; ++Half) {
3720 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3726 return MatchA && MatchB;
3729 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3730 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3731 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3732 EVT VT = SVOp->getValueType(0);
3734 int HalfSize = VT.getVectorNumElements()/2;
3736 int FstHalf = 0, SndHalf = 0;
3737 for (int i = 0; i < HalfSize; ++i) {
3738 if (SVOp->getMaskElt(i) > 0) {
3739 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3743 for (int i = HalfSize; i < HalfSize*2; ++i) {
3744 if (SVOp->getMaskElt(i) > 0) {
3745 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3750 return (FstHalf | (SndHalf << 4));
3753 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3754 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3755 /// Note that VPERMIL mask matching is different depending whether theunderlying
3756 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3757 /// to the same elements of the low, but to the higher half of the source.
3758 /// In VPERMILPD the two lanes could be shuffled independently of each other
3759 /// with the same restriction that lanes can't be crossed.
3760 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3762 int NumElts = VT.getVectorNumElements();
3763 int NumLanes = VT.getSizeInBits()/128;
3768 // Only match 256-bit with 32/64-bit types
3769 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3772 int LaneSize = NumElts/NumLanes;
3773 for (int l = 0; l != NumLanes; ++l) {
3774 int LaneStart = l*LaneSize;
3775 for (int i = 0; i != LaneSize; ++i) {
3776 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3778 if (NumElts == 4 || l == 0)
3780 // VPERMILPS handling
3783 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3791 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3792 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3793 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3794 EVT VT = SVOp->getValueType(0);
3796 int NumElts = VT.getVectorNumElements();
3797 int NumLanes = VT.getSizeInBits()/128;
3798 int LaneSize = NumElts/NumLanes;
3800 // Although the mask is equal for both lanes do it twice to get the cases
3801 // where a mask will match because the same mask element is undef on the
3802 // first half but valid on the second. This would get pathological cases
3803 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3804 unsigned Shift = (LaneSize == 4) ? 2 : 1;
3806 for (int i = 0; i != NumElts; ++i) {
3807 int MaskElt = SVOp->getMaskElt(i);
3810 MaskElt %= LaneSize;
3812 // VPERMILPSY, the mask of the first half must be equal to the second one
3813 if (NumElts == 8) Shamt %= LaneSize;
3814 Mask |= MaskElt << (Shamt*Shift);
3820 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3821 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3822 /// element of vector 2 and the other elements to come from vector 1 in order.
3823 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3824 bool V2IsSplat = false, bool V2IsUndef = false) {
3825 int NumOps = VT.getVectorNumElements();
3826 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3829 if (!isUndefOrEqual(Mask[0], 0))
3832 for (int i = 1; i < NumOps; ++i)
3833 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3834 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3835 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3841 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3842 bool V2IsUndef = false) {
3843 SmallVector<int, 8> M;
3845 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3848 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3850 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3851 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3852 const X86Subtarget *Subtarget) {
3853 if (!Subtarget->hasSSE3orAVX())
3856 // The second vector must be undef
3857 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3860 EVT VT = N->getValueType(0);
3861 unsigned NumElems = VT.getVectorNumElements();
3863 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3864 (VT.getSizeInBits() == 256 && NumElems != 8))
3867 // "i+1" is the value the indexed mask element must have
3868 for (unsigned i = 0; i < NumElems; i += 2)
3869 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3870 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3876 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3877 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3878 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3879 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3880 const X86Subtarget *Subtarget) {
3881 if (!Subtarget->hasSSE3orAVX())
3884 // The second vector must be undef
3885 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3888 EVT VT = N->getValueType(0);
3889 unsigned NumElems = VT.getVectorNumElements();
3891 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3892 (VT.getSizeInBits() == 256 && NumElems != 8))
3895 // "i" is the value the indexed mask element must have
3896 for (unsigned i = 0; i < NumElems; i += 2)
3897 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3898 !isUndefOrEqual(N->getMaskElt(i+1), i))
3904 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3905 /// specifies a shuffle of elements that is suitable for input to 256-bit
3906 /// version of MOVDDUP.
3907 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3909 int NumElts = VT.getVectorNumElements();
3911 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3914 for (int i = 0; i != NumElts/2; ++i)
3915 if (!isUndefOrEqual(Mask[i], 0))
3917 for (int i = NumElts/2; i != NumElts; ++i)
3918 if (!isUndefOrEqual(Mask[i], NumElts/2))
3923 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to 128-bit
3925 /// version of MOVDDUP.
3926 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3927 EVT VT = N->getValueType(0);
3929 if (VT.getSizeInBits() != 128)
3932 int e = VT.getVectorNumElements() / 2;
3933 for (int i = 0; i < e; ++i)
3934 if (!isUndefOrEqual(N->getMaskElt(i), i))
3936 for (int i = 0; i < e; ++i)
3937 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3942 /// isVEXTRACTF128Index - Return true if the specified
3943 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3944 /// suitable for input to VEXTRACTF128.
3945 bool X86::isVEXTRACTF128Index(SDNode *N) {
3946 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3949 // The index should be aligned on a 128-bit boundary.
3951 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3953 unsigned VL = N->getValueType(0).getVectorNumElements();
3954 unsigned VBits = N->getValueType(0).getSizeInBits();
3955 unsigned ElSize = VBits / VL;
3956 bool Result = (Index * ElSize) % 128 == 0;
3961 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3962 /// operand specifies a subvector insert that is suitable for input to
3964 bool X86::isVINSERTF128Index(SDNode *N) {
3965 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3968 // The index should be aligned on a 128-bit boundary.
3970 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3972 unsigned VL = N->getValueType(0).getVectorNumElements();
3973 unsigned VBits = N->getValueType(0).getSizeInBits();
3974 unsigned ElSize = VBits / VL;
3975 bool Result = (Index * ElSize) % 128 == 0;
3980 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3981 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3982 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3983 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3984 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3986 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3988 for (int i = 0; i < NumOperands; ++i) {
3989 int Val = SVOp->getMaskElt(NumOperands-i-1);
3990 if (Val < 0) Val = 0;
3991 if (Val >= NumOperands) Val -= NumOperands;
3993 if (i != NumOperands - 1)
3999 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4000 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4001 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4002 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4004 // 8 nodes, but we only care about the last 4.
4005 for (unsigned i = 7; i >= 4; --i) {
4006 int Val = SVOp->getMaskElt(i);
4015 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4016 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4017 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4018 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4020 // 8 nodes, but we only care about the first 4.
4021 for (int i = 3; i >= 0; --i) {
4022 int Val = SVOp->getMaskElt(i);
4031 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4032 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4033 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4034 EVT VT = SVOp->getValueType(0);
4035 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4039 for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4040 Val = SVOp->getMaskElt(i);
4044 assert(Val - i > 0 && "PALIGNR imm should be positive");
4045 return (Val - i) * EltSize;
4048 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4049 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4051 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4052 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4053 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4056 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4058 EVT VecVT = N->getOperand(0).getValueType();
4059 EVT ElVT = VecVT.getVectorElementType();
4061 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4062 return Index / NumElemsPerChunk;
4065 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4066 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4068 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4069 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4070 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4073 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4075 EVT VecVT = N->getValueType(0);
4076 EVT ElVT = VecVT.getVectorElementType();
4078 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4079 return Index / NumElemsPerChunk;
4082 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4084 bool X86::isZeroNode(SDValue Elt) {
4085 return ((isa<ConstantSDNode>(Elt) &&
4086 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4087 (isa<ConstantFPSDNode>(Elt) &&
4088 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4091 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4092 /// their permute mask.
4093 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4094 SelectionDAG &DAG) {
4095 EVT VT = SVOp->getValueType(0);
4096 unsigned NumElems = VT.getVectorNumElements();
4097 SmallVector<int, 8> MaskVec;
4099 for (unsigned i = 0; i != NumElems; ++i) {
4100 int idx = SVOp->getMaskElt(i);
4102 MaskVec.push_back(idx);
4103 else if (idx < (int)NumElems)
4104 MaskVec.push_back(idx + NumElems);
4106 MaskVec.push_back(idx - NumElems);
4108 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4109 SVOp->getOperand(0), &MaskVec[0]);
4112 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4113 /// match movhlps. The lower half elements should come from upper half of
4114 /// V1 (and in order), and the upper half elements should come from the upper
4115 /// half of V2 (and in order).
4116 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4117 EVT VT = Op->getValueType(0);
4118 if (VT.getSizeInBits() != 128)
4120 if (VT.getVectorNumElements() != 4)
4122 for (unsigned i = 0, e = 2; i != e; ++i)
4123 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4125 for (unsigned i = 2; i != 4; ++i)
4126 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4131 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4132 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4134 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4135 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4137 N = N->getOperand(0).getNode();
4138 if (!ISD::isNON_EXTLoad(N))
4141 *LD = cast<LoadSDNode>(N);
4145 // Test whether the given value is a vector value which will be legalized
4147 static bool WillBeConstantPoolLoad(SDNode *N) {
4148 if (N->getOpcode() != ISD::BUILD_VECTOR)
4151 // Check for any non-constant elements.
4152 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4153 switch (N->getOperand(i).getNode()->getOpcode()) {
4155 case ISD::ConstantFP:
4162 // Vectors of all-zeros and all-ones are materialized with special
4163 // instructions rather than being loaded.
4164 return !ISD::isBuildVectorAllZeros(N) &&
4165 !ISD::isBuildVectorAllOnes(N);
4168 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4169 /// match movlp{s|d}. The lower half elements should come from lower half of
4170 /// V1 (and in order), and the upper half elements should come from the upper
4171 /// half of V2 (and in order). And since V1 will become the source of the
4172 /// MOVLP, it must be either a vector load or a scalar load to vector.
4173 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4174 ShuffleVectorSDNode *Op) {
4175 EVT VT = Op->getValueType(0);
4176 if (VT.getSizeInBits() != 128)
4179 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4181 // Is V2 is a vector load, don't do this transformation. We will try to use
4182 // load folding shufps op.
4183 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4186 unsigned NumElems = VT.getVectorNumElements();
4188 if (NumElems != 2 && NumElems != 4)
4190 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4191 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4193 for (unsigned i = NumElems/2; i != NumElems; ++i)
4194 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4199 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4201 static bool isSplatVector(SDNode *N) {
4202 if (N->getOpcode() != ISD::BUILD_VECTOR)
4205 SDValue SplatValue = N->getOperand(0);
4206 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4207 if (N->getOperand(i) != SplatValue)
4212 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4213 /// to an zero vector.
4214 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4215 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4216 SDValue V1 = N->getOperand(0);
4217 SDValue V2 = N->getOperand(1);
4218 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4219 for (unsigned i = 0; i != NumElems; ++i) {
4220 int Idx = N->getMaskElt(i);
4221 if (Idx >= (int)NumElems) {
4222 unsigned Opc = V2.getOpcode();
4223 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4225 if (Opc != ISD::BUILD_VECTOR ||
4226 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4228 } else if (Idx >= 0) {
4229 unsigned Opc = V1.getOpcode();
4230 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4232 if (Opc != ISD::BUILD_VECTOR ||
4233 !X86::isZeroNode(V1.getOperand(Idx)))
4240 /// getZeroVector - Returns a vector of specified type with all zero elements.
4242 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4244 assert(VT.isVector() && "Expected a vector type");
4246 // Always build SSE zero vectors as <4 x i32> bitcasted
4247 // to their dest type. This ensures they get CSE'd.
4249 if (VT.getSizeInBits() == 128) { // SSE
4250 if (HasXMMInt) { // SSE2
4251 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4252 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4254 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4255 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4257 } else if (VT.getSizeInBits() == 256) { // AVX
4258 // 256-bit logic and arithmetic instructions in AVX are
4259 // all floating-point, no support for integer ops. Default
4260 // to emitting fp zeroed vectors then.
4261 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4262 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4263 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4265 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4268 /// getOnesVector - Returns a vector of specified type with all bits set.
4269 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4270 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4271 /// Then bitcast to their original type, ensuring they get CSE'd.
4272 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4274 assert(VT.isVector() && "Expected a vector type");
4275 assert((VT.is128BitVector() || VT.is256BitVector())
4276 && "Expected a 128-bit or 256-bit vector type");
4278 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4280 if (VT.getSizeInBits() == 256) {
4281 if (HasAVX2) { // AVX2
4282 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4283 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4285 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4286 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4287 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4288 Vec = Insert128BitVector(InsV, Vec,
4289 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4292 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4295 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4298 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4299 /// that point to V2 points to its first element.
4300 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4301 EVT VT = SVOp->getValueType(0);
4302 unsigned NumElems = VT.getVectorNumElements();
4304 bool Changed = false;
4305 SmallVector<int, 8> MaskVec;
4306 SVOp->getMask(MaskVec);
4308 for (unsigned i = 0; i != NumElems; ++i) {
4309 if (MaskVec[i] > (int)NumElems) {
4310 MaskVec[i] = NumElems;
4315 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4316 SVOp->getOperand(1), &MaskVec[0]);
4317 return SDValue(SVOp, 0);
4320 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4321 /// operation of specified width.
4322 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4324 unsigned NumElems = VT.getVectorNumElements();
4325 SmallVector<int, 8> Mask;
4326 Mask.push_back(NumElems);
4327 for (unsigned i = 1; i != NumElems; ++i)
4329 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4332 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4333 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4335 unsigned NumElems = VT.getVectorNumElements();
4336 SmallVector<int, 8> Mask;
4337 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4339 Mask.push_back(i + NumElems);
4341 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4344 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4345 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4347 unsigned NumElems = VT.getVectorNumElements();
4348 unsigned Half = NumElems/2;
4349 SmallVector<int, 8> Mask;
4350 for (unsigned i = 0; i != Half; ++i) {
4351 Mask.push_back(i + Half);
4352 Mask.push_back(i + NumElems + Half);
4354 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4357 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4358 // a generic shuffle instruction because the target has no such instructions.
4359 // Generate shuffles which repeat i16 and i8 several times until they can be
4360 // represented by v4f32 and then be manipulated by target suported shuffles.
4361 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4362 EVT VT = V.getValueType();
4363 int NumElems = VT.getVectorNumElements();
4364 DebugLoc dl = V.getDebugLoc();
4366 while (NumElems > 4) {
4367 if (EltNo < NumElems/2) {
4368 V = getUnpackl(DAG, dl, VT, V, V);
4370 V = getUnpackh(DAG, dl, VT, V, V);
4371 EltNo -= NumElems/2;
4378 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4379 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4380 EVT VT = V.getValueType();
4381 DebugLoc dl = V.getDebugLoc();
4382 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4383 && "Vector size not supported");
4385 if (VT.getSizeInBits() == 128) {
4386 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4387 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4388 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4391 // To use VPERMILPS to splat scalars, the second half of indicies must
4392 // refer to the higher part, which is a duplication of the lower one,
4393 // because VPERMILPS can only handle in-lane permutations.
4394 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4395 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4397 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4398 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4402 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4405 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4406 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4407 EVT SrcVT = SV->getValueType(0);
4408 SDValue V1 = SV->getOperand(0);
4409 DebugLoc dl = SV->getDebugLoc();
4411 int EltNo = SV->getSplatIndex();
4412 int NumElems = SrcVT.getVectorNumElements();
4413 unsigned Size = SrcVT.getSizeInBits();
4415 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4416 "Unknown how to promote splat for type");
4418 // Extract the 128-bit part containing the splat element and update
4419 // the splat element index when it refers to the higher register.
4421 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4422 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4424 EltNo -= NumElems/2;
4427 // All i16 and i8 vector types can't be used directly by a generic shuffle
4428 // instruction because the target has no such instruction. Generate shuffles
4429 // which repeat i16 and i8 several times until they fit in i32, and then can
4430 // be manipulated by target suported shuffles.
4431 EVT EltVT = SrcVT.getVectorElementType();
4432 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4433 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4435 // Recreate the 256-bit vector and place the same 128-bit vector
4436 // into the low and high part. This is necessary because we want
4437 // to use VPERM* to shuffle the vectors
4439 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4440 DAG.getConstant(0, MVT::i32), DAG, dl);
4441 V1 = Insert128BitVector(InsV, V1,
4442 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4445 return getLegalSplat(DAG, V1, EltNo);
4448 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4449 /// vector of zero or undef vector. This produces a shuffle where the low
4450 /// element of V2 is swizzled into the zero/undef vector, landing at element
4451 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4452 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4453 bool isZero, bool HasXMMInt,
4454 SelectionDAG &DAG) {
4455 EVT VT = V2.getValueType();
4457 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4458 unsigned NumElems = VT.getVectorNumElements();
4459 SmallVector<int, 16> MaskVec;
4460 for (unsigned i = 0; i != NumElems; ++i)
4461 // If this is the insertion idx, put the low elt of V2 here.
4462 MaskVec.push_back(i == Idx ? NumElems : i);
4463 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4466 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4467 /// element of the result of the vector shuffle.
4468 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4471 return SDValue(); // Limit search depth.
4473 SDValue V = SDValue(N, 0);
4474 EVT VT = V.getValueType();
4475 unsigned Opcode = V.getOpcode();
4477 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4478 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4479 Index = SV->getMaskElt(Index);
4482 return DAG.getUNDEF(VT.getVectorElementType());
4484 int NumElems = VT.getVectorNumElements();
4485 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4486 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4489 // Recurse into target specific vector shuffles to find scalars.
4490 if (isTargetShuffle(Opcode)) {
4491 int NumElems = VT.getVectorNumElements();
4492 SmallVector<unsigned, 16> ShuffleMask;
4497 ImmN = N->getOperand(N->getNumOperands()-1);
4498 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4501 case X86ISD::UNPCKH:
4502 DecodeUNPCKHMask(VT, ShuffleMask);
4504 case X86ISD::UNPCKL:
4505 DecodeUNPCKLMask(VT, ShuffleMask);
4507 case X86ISD::MOVHLPS:
4508 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4510 case X86ISD::MOVLHPS:
4511 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4513 case X86ISD::PSHUFD:
4514 ImmN = N->getOperand(N->getNumOperands()-1);
4515 DecodePSHUFMask(NumElems,
4516 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4519 case X86ISD::PSHUFHW:
4520 ImmN = N->getOperand(N->getNumOperands()-1);
4521 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4524 case X86ISD::PSHUFLW:
4525 ImmN = N->getOperand(N->getNumOperands()-1);
4526 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4530 case X86ISD::MOVSD: {
4531 // The index 0 always comes from the first element of the second source,
4532 // this is why MOVSS and MOVSD are used in the first place. The other
4533 // elements come from the other positions of the first source vector.
4534 unsigned OpNum = (Index == 0) ? 1 : 0;
4535 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4538 case X86ISD::VPERMILP:
4539 ImmN = N->getOperand(N->getNumOperands()-1);
4540 DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4543 case X86ISD::VPERM2X128:
4544 ImmN = N->getOperand(N->getNumOperands()-1);
4545 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4548 case X86ISD::MOVDDUP:
4549 case X86ISD::MOVLHPD:
4550 case X86ISD::MOVLPD:
4551 case X86ISD::MOVLPS:
4552 case X86ISD::MOVSHDUP:
4553 case X86ISD::MOVSLDUP:
4554 case X86ISD::PALIGN:
4555 return SDValue(); // Not yet implemented.
4557 assert(0 && "unknown target shuffle node");
4561 Index = ShuffleMask[Index];
4563 return DAG.getUNDEF(VT.getVectorElementType());
4565 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4566 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4570 // Actual nodes that may contain scalar elements
4571 if (Opcode == ISD::BITCAST) {
4572 V = V.getOperand(0);
4573 EVT SrcVT = V.getValueType();
4574 unsigned NumElems = VT.getVectorNumElements();
4576 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4580 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4581 return (Index == 0) ? V.getOperand(0)
4582 : DAG.getUNDEF(VT.getVectorElementType());
4584 if (V.getOpcode() == ISD::BUILD_VECTOR)
4585 return V.getOperand(Index);
4590 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4591 /// shuffle operation which come from a consecutively from a zero. The
4592 /// search can start in two different directions, from left or right.
4594 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4595 bool ZerosFromLeft, SelectionDAG &DAG) {
4598 while (i < NumElems) {
4599 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4600 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4601 if (!(Elt.getNode() &&
4602 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4610 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4611 /// MaskE correspond consecutively to elements from one of the vector operands,
4612 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4614 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4615 int OpIdx, int NumElems, unsigned &OpNum) {
4616 bool SeenV1 = false;
4617 bool SeenV2 = false;
4619 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4620 int Idx = SVOp->getMaskElt(i);
4621 // Ignore undef indicies
4630 // Only accept consecutive elements from the same vector
4631 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4635 OpNum = SeenV1 ? 0 : 1;
4639 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4640 /// logical left shift of a vector.
4641 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4642 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4643 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4644 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4645 false /* check zeros from right */, DAG);
4651 // Considering the elements in the mask that are not consecutive zeros,
4652 // check if they consecutively come from only one of the source vectors.
4654 // V1 = {X, A, B, C} 0
4656 // vector_shuffle V1, V2 <1, 2, 3, X>
4658 if (!isShuffleMaskConsecutive(SVOp,
4659 0, // Mask Start Index
4660 NumElems-NumZeros-1, // Mask End Index
4661 NumZeros, // Where to start looking in the src vector
4662 NumElems, // Number of elements in vector
4663 OpSrc)) // Which source operand ?
4668 ShVal = SVOp->getOperand(OpSrc);
4672 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4673 /// logical left shift of a vector.
4674 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4675 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4676 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4677 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4678 true /* check zeros from left */, DAG);
4684 // Considering the elements in the mask that are not consecutive zeros,
4685 // check if they consecutively come from only one of the source vectors.
4687 // 0 { A, B, X, X } = V2
4689 // vector_shuffle V1, V2 <X, X, 4, 5>
4691 if (!isShuffleMaskConsecutive(SVOp,
4692 NumZeros, // Mask Start Index
4693 NumElems-1, // Mask End Index
4694 0, // Where to start looking in the src vector
4695 NumElems, // Number of elements in vector
4696 OpSrc)) // Which source operand ?
4701 ShVal = SVOp->getOperand(OpSrc);
4705 /// isVectorShift - Returns true if the shuffle can be implemented as a
4706 /// logical left or right shift of a vector.
4707 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4708 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4709 // Although the logic below support any bitwidth size, there are no
4710 // shift instructions which handle more than 128-bit vectors.
4711 if (SVOp->getValueType(0).getSizeInBits() > 128)
4714 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4715 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4721 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4723 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4724 unsigned NumNonZero, unsigned NumZero,
4726 const TargetLowering &TLI) {
4730 DebugLoc dl = Op.getDebugLoc();
4733 for (unsigned i = 0; i < 16; ++i) {
4734 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4735 if (ThisIsNonZero && First) {
4737 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4739 V = DAG.getUNDEF(MVT::v8i16);
4744 SDValue ThisElt(0, 0), LastElt(0, 0);
4745 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4746 if (LastIsNonZero) {
4747 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4748 MVT::i16, Op.getOperand(i-1));
4750 if (ThisIsNonZero) {
4751 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4752 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4753 ThisElt, DAG.getConstant(8, MVT::i8));
4755 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4759 if (ThisElt.getNode())
4760 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4761 DAG.getIntPtrConstant(i/2));
4765 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4768 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4770 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4771 unsigned NumNonZero, unsigned NumZero,
4773 const TargetLowering &TLI) {
4777 DebugLoc dl = Op.getDebugLoc();
4780 for (unsigned i = 0; i < 8; ++i) {
4781 bool isNonZero = (NonZeros & (1 << i)) != 0;
4785 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4787 V = DAG.getUNDEF(MVT::v8i16);
4790 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4791 MVT::v8i16, V, Op.getOperand(i),
4792 DAG.getIntPtrConstant(i));
4799 /// getVShift - Return a vector logical shift node.
4801 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4802 unsigned NumBits, SelectionDAG &DAG,
4803 const TargetLowering &TLI, DebugLoc dl) {
4804 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4805 EVT ShVT = MVT::v2i64;
4806 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4807 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4808 return DAG.getNode(ISD::BITCAST, dl, VT,
4809 DAG.getNode(Opc, dl, ShVT, SrcOp,
4810 DAG.getConstant(NumBits,
4811 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4815 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4816 SelectionDAG &DAG) const {
4818 // Check if the scalar load can be widened into a vector load. And if
4819 // the address is "base + cst" see if the cst can be "absorbed" into
4820 // the shuffle mask.
4821 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4822 SDValue Ptr = LD->getBasePtr();
4823 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4825 EVT PVT = LD->getValueType(0);
4826 if (PVT != MVT::i32 && PVT != MVT::f32)
4831 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4832 FI = FINode->getIndex();
4834 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4835 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4836 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4837 Offset = Ptr.getConstantOperandVal(1);
4838 Ptr = Ptr.getOperand(0);
4843 // FIXME: 256-bit vector instructions don't require a strict alignment,
4844 // improve this code to support it better.
4845 unsigned RequiredAlign = VT.getSizeInBits()/8;
4846 SDValue Chain = LD->getChain();
4847 // Make sure the stack object alignment is at least 16 or 32.
4848 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4849 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4850 if (MFI->isFixedObjectIndex(FI)) {
4851 // Can't change the alignment. FIXME: It's possible to compute
4852 // the exact stack offset and reference FI + adjust offset instead.
4853 // If someone *really* cares about this. That's the way to implement it.
4856 MFI->setObjectAlignment(FI, RequiredAlign);
4860 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4861 // Ptr + (Offset & ~15).
4864 if ((Offset % RequiredAlign) & 3)
4866 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4868 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4869 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4871 int EltNo = (Offset - StartOffset) >> 2;
4872 int NumElems = VT.getVectorNumElements();
4874 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4875 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4876 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4877 LD->getPointerInfo().getWithOffset(StartOffset),
4878 false, false, false, 0);
4880 // Canonicalize it to a v4i32 or v8i32 shuffle.
4881 SmallVector<int, 8> Mask;
4882 for (int i = 0; i < NumElems; ++i)
4883 Mask.push_back(EltNo);
4885 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4886 return DAG.getNode(ISD::BITCAST, dl, NVT,
4887 DAG.getVectorShuffle(CanonVT, dl, V1,
4888 DAG.getUNDEF(CanonVT),&Mask[0]));
4894 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4895 /// vector of type 'VT', see if the elements can be replaced by a single large
4896 /// load which has the same value as a build_vector whose operands are 'elts'.
4898 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4900 /// FIXME: we'd also like to handle the case where the last elements are zero
4901 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4902 /// There's even a handy isZeroNode for that purpose.
4903 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4904 DebugLoc &DL, SelectionDAG &DAG) {
4905 EVT EltVT = VT.getVectorElementType();
4906 unsigned NumElems = Elts.size();
4908 LoadSDNode *LDBase = NULL;
4909 unsigned LastLoadedElt = -1U;
4911 // For each element in the initializer, see if we've found a load or an undef.
4912 // If we don't find an initial load element, or later load elements are
4913 // non-consecutive, bail out.
4914 for (unsigned i = 0; i < NumElems; ++i) {
4915 SDValue Elt = Elts[i];
4917 if (!Elt.getNode() ||
4918 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4921 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4923 LDBase = cast<LoadSDNode>(Elt.getNode());
4927 if (Elt.getOpcode() == ISD::UNDEF)
4930 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4931 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4936 // If we have found an entire vector of loads and undefs, then return a large
4937 // load of the entire vector width starting at the base pointer. If we found
4938 // consecutive loads for the low half, generate a vzext_load node.
4939 if (LastLoadedElt == NumElems - 1) {
4940 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4941 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4942 LDBase->getPointerInfo(),
4943 LDBase->isVolatile(), LDBase->isNonTemporal(),
4944 LDBase->isInvariant(), 0);
4945 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4946 LDBase->getPointerInfo(),
4947 LDBase->isVolatile(), LDBase->isNonTemporal(),
4948 LDBase->isInvariant(), LDBase->getAlignment());
4949 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4950 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4951 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4952 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4954 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4955 LDBase->getPointerInfo(),
4956 LDBase->getAlignment(),
4957 false/*isVolatile*/, true/*ReadMem*/,
4959 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4964 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4965 /// a vbroadcast node. We support two patterns:
4966 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4967 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4969 /// The scalar load node is returned when a pattern is found,
4970 /// or SDValue() otherwise.
4971 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4972 EVT VT = Op.getValueType();
4975 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4976 V = V.getOperand(0);
4978 //A suspected load to be broadcasted.
4981 switch (V.getOpcode()) {
4983 // Unknown pattern found.
4986 case ISD::BUILD_VECTOR: {
4987 // The BUILD_VECTOR node must be a splat.
4988 if (!isSplatVector(V.getNode()))
4991 Ld = V.getOperand(0);
4993 // The suspected load node has several users. Make sure that all
4994 // of its users are from the BUILD_VECTOR node.
4995 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5000 case ISD::VECTOR_SHUFFLE: {
5001 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5003 // Shuffles must have a splat mask where the first element is
5005 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5008 SDValue Sc = Op.getOperand(0);
5009 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5012 Ld = Sc.getOperand(0);
5014 // The scalar_to_vector node and the suspected
5015 // load node must have exactly one user.
5016 if (!Sc.hasOneUse() || !Ld.hasOneUse())
5022 // The scalar source must be a normal load.
5023 if (!ISD::isNormalLoad(Ld.getNode()))
5026 bool Is256 = VT.getSizeInBits() == 256;
5027 bool Is128 = VT.getSizeInBits() == 128;
5028 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5031 // VBroadcast to YMM
5032 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5033 ScalarSize == 32 || ScalarSize == 64 ))
5036 // VBroadcast to XMM
5037 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5038 ScalarSize == 16 || ScalarSize == 64 ))
5042 // VBroadcast to YMM
5043 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5046 // VBroadcast to XMM
5047 if (Is128 && (ScalarSize == 32))
5051 // Unsupported broadcast.
5056 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5057 DebugLoc dl = Op.getDebugLoc();
5059 EVT VT = Op.getValueType();
5060 EVT ExtVT = VT.getVectorElementType();
5061 unsigned NumElems = Op.getNumOperands();
5063 // Vectors containing all zeros can be matched by pxor and xorps later
5064 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5065 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5066 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5067 if (Op.getValueType() == MVT::v4i32 ||
5068 Op.getValueType() == MVT::v8i32)
5071 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5074 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5075 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5076 // vpcmpeqd on 256-bit vectors.
5077 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5078 if (Op.getValueType() == MVT::v4i32 ||
5079 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5082 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5085 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5086 if (Subtarget->hasAVX() && LD.getNode())
5087 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5089 unsigned EVTBits = ExtVT.getSizeInBits();
5091 unsigned NumZero = 0;
5092 unsigned NumNonZero = 0;
5093 unsigned NonZeros = 0;
5094 bool IsAllConstants = true;
5095 SmallSet<SDValue, 8> Values;
5096 for (unsigned i = 0; i < NumElems; ++i) {
5097 SDValue Elt = Op.getOperand(i);
5098 if (Elt.getOpcode() == ISD::UNDEF)
5101 if (Elt.getOpcode() != ISD::Constant &&
5102 Elt.getOpcode() != ISD::ConstantFP)
5103 IsAllConstants = false;
5104 if (X86::isZeroNode(Elt))
5107 NonZeros |= (1 << i);
5112 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5113 if (NumNonZero == 0)
5114 return DAG.getUNDEF(VT);
5116 // Special case for single non-zero, non-undef, element.
5117 if (NumNonZero == 1) {
5118 unsigned Idx = CountTrailingZeros_32(NonZeros);
5119 SDValue Item = Op.getOperand(Idx);
5121 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5122 // the value are obviously zero, truncate the value to i32 and do the
5123 // insertion that way. Only do this if the value is non-constant or if the
5124 // value is a constant being inserted into element 0. It is cheaper to do
5125 // a constant pool load than it is to do a movd + shuffle.
5126 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5127 (!IsAllConstants || Idx == 0)) {
5128 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5130 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5131 EVT VecVT = MVT::v4i32;
5132 unsigned VecElts = 4;
5134 // Truncate the value (which may itself be a constant) to i32, and
5135 // convert it to a vector with movd (S2V+shuffle to zero extend).
5136 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5137 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5138 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5139 Subtarget->hasXMMInt(), DAG);
5141 // Now we have our 32-bit value zero extended in the low element of
5142 // a vector. If Idx != 0, swizzle it into place.
5144 SmallVector<int, 4> Mask;
5145 Mask.push_back(Idx);
5146 for (unsigned i = 1; i != VecElts; ++i)
5148 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5149 DAG.getUNDEF(Item.getValueType()),
5152 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5156 // If we have a constant or non-constant insertion into the low element of
5157 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5158 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5159 // depending on what the source datatype is.
5162 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5164 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5165 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5166 if (VT.getSizeInBits() == 256) {
5167 EVT VT128 = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems / 2);
5168 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Item);
5169 SDValue ZeroVec = getZeroVector(VT, true, DAG, dl);
5170 return Insert128BitVector(ZeroVec, Item, DAG.getConstant(0, MVT::i32),
5173 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5174 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5175 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5176 return getShuffleVectorZeroOrUndef(Item, 0, true,
5177 Subtarget->hasXMMInt(), DAG);
5180 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5181 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5182 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5183 if (VT.getSizeInBits() == 256) {
5184 SDValue ZeroVec = getZeroVector(MVT::v8i32, true, DAG, dl);
5185 Item = Insert128BitVector(ZeroVec, Item, DAG.getConstant(0, MVT::i32),
5188 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5189 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5190 Subtarget->hasXMMInt(), DAG);
5192 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5196 // Is it a vector logical left shift?
5197 if (NumElems == 2 && Idx == 1 &&
5198 X86::isZeroNode(Op.getOperand(0)) &&
5199 !X86::isZeroNode(Op.getOperand(1))) {
5200 unsigned NumBits = VT.getSizeInBits();
5201 return getVShift(true, VT,
5202 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5203 VT, Op.getOperand(1)),
5204 NumBits/2, DAG, *this, dl);
5207 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5210 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5211 // is a non-constant being inserted into an element other than the low one,
5212 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5213 // movd/movss) to move this into the low element, then shuffle it into
5215 if (EVTBits == 32) {
5216 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5218 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5219 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5220 Subtarget->hasXMMInt(), DAG);
5221 SmallVector<int, 8> MaskVec;
5222 for (unsigned i = 0; i < NumElems; i++)
5223 MaskVec.push_back(i == Idx ? 0 : 1);
5224 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5228 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5229 if (Values.size() == 1) {
5230 if (EVTBits == 32) {
5231 // Instead of a shuffle like this:
5232 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5233 // Check if it's possible to issue this instead.
5234 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5235 unsigned Idx = CountTrailingZeros_32(NonZeros);
5236 SDValue Item = Op.getOperand(Idx);
5237 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5238 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5243 // A vector full of immediates; various special cases are already
5244 // handled, so this is best done with a single constant-pool load.
5248 // For AVX-length vectors, build the individual 128-bit pieces and use
5249 // shuffles to put them in place.
5250 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5251 SmallVector<SDValue, 32> V;
5252 for (unsigned i = 0; i < NumElems; ++i)
5253 V.push_back(Op.getOperand(i));
5255 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5257 // Build both the lower and upper subvector.
5258 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5259 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5262 // Recreate the wider vector with the lower and upper part.
5263 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5264 DAG.getConstant(0, MVT::i32), DAG, dl);
5265 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5269 // Let legalizer expand 2-wide build_vectors.
5270 if (EVTBits == 64) {
5271 if (NumNonZero == 1) {
5272 // One half is zero or undef.
5273 unsigned Idx = CountTrailingZeros_32(NonZeros);
5274 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5275 Op.getOperand(Idx));
5276 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5277 Subtarget->hasXMMInt(), DAG);
5282 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5283 if (EVTBits == 8 && NumElems == 16) {
5284 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5286 if (V.getNode()) return V;
5289 if (EVTBits == 16 && NumElems == 8) {
5290 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5292 if (V.getNode()) return V;
5295 // If element VT is == 32 bits, turn it into a number of shuffles.
5296 SmallVector<SDValue, 8> V;
5298 if (NumElems == 4 && NumZero > 0) {
5299 for (unsigned i = 0; i < 4; ++i) {
5300 bool isZero = !(NonZeros & (1 << i));
5302 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5304 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5307 for (unsigned i = 0; i < 2; ++i) {
5308 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5311 V[i] = V[i*2]; // Must be a zero vector.
5314 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5317 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5320 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5325 SmallVector<int, 8> MaskVec;
5326 bool Reverse = (NonZeros & 0x3) == 2;
5327 for (unsigned i = 0; i < 2; ++i)
5328 MaskVec.push_back(Reverse ? 1-i : i);
5329 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5330 for (unsigned i = 0; i < 2; ++i)
5331 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5332 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5335 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5336 // Check for a build vector of consecutive loads.
5337 for (unsigned i = 0; i < NumElems; ++i)
5338 V[i] = Op.getOperand(i);
5340 // Check for elements which are consecutive loads.
5341 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5345 // For SSE 4.1, use insertps to put the high elements into the low element.
5346 if (getSubtarget()->hasSSE41orAVX()) {
5348 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5349 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5351 Result = DAG.getUNDEF(VT);
5353 for (unsigned i = 1; i < NumElems; ++i) {
5354 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5355 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5356 Op.getOperand(i), DAG.getIntPtrConstant(i));
5361 // Otherwise, expand into a number of unpckl*, start by extending each of
5362 // our (non-undef) elements to the full vector width with the element in the
5363 // bottom slot of the vector (which generates no code for SSE).
5364 for (unsigned i = 0; i < NumElems; ++i) {
5365 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5366 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5368 V[i] = DAG.getUNDEF(VT);
5371 // Next, we iteratively mix elements, e.g. for v4f32:
5372 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5373 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5374 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5375 unsigned EltStride = NumElems >> 1;
5376 while (EltStride != 0) {
5377 for (unsigned i = 0; i < EltStride; ++i) {
5378 // If V[i+EltStride] is undef and this is the first round of mixing,
5379 // then it is safe to just drop this shuffle: V[i] is already in the
5380 // right place, the one element (since it's the first round) being
5381 // inserted as undef can be dropped. This isn't safe for successive
5382 // rounds because they will permute elements within both vectors.
5383 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5384 EltStride == NumElems/2)
5387 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5396 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5397 // them in a MMX register. This is better than doing a stack convert.
5398 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5399 DebugLoc dl = Op.getDebugLoc();
5400 EVT ResVT = Op.getValueType();
5402 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5403 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5405 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5406 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5407 InVec = Op.getOperand(1);
5408 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5409 unsigned NumElts = ResVT.getVectorNumElements();
5410 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5411 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5412 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5414 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5415 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5416 Mask[0] = 0; Mask[1] = 2;
5417 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5419 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5422 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5423 // to create 256-bit vectors from two other 128-bit ones.
5424 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5425 DebugLoc dl = Op.getDebugLoc();
5426 EVT ResVT = Op.getValueType();
5428 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5430 SDValue V1 = Op.getOperand(0);
5431 SDValue V2 = Op.getOperand(1);
5432 unsigned NumElems = ResVT.getVectorNumElements();
5434 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5435 DAG.getConstant(0, MVT::i32), DAG, dl);
5436 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5441 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5442 EVT ResVT = Op.getValueType();
5444 assert(Op.getNumOperands() == 2);
5445 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5446 "Unsupported CONCAT_VECTORS for value type");
5448 // We support concatenate two MMX registers and place them in a MMX register.
5449 // This is better than doing a stack convert.
5450 if (ResVT.is128BitVector())
5451 return LowerMMXCONCAT_VECTORS(Op, DAG);
5453 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5454 // from two other 128-bit ones.
5455 return LowerAVXCONCAT_VECTORS(Op, DAG);
5458 // v8i16 shuffles - Prefer shuffles in the following order:
5459 // 1. [all] pshuflw, pshufhw, optional move
5460 // 2. [ssse3] 1 x pshufb
5461 // 3. [ssse3] 2 x pshufb + 1 x por
5462 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5464 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5465 SelectionDAG &DAG) const {
5466 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5467 SDValue V1 = SVOp->getOperand(0);
5468 SDValue V2 = SVOp->getOperand(1);
5469 DebugLoc dl = SVOp->getDebugLoc();
5470 SmallVector<int, 8> MaskVals;
5472 // Determine if more than 1 of the words in each of the low and high quadwords
5473 // of the result come from the same quadword of one of the two inputs. Undef
5474 // mask values count as coming from any quadword, for better codegen.
5475 unsigned LoQuad[] = { 0, 0, 0, 0 };
5476 unsigned HiQuad[] = { 0, 0, 0, 0 };
5477 BitVector InputQuads(4);
5478 for (unsigned i = 0; i < 8; ++i) {
5479 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5480 int EltIdx = SVOp->getMaskElt(i);
5481 MaskVals.push_back(EltIdx);
5490 InputQuads.set(EltIdx / 4);
5493 int BestLoQuad = -1;
5494 unsigned MaxQuad = 1;
5495 for (unsigned i = 0; i < 4; ++i) {
5496 if (LoQuad[i] > MaxQuad) {
5498 MaxQuad = LoQuad[i];
5502 int BestHiQuad = -1;
5504 for (unsigned i = 0; i < 4; ++i) {
5505 if (HiQuad[i] > MaxQuad) {
5507 MaxQuad = HiQuad[i];
5511 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5512 // of the two input vectors, shuffle them into one input vector so only a
5513 // single pshufb instruction is necessary. If There are more than 2 input
5514 // quads, disable the next transformation since it does not help SSSE3.
5515 bool V1Used = InputQuads[0] || InputQuads[1];
5516 bool V2Used = InputQuads[2] || InputQuads[3];
5517 if (Subtarget->hasSSSE3orAVX()) {
5518 if (InputQuads.count() == 2 && V1Used && V2Used) {
5519 BestLoQuad = InputQuads.find_first();
5520 BestHiQuad = InputQuads.find_next(BestLoQuad);
5522 if (InputQuads.count() > 2) {
5528 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5529 // the shuffle mask. If a quad is scored as -1, that means that it contains
5530 // words from all 4 input quadwords.
5532 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5533 SmallVector<int, 8> MaskV;
5534 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5535 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5536 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5537 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5538 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5539 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5541 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5542 // source words for the shuffle, to aid later transformations.
5543 bool AllWordsInNewV = true;
5544 bool InOrder[2] = { true, true };
5545 for (unsigned i = 0; i != 8; ++i) {
5546 int idx = MaskVals[i];
5548 InOrder[i/4] = false;
5549 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5551 AllWordsInNewV = false;
5555 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5556 if (AllWordsInNewV) {
5557 for (int i = 0; i != 8; ++i) {
5558 int idx = MaskVals[i];
5561 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5562 if ((idx != i) && idx < 4)
5564 if ((idx != i) && idx > 3)
5573 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5574 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5575 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5576 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5577 unsigned TargetMask = 0;
5578 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5579 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5580 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5581 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5582 V1 = NewV.getOperand(0);
5583 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5587 // If we have SSSE3, and all words of the result are from 1 input vector,
5588 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5589 // is present, fall back to case 4.
5590 if (Subtarget->hasSSSE3orAVX()) {
5591 SmallVector<SDValue,16> pshufbMask;
5593 // If we have elements from both input vectors, set the high bit of the
5594 // shuffle mask element to zero out elements that come from V2 in the V1
5595 // mask, and elements that come from V1 in the V2 mask, so that the two
5596 // results can be OR'd together.
5597 bool TwoInputs = V1Used && V2Used;
5598 for (unsigned i = 0; i != 8; ++i) {
5599 int EltIdx = MaskVals[i] * 2;
5600 if (TwoInputs && (EltIdx >= 16)) {
5601 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5602 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5605 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5606 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5608 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5609 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5610 DAG.getNode(ISD::BUILD_VECTOR, dl,
5611 MVT::v16i8, &pshufbMask[0], 16));
5613 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5615 // Calculate the shuffle mask for the second input, shuffle it, and
5616 // OR it with the first shuffled input.
5618 for (unsigned i = 0; i != 8; ++i) {
5619 int EltIdx = MaskVals[i] * 2;
5621 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5622 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5625 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5626 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5628 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5629 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5630 DAG.getNode(ISD::BUILD_VECTOR, dl,
5631 MVT::v16i8, &pshufbMask[0], 16));
5632 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5633 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5636 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5637 // and update MaskVals with new element order.
5638 BitVector InOrder(8);
5639 if (BestLoQuad >= 0) {
5640 SmallVector<int, 8> MaskV;
5641 for (int i = 0; i != 4; ++i) {
5642 int idx = MaskVals[i];
5644 MaskV.push_back(-1);
5646 } else if ((idx / 4) == BestLoQuad) {
5647 MaskV.push_back(idx & 3);
5650 MaskV.push_back(-1);
5653 for (unsigned i = 4; i != 8; ++i)
5655 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5658 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5659 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5661 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5665 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5666 // and update MaskVals with the new element order.
5667 if (BestHiQuad >= 0) {
5668 SmallVector<int, 8> MaskV;
5669 for (unsigned i = 0; i != 4; ++i)
5671 for (unsigned i = 4; i != 8; ++i) {
5672 int idx = MaskVals[i];
5674 MaskV.push_back(-1);
5676 } else if ((idx / 4) == BestHiQuad) {
5677 MaskV.push_back((idx & 3) + 4);
5680 MaskV.push_back(-1);
5683 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5686 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5687 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5689 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5693 // In case BestHi & BestLo were both -1, which means each quadword has a word
5694 // from each of the four input quadwords, calculate the InOrder bitvector now
5695 // before falling through to the insert/extract cleanup.
5696 if (BestLoQuad == -1 && BestHiQuad == -1) {
5698 for (int i = 0; i != 8; ++i)
5699 if (MaskVals[i] < 0 || MaskVals[i] == i)
5703 // The other elements are put in the right place using pextrw and pinsrw.
5704 for (unsigned i = 0; i != 8; ++i) {
5707 int EltIdx = MaskVals[i];
5710 SDValue ExtOp = (EltIdx < 8)
5711 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5712 DAG.getIntPtrConstant(EltIdx))
5713 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5714 DAG.getIntPtrConstant(EltIdx - 8));
5715 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5716 DAG.getIntPtrConstant(i));
5721 // v16i8 shuffles - Prefer shuffles in the following order:
5722 // 1. [ssse3] 1 x pshufb
5723 // 2. [ssse3] 2 x pshufb + 1 x por
5724 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5726 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5728 const X86TargetLowering &TLI) {
5729 SDValue V1 = SVOp->getOperand(0);
5730 SDValue V2 = SVOp->getOperand(1);
5731 DebugLoc dl = SVOp->getDebugLoc();
5732 SmallVector<int, 16> MaskVals;
5733 SVOp->getMask(MaskVals);
5735 // If we have SSSE3, case 1 is generated when all result bytes come from
5736 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5737 // present, fall back to case 3.
5738 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5741 for (unsigned i = 0; i < 16; ++i) {
5742 int EltIdx = MaskVals[i];
5751 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5752 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5753 SmallVector<SDValue,16> pshufbMask;
5755 // If all result elements are from one input vector, then only translate
5756 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5758 // Otherwise, we have elements from both input vectors, and must zero out
5759 // elements that come from V2 in the first mask, and V1 in the second mask
5760 // so that we can OR them together.
5761 bool TwoInputs = !(V1Only || V2Only);
5762 for (unsigned i = 0; i != 16; ++i) {
5763 int EltIdx = MaskVals[i];
5764 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5765 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5768 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5770 // If all the elements are from V2, assign it to V1 and return after
5771 // building the first pshufb.
5774 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5775 DAG.getNode(ISD::BUILD_VECTOR, dl,
5776 MVT::v16i8, &pshufbMask[0], 16));
5780 // Calculate the shuffle mask for the second input, shuffle it, and
5781 // OR it with the first shuffled input.
5783 for (unsigned i = 0; i != 16; ++i) {
5784 int EltIdx = MaskVals[i];
5786 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5789 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5791 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5792 DAG.getNode(ISD::BUILD_VECTOR, dl,
5793 MVT::v16i8, &pshufbMask[0], 16));
5794 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5797 // No SSSE3 - Calculate in place words and then fix all out of place words
5798 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5799 // the 16 different words that comprise the two doublequadword input vectors.
5800 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5801 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5802 SDValue NewV = V2Only ? V2 : V1;
5803 for (int i = 0; i != 8; ++i) {
5804 int Elt0 = MaskVals[i*2];
5805 int Elt1 = MaskVals[i*2+1];
5807 // This word of the result is all undef, skip it.
5808 if (Elt0 < 0 && Elt1 < 0)
5811 // This word of the result is already in the correct place, skip it.
5812 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5814 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5817 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5818 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5821 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5822 // using a single extract together, load it and store it.
5823 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5824 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5825 DAG.getIntPtrConstant(Elt1 / 2));
5826 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5827 DAG.getIntPtrConstant(i));
5831 // If Elt1 is defined, extract it from the appropriate source. If the
5832 // source byte is not also odd, shift the extracted word left 8 bits
5833 // otherwise clear the bottom 8 bits if we need to do an or.
5835 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5836 DAG.getIntPtrConstant(Elt1 / 2));
5837 if ((Elt1 & 1) == 0)
5838 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5840 TLI.getShiftAmountTy(InsElt.getValueType())));
5842 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5843 DAG.getConstant(0xFF00, MVT::i16));
5845 // If Elt0 is defined, extract it from the appropriate source. If the
5846 // source byte is not also even, shift the extracted word right 8 bits. If
5847 // Elt1 was also defined, OR the extracted values together before
5848 // inserting them in the result.
5850 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5851 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5852 if ((Elt0 & 1) != 0)
5853 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5855 TLI.getShiftAmountTy(InsElt0.getValueType())));
5857 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5858 DAG.getConstant(0x00FF, MVT::i16));
5859 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5862 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5863 DAG.getIntPtrConstant(i));
5865 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5868 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5869 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5870 /// done when every pair / quad of shuffle mask elements point to elements in
5871 /// the right sequence. e.g.
5872 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5874 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5875 SelectionDAG &DAG, DebugLoc dl) {
5876 EVT VT = SVOp->getValueType(0);
5877 SDValue V1 = SVOp->getOperand(0);
5878 SDValue V2 = SVOp->getOperand(1);
5879 unsigned NumElems = VT.getVectorNumElements();
5880 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5882 switch (VT.getSimpleVT().SimpleTy) {
5883 default: assert(false && "Unexpected!");
5884 case MVT::v4f32: NewVT = MVT::v2f64; break;
5885 case MVT::v4i32: NewVT = MVT::v2i64; break;
5886 case MVT::v8i16: NewVT = MVT::v4i32; break;
5887 case MVT::v16i8: NewVT = MVT::v4i32; break;
5890 int Scale = NumElems / NewWidth;
5891 SmallVector<int, 8> MaskVec;
5892 for (unsigned i = 0; i < NumElems; i += Scale) {
5894 for (int j = 0; j < Scale; ++j) {
5895 int EltIdx = SVOp->getMaskElt(i+j);
5899 StartIdx = EltIdx - (EltIdx % Scale);
5900 if (EltIdx != StartIdx + j)
5904 MaskVec.push_back(-1);
5906 MaskVec.push_back(StartIdx / Scale);
5909 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5910 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5911 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5914 /// getVZextMovL - Return a zero-extending vector move low node.
5916 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5917 SDValue SrcOp, SelectionDAG &DAG,
5918 const X86Subtarget *Subtarget, DebugLoc dl) {
5919 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5920 LoadSDNode *LD = NULL;
5921 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5922 LD = dyn_cast<LoadSDNode>(SrcOp);
5924 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5926 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5927 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5928 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5929 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5930 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5932 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5933 return DAG.getNode(ISD::BITCAST, dl, VT,
5934 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5935 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5943 return DAG.getNode(ISD::BITCAST, dl, VT,
5944 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5945 DAG.getNode(ISD::BITCAST, dl,
5949 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5950 /// shuffle node referes to only one lane in the sources.
5951 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5952 EVT VT = SVOp->getValueType(0);
5953 int NumElems = VT.getVectorNumElements();
5954 int HalfSize = NumElems/2;
5955 SmallVector<int, 16> M;
5957 bool MatchA = false, MatchB = false;
5959 for (int l = 0; l < NumElems*2; l += HalfSize) {
5960 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5966 for (int l = 0; l < NumElems*2; l += HalfSize) {
5967 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5973 return MatchA && MatchB;
5976 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5977 /// which could not be matched by any known target speficic shuffle
5979 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5980 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5981 // If each half of a vector shuffle node referes to only one lane in the
5982 // source vectors, extract each used 128-bit lane and shuffle them using
5983 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5984 // the work to the legalizer.
5985 DebugLoc dl = SVOp->getDebugLoc();
5986 EVT VT = SVOp->getValueType(0);
5987 int NumElems = VT.getVectorNumElements();
5988 int HalfSize = NumElems/2;
5990 // Extract the reference for each half
5991 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5992 int FstVecOpNum = 0, SndVecOpNum = 0;
5993 for (int i = 0; i < HalfSize; ++i) {
5994 int Elt = SVOp->getMaskElt(i);
5995 if (SVOp->getMaskElt(i) < 0)
5997 FstVecOpNum = Elt/NumElems;
5998 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6001 for (int i = HalfSize; i < NumElems; ++i) {
6002 int Elt = SVOp->getMaskElt(i);
6003 if (SVOp->getMaskElt(i) < 0)
6005 SndVecOpNum = Elt/NumElems;
6006 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6010 // Extract the subvectors
6011 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6012 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6013 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6014 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6016 // Generate 128-bit shuffles
6017 SmallVector<int, 16> MaskV1, MaskV2;
6018 for (int i = 0; i < HalfSize; ++i) {
6019 int Elt = SVOp->getMaskElt(i);
6020 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6022 for (int i = HalfSize; i < NumElems; ++i) {
6023 int Elt = SVOp->getMaskElt(i);
6024 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6027 EVT NVT = V1.getValueType();
6028 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6029 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6031 // Concatenate the result back
6032 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6033 DAG.getConstant(0, MVT::i32), DAG, dl);
6034 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6041 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6042 /// 4 elements, and match them with several different shuffle types.
6044 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6045 SDValue V1 = SVOp->getOperand(0);
6046 SDValue V2 = SVOp->getOperand(1);
6047 DebugLoc dl = SVOp->getDebugLoc();
6048 EVT VT = SVOp->getValueType(0);
6050 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6052 SmallVector<std::pair<int, int>, 8> Locs;
6054 SmallVector<int, 8> Mask1(4U, -1);
6055 SmallVector<int, 8> PermMask;
6056 SVOp->getMask(PermMask);
6060 for (unsigned i = 0; i != 4; ++i) {
6061 int Idx = PermMask[i];
6063 Locs[i] = std::make_pair(-1, -1);
6065 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6067 Locs[i] = std::make_pair(0, NumLo);
6071 Locs[i] = std::make_pair(1, NumHi);
6073 Mask1[2+NumHi] = Idx;
6079 if (NumLo <= 2 && NumHi <= 2) {
6080 // If no more than two elements come from either vector. This can be
6081 // implemented with two shuffles. First shuffle gather the elements.
6082 // The second shuffle, which takes the first shuffle as both of its
6083 // vector operands, put the elements into the right order.
6084 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6086 SmallVector<int, 8> Mask2(4U, -1);
6088 for (unsigned i = 0; i != 4; ++i) {
6089 if (Locs[i].first == -1)
6092 unsigned Idx = (i < 2) ? 0 : 4;
6093 Idx += Locs[i].first * 2 + Locs[i].second;
6098 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6099 } else if (NumLo == 3 || NumHi == 3) {
6100 // Otherwise, we must have three elements from one vector, call it X, and
6101 // one element from the other, call it Y. First, use a shufps to build an
6102 // intermediate vector with the one element from Y and the element from X
6103 // that will be in the same half in the final destination (the indexes don't
6104 // matter). Then, use a shufps to build the final vector, taking the half
6105 // containing the element from Y from the intermediate, and the other half
6108 // Normalize it so the 3 elements come from V1.
6109 CommuteVectorShuffleMask(PermMask, 4);
6113 // Find the element from V2.
6115 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6116 int Val = PermMask[HiIndex];
6123 Mask1[0] = PermMask[HiIndex];
6125 Mask1[2] = PermMask[HiIndex^1];
6127 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6130 Mask1[0] = PermMask[0];
6131 Mask1[1] = PermMask[1];
6132 Mask1[2] = HiIndex & 1 ? 6 : 4;
6133 Mask1[3] = HiIndex & 1 ? 4 : 6;
6134 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6136 Mask1[0] = HiIndex & 1 ? 2 : 0;
6137 Mask1[1] = HiIndex & 1 ? 0 : 2;
6138 Mask1[2] = PermMask[2];
6139 Mask1[3] = PermMask[3];
6144 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6148 // Break it into (shuffle shuffle_hi, shuffle_lo).
6151 SmallVector<int,8> LoMask(4U, -1);
6152 SmallVector<int,8> HiMask(4U, -1);
6154 SmallVector<int,8> *MaskPtr = &LoMask;
6155 unsigned MaskIdx = 0;
6158 for (unsigned i = 0; i != 4; ++i) {
6165 int Idx = PermMask[i];
6167 Locs[i] = std::make_pair(-1, -1);
6168 } else if (Idx < 4) {
6169 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6170 (*MaskPtr)[LoIdx] = Idx;
6173 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6174 (*MaskPtr)[HiIdx] = Idx;
6179 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6180 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6181 SmallVector<int, 8> MaskOps;
6182 for (unsigned i = 0; i != 4; ++i) {
6183 if (Locs[i].first == -1) {
6184 MaskOps.push_back(-1);
6186 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6187 MaskOps.push_back(Idx);
6190 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6193 static bool MayFoldVectorLoad(SDValue V) {
6194 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6195 V = V.getOperand(0);
6196 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6197 V = V.getOperand(0);
6198 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6199 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6200 // BUILD_VECTOR (load), undef
6201 V = V.getOperand(0);
6207 // FIXME: the version above should always be used. Since there's
6208 // a bug where several vector shuffles can't be folded because the
6209 // DAG is not updated during lowering and a node claims to have two
6210 // uses while it only has one, use this version, and let isel match
6211 // another instruction if the load really happens to have more than
6212 // one use. Remove this version after this bug get fixed.
6213 // rdar://8434668, PR8156
6214 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6215 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6216 V = V.getOperand(0);
6217 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6218 V = V.getOperand(0);
6219 if (ISD::isNormalLoad(V.getNode()))
6224 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6225 /// a vector extract, and if both can be later optimized into a single load.
6226 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6227 /// here because otherwise a target specific shuffle node is going to be
6228 /// emitted for this shuffle, and the optimization not done.
6229 /// FIXME: This is probably not the best approach, but fix the problem
6230 /// until the right path is decided.
6232 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6233 const TargetLowering &TLI) {
6234 EVT VT = V.getValueType();
6235 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6237 // Be sure that the vector shuffle is present in a pattern like this:
6238 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6242 SDNode *N = *V.getNode()->use_begin();
6243 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6246 SDValue EltNo = N->getOperand(1);
6247 if (!isa<ConstantSDNode>(EltNo))
6250 // If the bit convert changed the number of elements, it is unsafe
6251 // to examine the mask.
6252 bool HasShuffleIntoBitcast = false;
6253 if (V.getOpcode() == ISD::BITCAST) {
6254 EVT SrcVT = V.getOperand(0).getValueType();
6255 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6257 V = V.getOperand(0);
6258 HasShuffleIntoBitcast = true;
6261 // Select the input vector, guarding against out of range extract vector.
6262 unsigned NumElems = VT.getVectorNumElements();
6263 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6264 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6265 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6267 // Skip one more bit_convert if necessary
6268 if (V.getOpcode() == ISD::BITCAST)
6269 V = V.getOperand(0);
6271 if (ISD::isNormalLoad(V.getNode())) {
6272 // Is the original load suitable?
6273 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6275 // FIXME: avoid the multi-use bug that is preventing lots of
6276 // of foldings to be detected, this is still wrong of course, but
6277 // give the temporary desired behavior, and if it happens that
6278 // the load has real more uses, during isel it will not fold, and
6279 // will generate poor code.
6280 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6283 if (!HasShuffleIntoBitcast)
6286 // If there's a bitcast before the shuffle, check if the load type and
6287 // alignment is valid.
6288 unsigned Align = LN0->getAlignment();
6290 TLI.getTargetData()->getABITypeAlignment(
6291 VT.getTypeForEVT(*DAG.getContext()));
6293 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6301 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6302 EVT VT = Op.getValueType();
6304 // Canonizalize to v2f64.
6305 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6306 return DAG.getNode(ISD::BITCAST, dl, VT,
6307 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6312 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6314 SDValue V1 = Op.getOperand(0);
6315 SDValue V2 = Op.getOperand(1);
6316 EVT VT = Op.getValueType();
6318 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6320 if (HasXMMInt && VT == MVT::v2f64)
6321 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6323 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6324 return DAG.getNode(ISD::BITCAST, dl, VT,
6325 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6326 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6327 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6331 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6332 SDValue V1 = Op.getOperand(0);
6333 SDValue V2 = Op.getOperand(1);
6334 EVT VT = Op.getValueType();
6336 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6337 "unsupported shuffle type");
6339 if (V2.getOpcode() == ISD::UNDEF)
6343 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6347 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6348 SDValue V1 = Op.getOperand(0);
6349 SDValue V2 = Op.getOperand(1);
6350 EVT VT = Op.getValueType();
6351 unsigned NumElems = VT.getVectorNumElements();
6353 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6354 // operand of these instructions is only memory, so check if there's a
6355 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6357 bool CanFoldLoad = false;
6359 // Trivial case, when V2 comes from a load.
6360 if (MayFoldVectorLoad(V2))
6363 // When V1 is a load, it can be folded later into a store in isel, example:
6364 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6366 // (MOVLPSmr addr:$src1, VR128:$src2)
6367 // So, recognize this potential and also use MOVLPS or MOVLPD
6368 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6371 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6373 if (HasXMMInt && NumElems == 2)
6374 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6377 // If we don't care about the second element, procede to use movss.
6378 if (SVOp->getMaskElt(1) != -1)
6379 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6382 // movl and movlp will both match v2i64, but v2i64 is never matched by
6383 // movl earlier because we make it strict to avoid messing with the movlp load
6384 // folding logic (see the code above getMOVLP call). Match it here then,
6385 // this is horrible, but will stay like this until we move all shuffle
6386 // matching to x86 specific nodes. Note that for the 1st condition all
6387 // types are matched with movsd.
6389 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6390 // as to remove this logic from here, as much as possible
6391 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6392 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6393 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6396 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6398 // Invert the operand order and use SHUFPS to match it.
6399 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6400 X86::getShuffleSHUFImmediate(SVOp), DAG);
6404 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6405 const TargetLowering &TLI,
6406 const X86Subtarget *Subtarget) {
6407 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6408 EVT VT = Op.getValueType();
6409 DebugLoc dl = Op.getDebugLoc();
6410 SDValue V1 = Op.getOperand(0);
6411 SDValue V2 = Op.getOperand(1);
6413 if (isZeroShuffle(SVOp))
6414 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6416 // Handle splat operations
6417 if (SVOp->isSplat()) {
6418 unsigned NumElem = VT.getVectorNumElements();
6419 int Size = VT.getSizeInBits();
6420 // Special case, this is the only place now where it's allowed to return
6421 // a vector_shuffle operation without using a target specific node, because
6422 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6423 // this be moved to DAGCombine instead?
6424 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6427 // Use vbroadcast whenever the splat comes from a foldable load
6428 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6429 if (Subtarget->hasAVX() && LD.getNode())
6430 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6432 // Handle splats by matching through known shuffle masks
6433 if ((Size == 128 && NumElem <= 4) ||
6434 (Size == 256 && NumElem < 8))
6437 // All remaning splats are promoted to target supported vector shuffles.
6438 return PromoteSplat(SVOp, DAG);
6441 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6443 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6444 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6445 if (NewOp.getNode())
6446 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6447 } else if ((VT == MVT::v4i32 ||
6448 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6449 // FIXME: Figure out a cleaner way to do this.
6450 // Try to make use of movq to zero out the top part.
6451 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6452 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6453 if (NewOp.getNode()) {
6454 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6455 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6456 DAG, Subtarget, dl);
6458 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6459 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6460 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6461 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6462 DAG, Subtarget, dl);
6469 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6470 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6471 SDValue V1 = Op.getOperand(0);
6472 SDValue V2 = Op.getOperand(1);
6473 EVT VT = Op.getValueType();
6474 DebugLoc dl = Op.getDebugLoc();
6475 unsigned NumElems = VT.getVectorNumElements();
6476 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6477 bool V1IsSplat = false;
6478 bool V2IsSplat = false;
6479 bool HasXMMInt = Subtarget->hasXMMInt();
6480 bool HasAVX = Subtarget->hasAVX();
6481 bool HasAVX2 = Subtarget->hasAVX2();
6482 MachineFunction &MF = DAG.getMachineFunction();
6483 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6485 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6487 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6489 // Vector shuffle lowering takes 3 steps:
6491 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6492 // narrowing and commutation of operands should be handled.
6493 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6495 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6496 // so the shuffle can be broken into other shuffles and the legalizer can
6497 // try the lowering again.
6499 // The general idea is that no vector_shuffle operation should be left to
6500 // be matched during isel, all of them must be converted to a target specific
6503 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6504 // narrowing and commutation of operands should be handled. The actual code
6505 // doesn't include all of those, work in progress...
6506 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6507 if (NewOp.getNode())
6510 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6511 // unpckh_undef). Only use pshufd if speed is more important than size.
6512 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6513 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6514 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6515 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6517 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6518 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6519 return getMOVDDup(Op, dl, V1, DAG);
6521 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6522 return getMOVHighToLow(Op, dl, DAG);
6524 // Use to match splats
6525 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6526 (VT == MVT::v2f64 || VT == MVT::v2i64))
6527 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6529 if (X86::isPSHUFDMask(SVOp)) {
6530 // The actual implementation will match the mask in the if above and then
6531 // during isel it can match several different instructions, not only pshufd
6532 // as its name says, sad but true, emulate the behavior for now...
6533 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6534 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6536 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6538 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6539 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6541 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6545 // Check if this can be converted into a logical shift.
6546 bool isLeft = false;
6549 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6550 if (isShift && ShVal.hasOneUse()) {
6551 // If the shifted value has multiple uses, it may be cheaper to use
6552 // v_set0 + movlhps or movhlps, etc.
6553 EVT EltVT = VT.getVectorElementType();
6554 ShAmt *= EltVT.getSizeInBits();
6555 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6558 if (X86::isMOVLMask(SVOp)) {
6559 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6560 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6561 if (!X86::isMOVLPMask(SVOp)) {
6562 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6563 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6565 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6566 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6570 // FIXME: fold these into legal mask.
6571 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6572 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6574 if (X86::isMOVHLPSMask(SVOp))
6575 return getMOVHighToLow(Op, dl, DAG);
6577 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6578 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6580 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6581 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6583 if (X86::isMOVLPMask(SVOp))
6584 return getMOVLP(Op, dl, DAG, HasXMMInt);
6586 if (ShouldXformToMOVHLPS(SVOp) ||
6587 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6588 return CommuteVectorShuffle(SVOp, DAG);
6591 // No better options. Use a vshl / vsrl.
6592 EVT EltVT = VT.getVectorElementType();
6593 ShAmt *= EltVT.getSizeInBits();
6594 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6597 bool Commuted = false;
6598 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6599 // 1,1,1,1 -> v8i16 though.
6600 V1IsSplat = isSplatVector(V1.getNode());
6601 V2IsSplat = isSplatVector(V2.getNode());
6603 // Canonicalize the splat or undef, if present, to be on the RHS.
6604 if (V1IsSplat && !V2IsSplat) {
6605 Op = CommuteVectorShuffle(SVOp, DAG);
6606 SVOp = cast<ShuffleVectorSDNode>(Op);
6607 V1 = SVOp->getOperand(0);
6608 V2 = SVOp->getOperand(1);
6609 std::swap(V1IsSplat, V2IsSplat);
6613 SmallVector<int, 32> M;
6616 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6617 // Shuffling low element of v1 into undef, just return v1.
6620 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6621 // the instruction selector will not match, so get a canonical MOVL with
6622 // swapped operands to undo the commute.
6623 return getMOVL(DAG, dl, VT, V2, V1);
6626 if (isUNPCKLMask(M, VT, HasAVX2))
6627 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6629 if (isUNPCKHMask(M, VT, HasAVX2))
6630 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6633 // Normalize mask so all entries that point to V2 points to its first
6634 // element then try to match unpck{h|l} again. If match, return a
6635 // new vector_shuffle with the corrected mask.
6636 SDValue NewMask = NormalizeMask(SVOp, DAG);
6637 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6638 if (NSVOp != SVOp) {
6639 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6641 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6648 // Commute is back and try unpck* again.
6649 // FIXME: this seems wrong.
6650 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6651 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6653 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6654 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6656 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6657 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6660 // Normalize the node to match x86 shuffle ops if needed
6661 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6662 isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6663 return CommuteVectorShuffle(SVOp, DAG);
6665 // The checks below are all present in isShuffleMaskLegal, but they are
6666 // inlined here right now to enable us to directly emit target specific
6667 // nodes, and remove one by one until they don't return Op anymore.
6669 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6670 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6671 getShufflePALIGNRImmediate(SVOp),
6674 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6675 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6676 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6677 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6680 if (isPSHUFHWMask(M, VT))
6681 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6682 X86::getShufflePSHUFHWImmediate(SVOp),
6685 if (isPSHUFLWMask(M, VT))
6686 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6687 X86::getShufflePSHUFLWImmediate(SVOp),
6690 if (isSHUFPMask(M, VT))
6691 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6692 X86::getShuffleSHUFImmediate(SVOp), DAG);
6694 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6695 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6696 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6697 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6699 //===--------------------------------------------------------------------===//
6700 // Generate target specific nodes for 128 or 256-bit shuffles only
6701 // supported in the AVX instruction set.
6704 // Handle VMOVDDUPY permutations
6705 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6706 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6708 // Handle VPERMILPS/D* permutations
6709 if (isVPERMILPMask(M, VT, HasAVX))
6710 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6711 getShuffleVPERMILPImmediate(SVOp), DAG);
6713 // Handle VPERM2F128/VPERM2I128 permutations
6714 if (isVPERM2X128Mask(M, VT, HasAVX))
6715 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6716 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6718 // Handle VSHUFPS/DY permutations
6719 if (isVSHUFPYMask(M, VT, HasAVX))
6720 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6721 getShuffleVSHUFPYImmediate(SVOp), DAG);
6723 //===--------------------------------------------------------------------===//
6724 // Since no target specific shuffle was selected for this generic one,
6725 // lower it into other known shuffles. FIXME: this isn't true yet, but
6726 // this is the plan.
6729 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6730 if (VT == MVT::v8i16) {
6731 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6732 if (NewOp.getNode())
6736 if (VT == MVT::v16i8) {
6737 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6738 if (NewOp.getNode())
6742 // Handle all 128-bit wide vectors with 4 elements, and match them with
6743 // several different shuffle types.
6744 if (NumElems == 4 && VT.getSizeInBits() == 128)
6745 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6747 // Handle general 256-bit shuffles
6748 if (VT.is256BitVector())
6749 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6755 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6756 SelectionDAG &DAG) const {
6757 EVT VT = Op.getValueType();
6758 DebugLoc dl = Op.getDebugLoc();
6760 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6763 if (VT.getSizeInBits() == 8) {
6764 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6765 Op.getOperand(0), Op.getOperand(1));
6766 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6767 DAG.getValueType(VT));
6768 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6769 } else if (VT.getSizeInBits() == 16) {
6770 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6771 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6773 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6774 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6775 DAG.getNode(ISD::BITCAST, dl,
6779 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6780 Op.getOperand(0), Op.getOperand(1));
6781 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6782 DAG.getValueType(VT));
6783 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6784 } else if (VT == MVT::f32) {
6785 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6786 // the result back to FR32 register. It's only worth matching if the
6787 // result has a single use which is a store or a bitcast to i32. And in
6788 // the case of a store, it's not worth it if the index is a constant 0,
6789 // because a MOVSSmr can be used instead, which is smaller and faster.
6790 if (!Op.hasOneUse())
6792 SDNode *User = *Op.getNode()->use_begin();
6793 if ((User->getOpcode() != ISD::STORE ||
6794 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6795 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6796 (User->getOpcode() != ISD::BITCAST ||
6797 User->getValueType(0) != MVT::i32))
6799 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6800 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6803 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6804 } else if (VT == MVT::i32 || VT == MVT::i64) {
6805 // ExtractPS/pextrq works with constant index.
6806 if (isa<ConstantSDNode>(Op.getOperand(1)))
6814 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6815 SelectionDAG &DAG) const {
6816 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6819 SDValue Vec = Op.getOperand(0);
6820 EVT VecVT = Vec.getValueType();
6822 // If this is a 256-bit vector result, first extract the 128-bit vector and
6823 // then extract the element from the 128-bit vector.
6824 if (VecVT.getSizeInBits() == 256) {
6825 DebugLoc dl = Op.getNode()->getDebugLoc();
6826 unsigned NumElems = VecVT.getVectorNumElements();
6827 SDValue Idx = Op.getOperand(1);
6828 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6830 // Get the 128-bit vector.
6831 bool Upper = IdxVal >= NumElems/2;
6832 Vec = Extract128BitVector(Vec,
6833 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6835 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6836 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6839 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6841 if (Subtarget->hasSSE41orAVX()) {
6842 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6847 EVT VT = Op.getValueType();
6848 DebugLoc dl = Op.getDebugLoc();
6849 // TODO: handle v16i8.
6850 if (VT.getSizeInBits() == 16) {
6851 SDValue Vec = Op.getOperand(0);
6852 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6854 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6855 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6856 DAG.getNode(ISD::BITCAST, dl,
6859 // Transform it so it match pextrw which produces a 32-bit result.
6860 EVT EltVT = MVT::i32;
6861 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6862 Op.getOperand(0), Op.getOperand(1));
6863 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6864 DAG.getValueType(VT));
6865 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6866 } else if (VT.getSizeInBits() == 32) {
6867 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6871 // SHUFPS the element to the lowest double word, then movss.
6872 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6873 EVT VVT = Op.getOperand(0).getValueType();
6874 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6875 DAG.getUNDEF(VVT), Mask);
6876 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6877 DAG.getIntPtrConstant(0));
6878 } else if (VT.getSizeInBits() == 64) {
6879 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6880 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6881 // to match extract_elt for f64.
6882 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6886 // UNPCKHPD the element to the lowest double word, then movsd.
6887 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6888 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6889 int Mask[2] = { 1, -1 };
6890 EVT VVT = Op.getOperand(0).getValueType();
6891 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6892 DAG.getUNDEF(VVT), Mask);
6893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6894 DAG.getIntPtrConstant(0));
6901 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6902 SelectionDAG &DAG) const {
6903 EVT VT = Op.getValueType();
6904 EVT EltVT = VT.getVectorElementType();
6905 DebugLoc dl = Op.getDebugLoc();
6907 SDValue N0 = Op.getOperand(0);
6908 SDValue N1 = Op.getOperand(1);
6909 SDValue N2 = Op.getOperand(2);
6911 if (VT.getSizeInBits() == 256)
6914 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6915 isa<ConstantSDNode>(N2)) {
6917 if (VT == MVT::v8i16)
6918 Opc = X86ISD::PINSRW;
6919 else if (VT == MVT::v16i8)
6920 Opc = X86ISD::PINSRB;
6922 Opc = X86ISD::PINSRB;
6924 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6926 if (N1.getValueType() != MVT::i32)
6927 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6928 if (N2.getValueType() != MVT::i32)
6929 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6930 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6931 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6932 // Bits [7:6] of the constant are the source select. This will always be
6933 // zero here. The DAG Combiner may combine an extract_elt index into these
6934 // bits. For example (insert (extract, 3), 2) could be matched by putting
6935 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6936 // Bits [5:4] of the constant are the destination select. This is the
6937 // value of the incoming immediate.
6938 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6939 // combine either bitwise AND or insert of float 0.0 to set these bits.
6940 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6941 // Create this as a scalar to vector..
6942 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6943 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6944 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
6945 isa<ConstantSDNode>(N2)) {
6946 // PINSR* works with constant index.
6953 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6954 EVT VT = Op.getValueType();
6955 EVT EltVT = VT.getVectorElementType();
6957 DebugLoc dl = Op.getDebugLoc();
6958 SDValue N0 = Op.getOperand(0);
6959 SDValue N1 = Op.getOperand(1);
6960 SDValue N2 = Op.getOperand(2);
6962 // If this is a 256-bit vector result, first extract the 128-bit vector,
6963 // insert the element into the extracted half and then place it back.
6964 if (VT.getSizeInBits() == 256) {
6965 if (!isa<ConstantSDNode>(N2))
6968 // Get the desired 128-bit vector half.
6969 unsigned NumElems = VT.getVectorNumElements();
6970 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6971 bool Upper = IdxVal >= NumElems/2;
6972 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6973 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6975 // Insert the element into the desired half.
6976 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6977 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6979 // Insert the changed part back to the 256-bit vector
6980 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6983 if (Subtarget->hasSSE41orAVX())
6984 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6986 if (EltVT == MVT::i8)
6989 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6990 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6991 // as its second argument.
6992 if (N1.getValueType() != MVT::i32)
6993 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6994 if (N2.getValueType() != MVT::i32)
6995 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6996 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7002 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7003 LLVMContext *Context = DAG.getContext();
7004 DebugLoc dl = Op.getDebugLoc();
7005 EVT OpVT = Op.getValueType();
7007 // If this is a 256-bit vector result, first insert into a 128-bit
7008 // vector and then insert into the 256-bit vector.
7009 if (OpVT.getSizeInBits() > 128) {
7010 // Insert into a 128-bit vector.
7011 EVT VT128 = EVT::getVectorVT(*Context,
7012 OpVT.getVectorElementType(),
7013 OpVT.getVectorNumElements() / 2);
7015 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7017 // Insert the 128-bit vector.
7018 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7019 DAG.getConstant(0, MVT::i32),
7023 if (Op.getValueType() == MVT::v1i64 &&
7024 Op.getOperand(0).getValueType() == MVT::i64)
7025 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7027 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7028 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7029 "Expected an SSE type!");
7030 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7031 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7034 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7035 // a simple subregister reference or explicit instructions to grab
7036 // upper bits of a vector.
7038 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7039 if (Subtarget->hasAVX()) {
7040 DebugLoc dl = Op.getNode()->getDebugLoc();
7041 SDValue Vec = Op.getNode()->getOperand(0);
7042 SDValue Idx = Op.getNode()->getOperand(1);
7044 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7045 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7046 return Extract128BitVector(Vec, Idx, DAG, dl);
7052 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7053 // simple superregister reference or explicit instructions to insert
7054 // the upper bits of a vector.
7056 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7057 if (Subtarget->hasAVX()) {
7058 DebugLoc dl = Op.getNode()->getDebugLoc();
7059 SDValue Vec = Op.getNode()->getOperand(0);
7060 SDValue SubVec = Op.getNode()->getOperand(1);
7061 SDValue Idx = Op.getNode()->getOperand(2);
7063 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7064 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7065 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7071 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7072 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7073 // one of the above mentioned nodes. It has to be wrapped because otherwise
7074 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7075 // be used to form addressing mode. These wrapped nodes will be selected
7078 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7079 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7081 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7083 unsigned char OpFlag = 0;
7084 unsigned WrapperKind = X86ISD::Wrapper;
7085 CodeModel::Model M = getTargetMachine().getCodeModel();
7087 if (Subtarget->isPICStyleRIPRel() &&
7088 (M == CodeModel::Small || M == CodeModel::Kernel))
7089 WrapperKind = X86ISD::WrapperRIP;
7090 else if (Subtarget->isPICStyleGOT())
7091 OpFlag = X86II::MO_GOTOFF;
7092 else if (Subtarget->isPICStyleStubPIC())
7093 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7095 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7097 CP->getOffset(), OpFlag);
7098 DebugLoc DL = CP->getDebugLoc();
7099 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7100 // With PIC, the address is actually $g + Offset.
7102 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7103 DAG.getNode(X86ISD::GlobalBaseReg,
7104 DebugLoc(), getPointerTy()),
7111 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7112 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7114 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7116 unsigned char OpFlag = 0;
7117 unsigned WrapperKind = X86ISD::Wrapper;
7118 CodeModel::Model M = getTargetMachine().getCodeModel();
7120 if (Subtarget->isPICStyleRIPRel() &&
7121 (M == CodeModel::Small || M == CodeModel::Kernel))
7122 WrapperKind = X86ISD::WrapperRIP;
7123 else if (Subtarget->isPICStyleGOT())
7124 OpFlag = X86II::MO_GOTOFF;
7125 else if (Subtarget->isPICStyleStubPIC())
7126 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7128 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7130 DebugLoc DL = JT->getDebugLoc();
7131 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7133 // With PIC, the address is actually $g + Offset.
7135 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7136 DAG.getNode(X86ISD::GlobalBaseReg,
7137 DebugLoc(), getPointerTy()),
7144 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7145 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7147 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7149 unsigned char OpFlag = 0;
7150 unsigned WrapperKind = X86ISD::Wrapper;
7151 CodeModel::Model M = getTargetMachine().getCodeModel();
7153 if (Subtarget->isPICStyleRIPRel() &&
7154 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7155 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7156 OpFlag = X86II::MO_GOTPCREL;
7157 WrapperKind = X86ISD::WrapperRIP;
7158 } else if (Subtarget->isPICStyleGOT()) {
7159 OpFlag = X86II::MO_GOT;
7160 } else if (Subtarget->isPICStyleStubPIC()) {
7161 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7162 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7163 OpFlag = X86II::MO_DARWIN_NONLAZY;
7166 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7168 DebugLoc DL = Op.getDebugLoc();
7169 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7172 // With PIC, the address is actually $g + Offset.
7173 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7174 !Subtarget->is64Bit()) {
7175 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7176 DAG.getNode(X86ISD::GlobalBaseReg,
7177 DebugLoc(), getPointerTy()),
7181 // For symbols that require a load from a stub to get the address, emit the
7183 if (isGlobalStubReference(OpFlag))
7184 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7185 MachinePointerInfo::getGOT(), false, false, false, 0);
7191 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7192 // Create the TargetBlockAddressAddress node.
7193 unsigned char OpFlags =
7194 Subtarget->ClassifyBlockAddressReference();
7195 CodeModel::Model M = getTargetMachine().getCodeModel();
7196 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7197 DebugLoc dl = Op.getDebugLoc();
7198 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7199 /*isTarget=*/true, OpFlags);
7201 if (Subtarget->isPICStyleRIPRel() &&
7202 (M == CodeModel::Small || M == CodeModel::Kernel))
7203 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7205 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7207 // With PIC, the address is actually $g + Offset.
7208 if (isGlobalRelativeToPICBase(OpFlags)) {
7209 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7210 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7218 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7220 SelectionDAG &DAG) const {
7221 // Create the TargetGlobalAddress node, folding in the constant
7222 // offset if it is legal.
7223 unsigned char OpFlags =
7224 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7225 CodeModel::Model M = getTargetMachine().getCodeModel();
7227 if (OpFlags == X86II::MO_NO_FLAG &&
7228 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7229 // A direct static reference to a global.
7230 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7233 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7236 if (Subtarget->isPICStyleRIPRel() &&
7237 (M == CodeModel::Small || M == CodeModel::Kernel))
7238 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7240 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7242 // With PIC, the address is actually $g + Offset.
7243 if (isGlobalRelativeToPICBase(OpFlags)) {
7244 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7245 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7249 // For globals that require a load from a stub to get the address, emit the
7251 if (isGlobalStubReference(OpFlags))
7252 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7253 MachinePointerInfo::getGOT(), false, false, false, 0);
7255 // If there was a non-zero offset that we didn't fold, create an explicit
7258 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7259 DAG.getConstant(Offset, getPointerTy()));
7265 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7266 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7267 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7268 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7272 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7273 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7274 unsigned char OperandFlags) {
7275 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7276 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7277 DebugLoc dl = GA->getDebugLoc();
7278 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7279 GA->getValueType(0),
7283 SDValue Ops[] = { Chain, TGA, *InFlag };
7284 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7286 SDValue Ops[] = { Chain, TGA };
7287 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7290 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7291 MFI->setAdjustsStack(true);
7293 SDValue Flag = Chain.getValue(1);
7294 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7297 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7299 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7302 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7303 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7304 DAG.getNode(X86ISD::GlobalBaseReg,
7305 DebugLoc(), PtrVT), InFlag);
7306 InFlag = Chain.getValue(1);
7308 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7311 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7313 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7315 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7316 X86::RAX, X86II::MO_TLSGD);
7319 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7320 // "local exec" model.
7321 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7322 const EVT PtrVT, TLSModel::Model model,
7324 DebugLoc dl = GA->getDebugLoc();
7326 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7327 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7328 is64Bit ? 257 : 256));
7330 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7331 DAG.getIntPtrConstant(0),
7332 MachinePointerInfo(Ptr),
7333 false, false, false, 0);
7335 unsigned char OperandFlags = 0;
7336 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7338 unsigned WrapperKind = X86ISD::Wrapper;
7339 if (model == TLSModel::LocalExec) {
7340 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7341 } else if (is64Bit) {
7342 assert(model == TLSModel::InitialExec);
7343 OperandFlags = X86II::MO_GOTTPOFF;
7344 WrapperKind = X86ISD::WrapperRIP;
7346 assert(model == TLSModel::InitialExec);
7347 OperandFlags = X86II::MO_INDNTPOFF;
7350 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7352 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7353 GA->getValueType(0),
7354 GA->getOffset(), OperandFlags);
7355 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7357 if (model == TLSModel::InitialExec)
7358 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7359 MachinePointerInfo::getGOT(), false, false, false, 0);
7361 // The address of the thread local variable is the add of the thread
7362 // pointer with the offset of the variable.
7363 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7367 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7369 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7370 const GlobalValue *GV = GA->getGlobal();
7372 if (Subtarget->isTargetELF()) {
7373 // TODO: implement the "local dynamic" model
7374 // TODO: implement the "initial exec"model for pic executables
7376 // If GV is an alias then use the aliasee for determining
7377 // thread-localness.
7378 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7379 GV = GA->resolveAliasedGlobal(false);
7381 TLSModel::Model model
7382 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7385 case TLSModel::GeneralDynamic:
7386 case TLSModel::LocalDynamic: // not implemented
7387 if (Subtarget->is64Bit())
7388 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7389 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7391 case TLSModel::InitialExec:
7392 case TLSModel::LocalExec:
7393 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7394 Subtarget->is64Bit());
7396 } else if (Subtarget->isTargetDarwin()) {
7397 // Darwin only has one model of TLS. Lower to that.
7398 unsigned char OpFlag = 0;
7399 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7400 X86ISD::WrapperRIP : X86ISD::Wrapper;
7402 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7404 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7405 !Subtarget->is64Bit();
7407 OpFlag = X86II::MO_TLVP_PIC_BASE;
7409 OpFlag = X86II::MO_TLVP;
7410 DebugLoc DL = Op.getDebugLoc();
7411 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7412 GA->getValueType(0),
7413 GA->getOffset(), OpFlag);
7414 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7416 // With PIC32, the address is actually $g + Offset.
7418 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7419 DAG.getNode(X86ISD::GlobalBaseReg,
7420 DebugLoc(), getPointerTy()),
7423 // Lowering the machine isd will make sure everything is in the right
7425 SDValue Chain = DAG.getEntryNode();
7426 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7427 SDValue Args[] = { Chain, Offset };
7428 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7430 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7431 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7432 MFI->setAdjustsStack(true);
7434 // And our return value (tls address) is in the standard call return value
7436 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7437 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7442 "TLS not implemented for this target.");
7444 llvm_unreachable("Unreachable");
7449 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7450 /// take a 2 x i32 value to shift plus a shift amount.
7451 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7452 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7453 EVT VT = Op.getValueType();
7454 unsigned VTBits = VT.getSizeInBits();
7455 DebugLoc dl = Op.getDebugLoc();
7456 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7457 SDValue ShOpLo = Op.getOperand(0);
7458 SDValue ShOpHi = Op.getOperand(1);
7459 SDValue ShAmt = Op.getOperand(2);
7460 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7461 DAG.getConstant(VTBits - 1, MVT::i8))
7462 : DAG.getConstant(0, VT);
7465 if (Op.getOpcode() == ISD::SHL_PARTS) {
7466 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7467 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7469 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7470 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7473 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7474 DAG.getConstant(VTBits, MVT::i8));
7475 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7476 AndNode, DAG.getConstant(0, MVT::i8));
7479 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7480 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7481 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7483 if (Op.getOpcode() == ISD::SHL_PARTS) {
7484 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7485 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7487 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7488 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7491 SDValue Ops[2] = { Lo, Hi };
7492 return DAG.getMergeValues(Ops, 2, dl);
7495 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7496 SelectionDAG &DAG) const {
7497 EVT SrcVT = Op.getOperand(0).getValueType();
7499 if (SrcVT.isVector())
7502 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7503 "Unknown SINT_TO_FP to lower!");
7505 // These are really Legal; return the operand so the caller accepts it as
7507 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7509 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7510 Subtarget->is64Bit()) {
7514 DebugLoc dl = Op.getDebugLoc();
7515 unsigned Size = SrcVT.getSizeInBits()/8;
7516 MachineFunction &MF = DAG.getMachineFunction();
7517 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7518 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7519 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7521 MachinePointerInfo::getFixedStack(SSFI),
7523 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7526 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7528 SelectionDAG &DAG) const {
7530 DebugLoc DL = Op.getDebugLoc();
7532 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7534 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7536 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7538 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7540 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7541 MachineMemOperand *MMO;
7543 int SSFI = FI->getIndex();
7545 DAG.getMachineFunction()
7546 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7547 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7549 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7550 StackSlot = StackSlot.getOperand(1);
7552 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7553 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7555 Tys, Ops, array_lengthof(Ops),
7559 Chain = Result.getValue(1);
7560 SDValue InFlag = Result.getValue(2);
7562 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7563 // shouldn't be necessary except that RFP cannot be live across
7564 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7565 MachineFunction &MF = DAG.getMachineFunction();
7566 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7567 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7568 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7569 Tys = DAG.getVTList(MVT::Other);
7571 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7573 MachineMemOperand *MMO =
7574 DAG.getMachineFunction()
7575 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7576 MachineMemOperand::MOStore, SSFISize, SSFISize);
7578 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7579 Ops, array_lengthof(Ops),
7580 Op.getValueType(), MMO);
7581 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7582 MachinePointerInfo::getFixedStack(SSFI),
7583 false, false, false, 0);
7589 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7590 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7591 SelectionDAG &DAG) const {
7592 // This algorithm is not obvious. Here it is in C code, more or less:
7594 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7595 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7596 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7598 // Copy ints to xmm registers.
7599 __m128i xh = _mm_cvtsi32_si128( hi );
7600 __m128i xl = _mm_cvtsi32_si128( lo );
7602 // Combine into low half of a single xmm register.
7603 __m128i x = _mm_unpacklo_epi32( xh, xl );
7607 // Merge in appropriate exponents to give the integer bits the right
7609 x = _mm_unpacklo_epi32( x, exp );
7611 // Subtract away the biases to deal with the IEEE-754 double precision
7613 d = _mm_sub_pd( (__m128d) x, bias );
7615 // All conversions up to here are exact. The correctly rounded result is
7616 // calculated using the current rounding mode using the following
7618 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7619 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7620 // store doesn't really need to be here (except
7621 // maybe to zero the other double)
7626 DebugLoc dl = Op.getDebugLoc();
7627 LLVMContext *Context = DAG.getContext();
7629 // Build some magic constants.
7630 SmallVector<Constant*,4> CV0;
7631 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7632 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7633 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7634 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7635 Constant *C0 = ConstantVector::get(CV0);
7636 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7638 SmallVector<Constant*,2> CV1;
7640 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7642 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7643 Constant *C1 = ConstantVector::get(CV1);
7644 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7646 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7647 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7649 DAG.getIntPtrConstant(1)));
7650 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7651 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7653 DAG.getIntPtrConstant(0)));
7654 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7655 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7656 MachinePointerInfo::getConstantPool(),
7657 false, false, false, 16);
7658 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7659 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7660 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7661 MachinePointerInfo::getConstantPool(),
7662 false, false, false, 16);
7663 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7665 // Add the halves; easiest way is to swap them into another reg first.
7666 int ShufMask[2] = { 1, -1 };
7667 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7668 DAG.getUNDEF(MVT::v2f64), ShufMask);
7669 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7670 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7671 DAG.getIntPtrConstant(0));
7674 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7675 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7676 SelectionDAG &DAG) const {
7677 DebugLoc dl = Op.getDebugLoc();
7678 // FP constant to bias correct the final result.
7679 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7682 // Load the 32-bit value into an XMM register.
7683 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7686 // Zero out the upper parts of the register.
7687 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7690 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7691 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7692 DAG.getIntPtrConstant(0));
7694 // Or the load with the bias.
7695 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7696 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7697 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7699 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7700 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7701 MVT::v2f64, Bias)));
7702 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7703 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7704 DAG.getIntPtrConstant(0));
7706 // Subtract the bias.
7707 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7709 // Handle final rounding.
7710 EVT DestVT = Op.getValueType();
7712 if (DestVT.bitsLT(MVT::f64)) {
7713 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7714 DAG.getIntPtrConstant(0));
7715 } else if (DestVT.bitsGT(MVT::f64)) {
7716 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7719 // Handle final rounding.
7723 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7724 SelectionDAG &DAG) const {
7725 SDValue N0 = Op.getOperand(0);
7726 DebugLoc dl = Op.getDebugLoc();
7728 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7729 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7730 // the optimization here.
7731 if (DAG.SignBitIsZero(N0))
7732 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7734 EVT SrcVT = N0.getValueType();
7735 EVT DstVT = Op.getValueType();
7736 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7737 return LowerUINT_TO_FP_i64(Op, DAG);
7738 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7739 return LowerUINT_TO_FP_i32(Op, DAG);
7741 // Make a 64-bit buffer, and use it to build an FILD.
7742 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7743 if (SrcVT == MVT::i32) {
7744 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7745 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7746 getPointerTy(), StackSlot, WordOff);
7747 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7748 StackSlot, MachinePointerInfo(),
7750 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7751 OffsetSlot, MachinePointerInfo(),
7753 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7757 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7758 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7759 StackSlot, MachinePointerInfo(),
7761 // For i64 source, we need to add the appropriate power of 2 if the input
7762 // was negative. This is the same as the optimization in
7763 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7764 // we must be careful to do the computation in x87 extended precision, not
7765 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7766 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7767 MachineMemOperand *MMO =
7768 DAG.getMachineFunction()
7769 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7770 MachineMemOperand::MOLoad, 8, 8);
7772 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7773 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7774 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7777 APInt FF(32, 0x5F800000ULL);
7779 // Check whether the sign bit is set.
7780 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7781 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7784 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7785 SDValue FudgePtr = DAG.getConstantPool(
7786 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7789 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7790 SDValue Zero = DAG.getIntPtrConstant(0);
7791 SDValue Four = DAG.getIntPtrConstant(4);
7792 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7794 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7796 // Load the value out, extending it from f32 to f80.
7797 // FIXME: Avoid the extend by constructing the right constant pool?
7798 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7799 FudgePtr, MachinePointerInfo::getConstantPool(),
7800 MVT::f32, false, false, 4);
7801 // Extend everything to 80 bits to force it to be done on x87.
7802 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7803 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7806 std::pair<SDValue,SDValue> X86TargetLowering::
7807 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7808 DebugLoc DL = Op.getDebugLoc();
7810 EVT DstTy = Op.getValueType();
7813 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7817 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7818 DstTy.getSimpleVT() >= MVT::i16 &&
7819 "Unknown FP_TO_SINT to lower!");
7821 // These are really Legal.
7822 if (DstTy == MVT::i32 &&
7823 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7824 return std::make_pair(SDValue(), SDValue());
7825 if (Subtarget->is64Bit() &&
7826 DstTy == MVT::i64 &&
7827 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7828 return std::make_pair(SDValue(), SDValue());
7830 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7832 MachineFunction &MF = DAG.getMachineFunction();
7833 unsigned MemSize = DstTy.getSizeInBits()/8;
7834 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7835 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7840 switch (DstTy.getSimpleVT().SimpleTy) {
7841 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7842 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7843 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7844 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7847 SDValue Chain = DAG.getEntryNode();
7848 SDValue Value = Op.getOperand(0);
7849 EVT TheVT = Op.getOperand(0).getValueType();
7850 if (isScalarFPTypeInSSEReg(TheVT)) {
7851 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7852 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7853 MachinePointerInfo::getFixedStack(SSFI),
7855 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7857 Chain, StackSlot, DAG.getValueType(TheVT)
7860 MachineMemOperand *MMO =
7861 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7862 MachineMemOperand::MOLoad, MemSize, MemSize);
7863 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7865 Chain = Value.getValue(1);
7866 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7867 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7870 MachineMemOperand *MMO =
7871 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7872 MachineMemOperand::MOStore, MemSize, MemSize);
7874 // Build the FP_TO_INT*_IN_MEM
7875 SDValue Ops[] = { Chain, Value, StackSlot };
7876 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7877 Ops, 3, DstTy, MMO);
7879 return std::make_pair(FIST, StackSlot);
7882 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7883 SelectionDAG &DAG) const {
7884 if (Op.getValueType().isVector())
7887 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7888 SDValue FIST = Vals.first, StackSlot = Vals.second;
7889 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7890 if (FIST.getNode() == 0) return Op;
7893 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7894 FIST, StackSlot, MachinePointerInfo(),
7895 false, false, false, 0);
7898 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7899 SelectionDAG &DAG) const {
7900 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7901 SDValue FIST = Vals.first, StackSlot = Vals.second;
7902 assert(FIST.getNode() && "Unexpected failure");
7905 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7906 FIST, StackSlot, MachinePointerInfo(),
7907 false, false, false, 0);
7910 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7911 SelectionDAG &DAG) const {
7912 LLVMContext *Context = DAG.getContext();
7913 DebugLoc dl = Op.getDebugLoc();
7914 EVT VT = Op.getValueType();
7917 EltVT = VT.getVectorElementType();
7918 SmallVector<Constant*,4> CV;
7919 if (EltVT == MVT::f64) {
7920 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7923 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7926 Constant *C = ConstantVector::get(CV);
7927 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7928 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7929 MachinePointerInfo::getConstantPool(),
7930 false, false, false, 16);
7931 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7934 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7935 LLVMContext *Context = DAG.getContext();
7936 DebugLoc dl = Op.getDebugLoc();
7937 EVT VT = Op.getValueType();
7939 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7940 if (VT.isVector()) {
7941 EltVT = VT.getVectorElementType();
7942 NumElts = VT.getVectorNumElements();
7944 SmallVector<Constant*,8> CV;
7945 if (EltVT == MVT::f64) {
7946 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7947 CV.assign(NumElts, C);
7949 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7950 CV.assign(NumElts, C);
7952 Constant *C = ConstantVector::get(CV);
7953 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7954 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7955 MachinePointerInfo::getConstantPool(),
7956 false, false, false, 16);
7957 if (VT.isVector()) {
7958 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7959 return DAG.getNode(ISD::BITCAST, dl, VT,
7960 DAG.getNode(ISD::XOR, dl, XORVT,
7961 DAG.getNode(ISD::BITCAST, dl, XORVT,
7963 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7965 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7969 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7970 LLVMContext *Context = DAG.getContext();
7971 SDValue Op0 = Op.getOperand(0);
7972 SDValue Op1 = Op.getOperand(1);
7973 DebugLoc dl = Op.getDebugLoc();
7974 EVT VT = Op.getValueType();
7975 EVT SrcVT = Op1.getValueType();
7977 // If second operand is smaller, extend it first.
7978 if (SrcVT.bitsLT(VT)) {
7979 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7982 // And if it is bigger, shrink it first.
7983 if (SrcVT.bitsGT(VT)) {
7984 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7988 // At this point the operands and the result should have the same
7989 // type, and that won't be f80 since that is not custom lowered.
7991 // First get the sign bit of second operand.
7992 SmallVector<Constant*,4> CV;
7993 if (SrcVT == MVT::f64) {
7994 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7995 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7997 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7998 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7999 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8000 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8002 Constant *C = ConstantVector::get(CV);
8003 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8004 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8005 MachinePointerInfo::getConstantPool(),
8006 false, false, false, 16);
8007 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8009 // Shift sign bit right or left if the two operands have different types.
8010 if (SrcVT.bitsGT(VT)) {
8011 // Op0 is MVT::f32, Op1 is MVT::f64.
8012 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8013 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8014 DAG.getConstant(32, MVT::i32));
8015 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8016 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8017 DAG.getIntPtrConstant(0));
8020 // Clear first operand sign bit.
8022 if (VT == MVT::f64) {
8023 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8024 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8026 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8027 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8028 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8029 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8031 C = ConstantVector::get(CV);
8032 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8033 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8034 MachinePointerInfo::getConstantPool(),
8035 false, false, false, 16);
8036 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8038 // Or the value with the sign bit.
8039 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8042 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8043 SDValue N0 = Op.getOperand(0);
8044 DebugLoc dl = Op.getDebugLoc();
8045 EVT VT = Op.getValueType();
8047 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8048 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8049 DAG.getConstant(1, VT));
8050 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8053 /// Emit nodes that will be selected as "test Op0,Op0", or something
8055 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8056 SelectionDAG &DAG) const {
8057 DebugLoc dl = Op.getDebugLoc();
8059 // CF and OF aren't always set the way we want. Determine which
8060 // of these we need.
8061 bool NeedCF = false;
8062 bool NeedOF = false;
8065 case X86::COND_A: case X86::COND_AE:
8066 case X86::COND_B: case X86::COND_BE:
8069 case X86::COND_G: case X86::COND_GE:
8070 case X86::COND_L: case X86::COND_LE:
8071 case X86::COND_O: case X86::COND_NO:
8076 // See if we can use the EFLAGS value from the operand instead of
8077 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8078 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8079 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8080 // Emit a CMP with 0, which is the TEST pattern.
8081 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8082 DAG.getConstant(0, Op.getValueType()));
8084 unsigned Opcode = 0;
8085 unsigned NumOperands = 0;
8086 switch (Op.getNode()->getOpcode()) {
8088 // Due to an isel shortcoming, be conservative if this add is likely to be
8089 // selected as part of a load-modify-store instruction. When the root node
8090 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8091 // uses of other nodes in the match, such as the ADD in this case. This
8092 // leads to the ADD being left around and reselected, with the result being
8093 // two adds in the output. Alas, even if none our users are stores, that
8094 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8095 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8096 // climbing the DAG back to the root, and it doesn't seem to be worth the
8098 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8099 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8100 if (UI->getOpcode() != ISD::CopyToReg &&
8101 UI->getOpcode() != ISD::SETCC &&
8102 UI->getOpcode() != ISD::STORE)
8105 if (ConstantSDNode *C =
8106 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8107 // An add of one will be selected as an INC.
8108 if (C->getAPIntValue() == 1) {
8109 Opcode = X86ISD::INC;
8114 // An add of negative one (subtract of one) will be selected as a DEC.
8115 if (C->getAPIntValue().isAllOnesValue()) {
8116 Opcode = X86ISD::DEC;
8122 // Otherwise use a regular EFLAGS-setting add.
8123 Opcode = X86ISD::ADD;
8127 // If the primary and result isn't used, don't bother using X86ISD::AND,
8128 // because a TEST instruction will be better.
8129 bool NonFlagUse = false;
8130 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8131 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8133 unsigned UOpNo = UI.getOperandNo();
8134 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8135 // Look pass truncate.
8136 UOpNo = User->use_begin().getOperandNo();
8137 User = *User->use_begin();
8140 if (User->getOpcode() != ISD::BRCOND &&
8141 User->getOpcode() != ISD::SETCC &&
8142 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8155 // Due to the ISEL shortcoming noted above, be conservative if this op is
8156 // likely to be selected as part of a load-modify-store instruction.
8157 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8158 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8159 if (UI->getOpcode() == ISD::STORE)
8162 // Otherwise use a regular EFLAGS-setting instruction.
8163 switch (Op.getNode()->getOpcode()) {
8164 default: llvm_unreachable("unexpected operator!");
8165 case ISD::SUB: Opcode = X86ISD::SUB; break;
8166 case ISD::OR: Opcode = X86ISD::OR; break;
8167 case ISD::XOR: Opcode = X86ISD::XOR; break;
8168 case ISD::AND: Opcode = X86ISD::AND; break;
8180 return SDValue(Op.getNode(), 1);
8187 // Emit a CMP with 0, which is the TEST pattern.
8188 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8189 DAG.getConstant(0, Op.getValueType()));
8191 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8192 SmallVector<SDValue, 4> Ops;
8193 for (unsigned i = 0; i != NumOperands; ++i)
8194 Ops.push_back(Op.getOperand(i));
8196 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8197 DAG.ReplaceAllUsesWith(Op, New);
8198 return SDValue(New.getNode(), 1);
8201 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8203 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8204 SelectionDAG &DAG) const {
8205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8206 if (C->getAPIntValue() == 0)
8207 return EmitTest(Op0, X86CC, DAG);
8209 DebugLoc dl = Op0.getDebugLoc();
8210 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8213 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8214 /// if it's possible.
8215 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8216 DebugLoc dl, SelectionDAG &DAG) const {
8217 SDValue Op0 = And.getOperand(0);
8218 SDValue Op1 = And.getOperand(1);
8219 if (Op0.getOpcode() == ISD::TRUNCATE)
8220 Op0 = Op0.getOperand(0);
8221 if (Op1.getOpcode() == ISD::TRUNCATE)
8222 Op1 = Op1.getOperand(0);
8225 if (Op1.getOpcode() == ISD::SHL)
8226 std::swap(Op0, Op1);
8227 if (Op0.getOpcode() == ISD::SHL) {
8228 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8229 if (And00C->getZExtValue() == 1) {
8230 // If we looked past a truncate, check that it's only truncating away
8232 unsigned BitWidth = Op0.getValueSizeInBits();
8233 unsigned AndBitWidth = And.getValueSizeInBits();
8234 if (BitWidth > AndBitWidth) {
8235 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8236 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8237 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8241 RHS = Op0.getOperand(1);
8243 } else if (Op1.getOpcode() == ISD::Constant) {
8244 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8245 uint64_t AndRHSVal = AndRHS->getZExtValue();
8246 SDValue AndLHS = Op0;
8248 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8249 LHS = AndLHS.getOperand(0);
8250 RHS = AndLHS.getOperand(1);
8253 // Use BT if the immediate can't be encoded in a TEST instruction.
8254 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8256 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8260 if (LHS.getNode()) {
8261 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8262 // instruction. Since the shift amount is in-range-or-undefined, we know
8263 // that doing a bittest on the i32 value is ok. We extend to i32 because
8264 // the encoding for the i16 version is larger than the i32 version.
8265 // Also promote i16 to i32 for performance / code size reason.
8266 if (LHS.getValueType() == MVT::i8 ||
8267 LHS.getValueType() == MVT::i16)
8268 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8270 // If the operand types disagree, extend the shift amount to match. Since
8271 // BT ignores high bits (like shifts) we can use anyextend.
8272 if (LHS.getValueType() != RHS.getValueType())
8273 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8275 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8276 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8277 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8278 DAG.getConstant(Cond, MVT::i8), BT);
8284 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8286 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8288 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8289 SDValue Op0 = Op.getOperand(0);
8290 SDValue Op1 = Op.getOperand(1);
8291 DebugLoc dl = Op.getDebugLoc();
8292 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8294 // Optimize to BT if possible.
8295 // Lower (X & (1 << N)) == 0 to BT(X, N).
8296 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8297 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8298 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8299 Op1.getOpcode() == ISD::Constant &&
8300 cast<ConstantSDNode>(Op1)->isNullValue() &&
8301 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8302 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8303 if (NewSetCC.getNode())
8307 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8309 if (Op1.getOpcode() == ISD::Constant &&
8310 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8311 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8312 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8314 // If the input is a setcc, then reuse the input setcc or use a new one with
8315 // the inverted condition.
8316 if (Op0.getOpcode() == X86ISD::SETCC) {
8317 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8318 bool Invert = (CC == ISD::SETNE) ^
8319 cast<ConstantSDNode>(Op1)->isNullValue();
8320 if (!Invert) return Op0;
8322 CCode = X86::GetOppositeBranchCondition(CCode);
8323 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8324 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8328 bool isFP = Op1.getValueType().isFloatingPoint();
8329 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8330 if (X86CC == X86::COND_INVALID)
8333 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8334 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8335 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8338 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8339 // ones, and then concatenate the result back.
8340 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8341 EVT VT = Op.getValueType();
8343 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8344 "Unsupported value type for operation");
8346 int NumElems = VT.getVectorNumElements();
8347 DebugLoc dl = Op.getDebugLoc();
8348 SDValue CC = Op.getOperand(2);
8349 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8350 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8352 // Extract the LHS vectors
8353 SDValue LHS = Op.getOperand(0);
8354 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8355 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8357 // Extract the RHS vectors
8358 SDValue RHS = Op.getOperand(1);
8359 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8360 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8362 // Issue the operation on the smaller types and concatenate the result back
8363 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8364 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8365 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8366 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8367 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8371 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8373 SDValue Op0 = Op.getOperand(0);
8374 SDValue Op1 = Op.getOperand(1);
8375 SDValue CC = Op.getOperand(2);
8376 EVT VT = Op.getValueType();
8377 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8378 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8379 DebugLoc dl = Op.getDebugLoc();
8383 EVT EltVT = Op0.getValueType().getVectorElementType();
8384 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8386 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8389 // SSE Condition code mapping:
8398 switch (SetCCOpcode) {
8401 case ISD::SETEQ: SSECC = 0; break;
8403 case ISD::SETGT: Swap = true; // Fallthrough
8405 case ISD::SETOLT: SSECC = 1; break;
8407 case ISD::SETGE: Swap = true; // Fallthrough
8409 case ISD::SETOLE: SSECC = 2; break;
8410 case ISD::SETUO: SSECC = 3; break;
8412 case ISD::SETNE: SSECC = 4; break;
8413 case ISD::SETULE: Swap = true;
8414 case ISD::SETUGE: SSECC = 5; break;
8415 case ISD::SETULT: Swap = true;
8416 case ISD::SETUGT: SSECC = 6; break;
8417 case ISD::SETO: SSECC = 7; break;
8420 std::swap(Op0, Op1);
8422 // In the two special cases we can't handle, emit two comparisons.
8424 if (SetCCOpcode == ISD::SETUEQ) {
8426 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8427 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8428 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8429 } else if (SetCCOpcode == ISD::SETONE) {
8431 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8432 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8433 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8435 llvm_unreachable("Illegal FP comparison");
8437 // Handle all other FP comparisons here.
8438 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8441 // Break 256-bit integer vector compare into smaller ones.
8442 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8443 return Lower256IntVSETCC(Op, DAG);
8445 // We are handling one of the integer comparisons here. Since SSE only has
8446 // GT and EQ comparisons for integer, swapping operands and multiple
8447 // operations may be required for some comparisons.
8448 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8449 bool Swap = false, Invert = false, FlipSigns = false;
8451 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8453 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8454 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8455 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8456 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8459 switch (SetCCOpcode) {
8461 case ISD::SETNE: Invert = true;
8462 case ISD::SETEQ: Opc = EQOpc; break;
8463 case ISD::SETLT: Swap = true;
8464 case ISD::SETGT: Opc = GTOpc; break;
8465 case ISD::SETGE: Swap = true;
8466 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8467 case ISD::SETULT: Swap = true;
8468 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8469 case ISD::SETUGE: Swap = true;
8470 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8473 std::swap(Op0, Op1);
8475 // Check that the operation in question is available (most are plain SSE2,
8476 // but PCMPGTQ and PCMPEQQ have different requirements).
8477 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8479 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8482 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8483 // bits of the inputs before performing those operations.
8485 EVT EltVT = VT.getVectorElementType();
8486 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8488 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8489 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8491 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8492 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8495 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8497 // If the logical-not of the result is required, perform that now.
8499 Result = DAG.getNOT(dl, Result, VT);
8504 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8505 static bool isX86LogicalCmp(SDValue Op) {
8506 unsigned Opc = Op.getNode()->getOpcode();
8507 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8509 if (Op.getResNo() == 1 &&
8510 (Opc == X86ISD::ADD ||
8511 Opc == X86ISD::SUB ||
8512 Opc == X86ISD::ADC ||
8513 Opc == X86ISD::SBB ||
8514 Opc == X86ISD::SMUL ||
8515 Opc == X86ISD::UMUL ||
8516 Opc == X86ISD::INC ||
8517 Opc == X86ISD::DEC ||
8518 Opc == X86ISD::OR ||
8519 Opc == X86ISD::XOR ||
8520 Opc == X86ISD::AND))
8523 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8529 static bool isZero(SDValue V) {
8530 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8531 return C && C->isNullValue();
8534 static bool isAllOnes(SDValue V) {
8535 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8536 return C && C->isAllOnesValue();
8539 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8540 bool addTest = true;
8541 SDValue Cond = Op.getOperand(0);
8542 SDValue Op1 = Op.getOperand(1);
8543 SDValue Op2 = Op.getOperand(2);
8544 DebugLoc DL = Op.getDebugLoc();
8547 if (Cond.getOpcode() == ISD::SETCC) {
8548 SDValue NewCond = LowerSETCC(Cond, DAG);
8549 if (NewCond.getNode())
8553 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8554 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8555 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8556 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8557 if (Cond.getOpcode() == X86ISD::SETCC &&
8558 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8559 isZero(Cond.getOperand(1).getOperand(1))) {
8560 SDValue Cmp = Cond.getOperand(1);
8562 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8564 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8565 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8566 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8568 SDValue CmpOp0 = Cmp.getOperand(0);
8569 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8570 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8572 SDValue Res = // Res = 0 or -1.
8573 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8574 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8576 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8577 Res = DAG.getNOT(DL, Res, Res.getValueType());
8579 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8580 if (N2C == 0 || !N2C->isNullValue())
8581 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8586 // Look past (and (setcc_carry (cmp ...)), 1).
8587 if (Cond.getOpcode() == ISD::AND &&
8588 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8589 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8590 if (C && C->getAPIntValue() == 1)
8591 Cond = Cond.getOperand(0);
8594 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8595 // setting operand in place of the X86ISD::SETCC.
8596 unsigned CondOpcode = Cond.getOpcode();
8597 if (CondOpcode == X86ISD::SETCC ||
8598 CondOpcode == X86ISD::SETCC_CARRY) {
8599 CC = Cond.getOperand(0);
8601 SDValue Cmp = Cond.getOperand(1);
8602 unsigned Opc = Cmp.getOpcode();
8603 EVT VT = Op.getValueType();
8605 bool IllegalFPCMov = false;
8606 if (VT.isFloatingPoint() && !VT.isVector() &&
8607 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8608 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8610 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8611 Opc == X86ISD::BT) { // FIXME
8615 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8616 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8617 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8618 Cond.getOperand(0).getValueType() != MVT::i8)) {
8619 SDValue LHS = Cond.getOperand(0);
8620 SDValue RHS = Cond.getOperand(1);
8624 switch (CondOpcode) {
8625 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8626 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8627 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8628 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8629 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8630 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8631 default: llvm_unreachable("unexpected overflowing operator");
8633 if (CondOpcode == ISD::UMULO)
8634 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8637 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8639 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8641 if (CondOpcode == ISD::UMULO)
8642 Cond = X86Op.getValue(2);
8644 Cond = X86Op.getValue(1);
8646 CC = DAG.getConstant(X86Cond, MVT::i8);
8651 // Look pass the truncate.
8652 if (Cond.getOpcode() == ISD::TRUNCATE)
8653 Cond = Cond.getOperand(0);
8655 // We know the result of AND is compared against zero. Try to match
8657 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8658 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8659 if (NewSetCC.getNode()) {
8660 CC = NewSetCC.getOperand(0);
8661 Cond = NewSetCC.getOperand(1);
8668 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8669 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8672 // a < b ? -1 : 0 -> RES = ~setcc_carry
8673 // a < b ? 0 : -1 -> RES = setcc_carry
8674 // a >= b ? -1 : 0 -> RES = setcc_carry
8675 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8676 if (Cond.getOpcode() == X86ISD::CMP) {
8677 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8679 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8680 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8681 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8682 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8683 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8684 return DAG.getNOT(DL, Res, Res.getValueType());
8689 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8690 // condition is true.
8691 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8692 SDValue Ops[] = { Op2, Op1, CC, Cond };
8693 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8696 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8697 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8698 // from the AND / OR.
8699 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8700 Opc = Op.getOpcode();
8701 if (Opc != ISD::OR && Opc != ISD::AND)
8703 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8704 Op.getOperand(0).hasOneUse() &&
8705 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8706 Op.getOperand(1).hasOneUse());
8709 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8710 // 1 and that the SETCC node has a single use.
8711 static bool isXor1OfSetCC(SDValue Op) {
8712 if (Op.getOpcode() != ISD::XOR)
8714 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8715 if (N1C && N1C->getAPIntValue() == 1) {
8716 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8717 Op.getOperand(0).hasOneUse();
8722 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8723 bool addTest = true;
8724 SDValue Chain = Op.getOperand(0);
8725 SDValue Cond = Op.getOperand(1);
8726 SDValue Dest = Op.getOperand(2);
8727 DebugLoc dl = Op.getDebugLoc();
8729 bool Inverted = false;
8731 if (Cond.getOpcode() == ISD::SETCC) {
8732 // Check for setcc([su]{add,sub,mul}o == 0).
8733 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8734 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8735 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8736 Cond.getOperand(0).getResNo() == 1 &&
8737 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8738 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8739 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8740 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8741 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8742 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8744 Cond = Cond.getOperand(0);
8746 SDValue NewCond = LowerSETCC(Cond, DAG);
8747 if (NewCond.getNode())
8752 // FIXME: LowerXALUO doesn't handle these!!
8753 else if (Cond.getOpcode() == X86ISD::ADD ||
8754 Cond.getOpcode() == X86ISD::SUB ||
8755 Cond.getOpcode() == X86ISD::SMUL ||
8756 Cond.getOpcode() == X86ISD::UMUL)
8757 Cond = LowerXALUO(Cond, DAG);
8760 // Look pass (and (setcc_carry (cmp ...)), 1).
8761 if (Cond.getOpcode() == ISD::AND &&
8762 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8763 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8764 if (C && C->getAPIntValue() == 1)
8765 Cond = Cond.getOperand(0);
8768 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8769 // setting operand in place of the X86ISD::SETCC.
8770 unsigned CondOpcode = Cond.getOpcode();
8771 if (CondOpcode == X86ISD::SETCC ||
8772 CondOpcode == X86ISD::SETCC_CARRY) {
8773 CC = Cond.getOperand(0);
8775 SDValue Cmp = Cond.getOperand(1);
8776 unsigned Opc = Cmp.getOpcode();
8777 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8778 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8782 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8786 // These can only come from an arithmetic instruction with overflow,
8787 // e.g. SADDO, UADDO.
8788 Cond = Cond.getNode()->getOperand(1);
8794 CondOpcode = Cond.getOpcode();
8795 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8796 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8797 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8798 Cond.getOperand(0).getValueType() != MVT::i8)) {
8799 SDValue LHS = Cond.getOperand(0);
8800 SDValue RHS = Cond.getOperand(1);
8804 switch (CondOpcode) {
8805 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8806 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8807 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8808 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8809 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8810 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8811 default: llvm_unreachable("unexpected overflowing operator");
8814 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8815 if (CondOpcode == ISD::UMULO)
8816 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8819 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8821 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8823 if (CondOpcode == ISD::UMULO)
8824 Cond = X86Op.getValue(2);
8826 Cond = X86Op.getValue(1);
8828 CC = DAG.getConstant(X86Cond, MVT::i8);
8832 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8833 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8834 if (CondOpc == ISD::OR) {
8835 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8836 // two branches instead of an explicit OR instruction with a
8838 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8839 isX86LogicalCmp(Cmp)) {
8840 CC = Cond.getOperand(0).getOperand(0);
8841 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8842 Chain, Dest, CC, Cmp);
8843 CC = Cond.getOperand(1).getOperand(0);
8847 } else { // ISD::AND
8848 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8849 // two branches instead of an explicit AND instruction with a
8850 // separate test. However, we only do this if this block doesn't
8851 // have a fall-through edge, because this requires an explicit
8852 // jmp when the condition is false.
8853 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8854 isX86LogicalCmp(Cmp) &&
8855 Op.getNode()->hasOneUse()) {
8856 X86::CondCode CCode =
8857 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8858 CCode = X86::GetOppositeBranchCondition(CCode);
8859 CC = DAG.getConstant(CCode, MVT::i8);
8860 SDNode *User = *Op.getNode()->use_begin();
8861 // Look for an unconditional branch following this conditional branch.
8862 // We need this because we need to reverse the successors in order
8863 // to implement FCMP_OEQ.
8864 if (User->getOpcode() == ISD::BR) {
8865 SDValue FalseBB = User->getOperand(1);
8867 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8868 assert(NewBR == User);
8872 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8873 Chain, Dest, CC, Cmp);
8874 X86::CondCode CCode =
8875 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8876 CCode = X86::GetOppositeBranchCondition(CCode);
8877 CC = DAG.getConstant(CCode, MVT::i8);
8883 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8884 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8885 // It should be transformed during dag combiner except when the condition
8886 // is set by a arithmetics with overflow node.
8887 X86::CondCode CCode =
8888 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8889 CCode = X86::GetOppositeBranchCondition(CCode);
8890 CC = DAG.getConstant(CCode, MVT::i8);
8891 Cond = Cond.getOperand(0).getOperand(1);
8893 } else if (Cond.getOpcode() == ISD::SETCC &&
8894 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8895 // For FCMP_OEQ, we can emit
8896 // two branches instead of an explicit AND instruction with a
8897 // separate test. However, we only do this if this block doesn't
8898 // have a fall-through edge, because this requires an explicit
8899 // jmp when the condition is false.
8900 if (Op.getNode()->hasOneUse()) {
8901 SDNode *User = *Op.getNode()->use_begin();
8902 // Look for an unconditional branch following this conditional branch.
8903 // We need this because we need to reverse the successors in order
8904 // to implement FCMP_OEQ.
8905 if (User->getOpcode() == ISD::BR) {
8906 SDValue FalseBB = User->getOperand(1);
8908 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8909 assert(NewBR == User);
8913 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8914 Cond.getOperand(0), Cond.getOperand(1));
8915 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8916 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8917 Chain, Dest, CC, Cmp);
8918 CC = DAG.getConstant(X86::COND_P, MVT::i8);
8923 } else if (Cond.getOpcode() == ISD::SETCC &&
8924 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8925 // For FCMP_UNE, we can emit
8926 // two branches instead of an explicit AND instruction with a
8927 // separate test. However, we only do this if this block doesn't
8928 // have a fall-through edge, because this requires an explicit
8929 // jmp when the condition is false.
8930 if (Op.getNode()->hasOneUse()) {
8931 SDNode *User = *Op.getNode()->use_begin();
8932 // Look for an unconditional branch following this conditional branch.
8933 // We need this because we need to reverse the successors in order
8934 // to implement FCMP_UNE.
8935 if (User->getOpcode() == ISD::BR) {
8936 SDValue FalseBB = User->getOperand(1);
8938 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8939 assert(NewBR == User);
8942 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8943 Cond.getOperand(0), Cond.getOperand(1));
8944 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8945 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8946 Chain, Dest, CC, Cmp);
8947 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8957 // Look pass the truncate.
8958 if (Cond.getOpcode() == ISD::TRUNCATE)
8959 Cond = Cond.getOperand(0);
8961 // We know the result of AND is compared against zero. Try to match
8963 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8964 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8965 if (NewSetCC.getNode()) {
8966 CC = NewSetCC.getOperand(0);
8967 Cond = NewSetCC.getOperand(1);
8974 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8975 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8977 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8978 Chain, Dest, CC, Cond);
8982 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8983 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8984 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8985 // that the guard pages used by the OS virtual memory manager are allocated in
8986 // correct sequence.
8988 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8989 SelectionDAG &DAG) const {
8990 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8991 getTargetMachine().Options.EnableSegmentedStacks) &&
8992 "This should be used only on Windows targets or when segmented stacks "
8994 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8995 DebugLoc dl = Op.getDebugLoc();
8998 SDValue Chain = Op.getOperand(0);
8999 SDValue Size = Op.getOperand(1);
9000 // FIXME: Ensure alignment here
9002 bool Is64Bit = Subtarget->is64Bit();
9003 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9005 if (getTargetMachine().Options.EnableSegmentedStacks) {
9006 MachineFunction &MF = DAG.getMachineFunction();
9007 MachineRegisterInfo &MRI = MF.getRegInfo();
9010 // The 64 bit implementation of segmented stacks needs to clobber both r10
9011 // r11. This makes it impossible to use it along with nested parameters.
9012 const Function *F = MF.getFunction();
9014 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9016 if (I->hasNestAttr())
9017 report_fatal_error("Cannot use segmented stacks with functions that "
9018 "have nested arguments.");
9021 const TargetRegisterClass *AddrRegClass =
9022 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9023 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9024 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9025 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9026 DAG.getRegister(Vreg, SPTy));
9027 SDValue Ops1[2] = { Value, Chain };
9028 return DAG.getMergeValues(Ops1, 2, dl);
9031 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9033 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9034 Flag = Chain.getValue(1);
9035 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9037 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9038 Flag = Chain.getValue(1);
9040 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9042 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9043 return DAG.getMergeValues(Ops1, 2, dl);
9047 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9048 MachineFunction &MF = DAG.getMachineFunction();
9049 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9051 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9052 DebugLoc DL = Op.getDebugLoc();
9054 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9055 // vastart just stores the address of the VarArgsFrameIndex slot into the
9056 // memory location argument.
9057 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9059 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9060 MachinePointerInfo(SV), false, false, 0);
9064 // gp_offset (0 - 6 * 8)
9065 // fp_offset (48 - 48 + 8 * 16)
9066 // overflow_arg_area (point to parameters coming in memory).
9068 SmallVector<SDValue, 8> MemOps;
9069 SDValue FIN = Op.getOperand(1);
9071 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9072 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9074 FIN, MachinePointerInfo(SV), false, false, 0);
9075 MemOps.push_back(Store);
9078 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9079 FIN, DAG.getIntPtrConstant(4));
9080 Store = DAG.getStore(Op.getOperand(0), DL,
9081 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9083 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9084 MemOps.push_back(Store);
9086 // Store ptr to overflow_arg_area
9087 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9088 FIN, DAG.getIntPtrConstant(4));
9089 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9091 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9092 MachinePointerInfo(SV, 8),
9094 MemOps.push_back(Store);
9096 // Store ptr to reg_save_area.
9097 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9098 FIN, DAG.getIntPtrConstant(8));
9099 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9101 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9102 MachinePointerInfo(SV, 16), false, false, 0);
9103 MemOps.push_back(Store);
9104 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9105 &MemOps[0], MemOps.size());
9108 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9109 assert(Subtarget->is64Bit() &&
9110 "LowerVAARG only handles 64-bit va_arg!");
9111 assert((Subtarget->isTargetLinux() ||
9112 Subtarget->isTargetDarwin()) &&
9113 "Unhandled target in LowerVAARG");
9114 assert(Op.getNode()->getNumOperands() == 4);
9115 SDValue Chain = Op.getOperand(0);
9116 SDValue SrcPtr = Op.getOperand(1);
9117 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9118 unsigned Align = Op.getConstantOperandVal(3);
9119 DebugLoc dl = Op.getDebugLoc();
9121 EVT ArgVT = Op.getNode()->getValueType(0);
9122 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9123 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9126 // Decide which area this value should be read from.
9127 // TODO: Implement the AMD64 ABI in its entirety. This simple
9128 // selection mechanism works only for the basic types.
9129 if (ArgVT == MVT::f80) {
9130 llvm_unreachable("va_arg for f80 not yet implemented");
9131 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9132 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9133 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9134 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9136 llvm_unreachable("Unhandled argument type in LowerVAARG");
9140 // Sanity Check: Make sure using fp_offset makes sense.
9141 assert(!getTargetMachine().Options.UseSoftFloat &&
9142 !(DAG.getMachineFunction()
9143 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9144 Subtarget->hasXMM());
9147 // Insert VAARG_64 node into the DAG
9148 // VAARG_64 returns two values: Variable Argument Address, Chain
9149 SmallVector<SDValue, 11> InstOps;
9150 InstOps.push_back(Chain);
9151 InstOps.push_back(SrcPtr);
9152 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9153 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9154 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9155 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9156 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9157 VTs, &InstOps[0], InstOps.size(),
9159 MachinePointerInfo(SV),
9164 Chain = VAARG.getValue(1);
9166 // Load the next argument and return it
9167 return DAG.getLoad(ArgVT, dl,
9170 MachinePointerInfo(),
9171 false, false, false, 0);
9174 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9175 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9176 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9177 SDValue Chain = Op.getOperand(0);
9178 SDValue DstPtr = Op.getOperand(1);
9179 SDValue SrcPtr = Op.getOperand(2);
9180 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9181 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9182 DebugLoc DL = Op.getDebugLoc();
9184 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9185 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9187 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9191 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9192 DebugLoc dl = Op.getDebugLoc();
9193 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9195 default: return SDValue(); // Don't custom lower most intrinsics.
9196 // Comparison intrinsics.
9197 case Intrinsic::x86_sse_comieq_ss:
9198 case Intrinsic::x86_sse_comilt_ss:
9199 case Intrinsic::x86_sse_comile_ss:
9200 case Intrinsic::x86_sse_comigt_ss:
9201 case Intrinsic::x86_sse_comige_ss:
9202 case Intrinsic::x86_sse_comineq_ss:
9203 case Intrinsic::x86_sse_ucomieq_ss:
9204 case Intrinsic::x86_sse_ucomilt_ss:
9205 case Intrinsic::x86_sse_ucomile_ss:
9206 case Intrinsic::x86_sse_ucomigt_ss:
9207 case Intrinsic::x86_sse_ucomige_ss:
9208 case Intrinsic::x86_sse_ucomineq_ss:
9209 case Intrinsic::x86_sse2_comieq_sd:
9210 case Intrinsic::x86_sse2_comilt_sd:
9211 case Intrinsic::x86_sse2_comile_sd:
9212 case Intrinsic::x86_sse2_comigt_sd:
9213 case Intrinsic::x86_sse2_comige_sd:
9214 case Intrinsic::x86_sse2_comineq_sd:
9215 case Intrinsic::x86_sse2_ucomieq_sd:
9216 case Intrinsic::x86_sse2_ucomilt_sd:
9217 case Intrinsic::x86_sse2_ucomile_sd:
9218 case Intrinsic::x86_sse2_ucomigt_sd:
9219 case Intrinsic::x86_sse2_ucomige_sd:
9220 case Intrinsic::x86_sse2_ucomineq_sd: {
9222 ISD::CondCode CC = ISD::SETCC_INVALID;
9225 case Intrinsic::x86_sse_comieq_ss:
9226 case Intrinsic::x86_sse2_comieq_sd:
9230 case Intrinsic::x86_sse_comilt_ss:
9231 case Intrinsic::x86_sse2_comilt_sd:
9235 case Intrinsic::x86_sse_comile_ss:
9236 case Intrinsic::x86_sse2_comile_sd:
9240 case Intrinsic::x86_sse_comigt_ss:
9241 case Intrinsic::x86_sse2_comigt_sd:
9245 case Intrinsic::x86_sse_comige_ss:
9246 case Intrinsic::x86_sse2_comige_sd:
9250 case Intrinsic::x86_sse_comineq_ss:
9251 case Intrinsic::x86_sse2_comineq_sd:
9255 case Intrinsic::x86_sse_ucomieq_ss:
9256 case Intrinsic::x86_sse2_ucomieq_sd:
9257 Opc = X86ISD::UCOMI;
9260 case Intrinsic::x86_sse_ucomilt_ss:
9261 case Intrinsic::x86_sse2_ucomilt_sd:
9262 Opc = X86ISD::UCOMI;
9265 case Intrinsic::x86_sse_ucomile_ss:
9266 case Intrinsic::x86_sse2_ucomile_sd:
9267 Opc = X86ISD::UCOMI;
9270 case Intrinsic::x86_sse_ucomigt_ss:
9271 case Intrinsic::x86_sse2_ucomigt_sd:
9272 Opc = X86ISD::UCOMI;
9275 case Intrinsic::x86_sse_ucomige_ss:
9276 case Intrinsic::x86_sse2_ucomige_sd:
9277 Opc = X86ISD::UCOMI;
9280 case Intrinsic::x86_sse_ucomineq_ss:
9281 case Intrinsic::x86_sse2_ucomineq_sd:
9282 Opc = X86ISD::UCOMI;
9287 SDValue LHS = Op.getOperand(1);
9288 SDValue RHS = Op.getOperand(2);
9289 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9290 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9291 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9292 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9293 DAG.getConstant(X86CC, MVT::i8), Cond);
9294 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9296 // Arithmetic intrinsics.
9297 case Intrinsic::x86_sse3_hadd_ps:
9298 case Intrinsic::x86_sse3_hadd_pd:
9299 case Intrinsic::x86_avx_hadd_ps_256:
9300 case Intrinsic::x86_avx_hadd_pd_256:
9301 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9302 Op.getOperand(1), Op.getOperand(2));
9303 case Intrinsic::x86_sse3_hsub_ps:
9304 case Intrinsic::x86_sse3_hsub_pd:
9305 case Intrinsic::x86_avx_hsub_ps_256:
9306 case Intrinsic::x86_avx_hsub_pd_256:
9307 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9308 Op.getOperand(1), Op.getOperand(2));
9309 case Intrinsic::x86_avx2_psllv_d:
9310 case Intrinsic::x86_avx2_psllv_q:
9311 case Intrinsic::x86_avx2_psllv_d_256:
9312 case Intrinsic::x86_avx2_psllv_q_256:
9313 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9314 Op.getOperand(1), Op.getOperand(2));
9315 case Intrinsic::x86_avx2_psrlv_d:
9316 case Intrinsic::x86_avx2_psrlv_q:
9317 case Intrinsic::x86_avx2_psrlv_d_256:
9318 case Intrinsic::x86_avx2_psrlv_q_256:
9319 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9320 Op.getOperand(1), Op.getOperand(2));
9321 case Intrinsic::x86_avx2_psrav_d:
9322 case Intrinsic::x86_avx2_psrav_d_256:
9323 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9324 Op.getOperand(1), Op.getOperand(2));
9326 // ptest and testp intrinsics. The intrinsic these come from are designed to
9327 // return an integer value, not just an instruction so lower it to the ptest
9328 // or testp pattern and a setcc for the result.
9329 case Intrinsic::x86_sse41_ptestz:
9330 case Intrinsic::x86_sse41_ptestc:
9331 case Intrinsic::x86_sse41_ptestnzc:
9332 case Intrinsic::x86_avx_ptestz_256:
9333 case Intrinsic::x86_avx_ptestc_256:
9334 case Intrinsic::x86_avx_ptestnzc_256:
9335 case Intrinsic::x86_avx_vtestz_ps:
9336 case Intrinsic::x86_avx_vtestc_ps:
9337 case Intrinsic::x86_avx_vtestnzc_ps:
9338 case Intrinsic::x86_avx_vtestz_pd:
9339 case Intrinsic::x86_avx_vtestc_pd:
9340 case Intrinsic::x86_avx_vtestnzc_pd:
9341 case Intrinsic::x86_avx_vtestz_ps_256:
9342 case Intrinsic::x86_avx_vtestc_ps_256:
9343 case Intrinsic::x86_avx_vtestnzc_ps_256:
9344 case Intrinsic::x86_avx_vtestz_pd_256:
9345 case Intrinsic::x86_avx_vtestc_pd_256:
9346 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9347 bool IsTestPacked = false;
9350 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9351 case Intrinsic::x86_avx_vtestz_ps:
9352 case Intrinsic::x86_avx_vtestz_pd:
9353 case Intrinsic::x86_avx_vtestz_ps_256:
9354 case Intrinsic::x86_avx_vtestz_pd_256:
9355 IsTestPacked = true; // Fallthrough
9356 case Intrinsic::x86_sse41_ptestz:
9357 case Intrinsic::x86_avx_ptestz_256:
9359 X86CC = X86::COND_E;
9361 case Intrinsic::x86_avx_vtestc_ps:
9362 case Intrinsic::x86_avx_vtestc_pd:
9363 case Intrinsic::x86_avx_vtestc_ps_256:
9364 case Intrinsic::x86_avx_vtestc_pd_256:
9365 IsTestPacked = true; // Fallthrough
9366 case Intrinsic::x86_sse41_ptestc:
9367 case Intrinsic::x86_avx_ptestc_256:
9369 X86CC = X86::COND_B;
9371 case Intrinsic::x86_avx_vtestnzc_ps:
9372 case Intrinsic::x86_avx_vtestnzc_pd:
9373 case Intrinsic::x86_avx_vtestnzc_ps_256:
9374 case Intrinsic::x86_avx_vtestnzc_pd_256:
9375 IsTestPacked = true; // Fallthrough
9376 case Intrinsic::x86_sse41_ptestnzc:
9377 case Intrinsic::x86_avx_ptestnzc_256:
9379 X86CC = X86::COND_A;
9383 SDValue LHS = Op.getOperand(1);
9384 SDValue RHS = Op.getOperand(2);
9385 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9386 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9387 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9388 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9389 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9392 // Fix vector shift instructions where the last operand is a non-immediate
9394 case Intrinsic::x86_avx2_pslli_w:
9395 case Intrinsic::x86_avx2_pslli_d:
9396 case Intrinsic::x86_avx2_pslli_q:
9397 case Intrinsic::x86_avx2_psrli_w:
9398 case Intrinsic::x86_avx2_psrli_d:
9399 case Intrinsic::x86_avx2_psrli_q:
9400 case Intrinsic::x86_avx2_psrai_w:
9401 case Intrinsic::x86_avx2_psrai_d:
9402 case Intrinsic::x86_sse2_pslli_w:
9403 case Intrinsic::x86_sse2_pslli_d:
9404 case Intrinsic::x86_sse2_pslli_q:
9405 case Intrinsic::x86_sse2_psrli_w:
9406 case Intrinsic::x86_sse2_psrli_d:
9407 case Intrinsic::x86_sse2_psrli_q:
9408 case Intrinsic::x86_sse2_psrai_w:
9409 case Intrinsic::x86_sse2_psrai_d:
9410 case Intrinsic::x86_mmx_pslli_w:
9411 case Intrinsic::x86_mmx_pslli_d:
9412 case Intrinsic::x86_mmx_pslli_q:
9413 case Intrinsic::x86_mmx_psrli_w:
9414 case Intrinsic::x86_mmx_psrli_d:
9415 case Intrinsic::x86_mmx_psrli_q:
9416 case Intrinsic::x86_mmx_psrai_w:
9417 case Intrinsic::x86_mmx_psrai_d: {
9418 SDValue ShAmt = Op.getOperand(2);
9419 if (isa<ConstantSDNode>(ShAmt))
9422 unsigned NewIntNo = 0;
9423 EVT ShAmtVT = MVT::v4i32;
9425 case Intrinsic::x86_sse2_pslli_w:
9426 NewIntNo = Intrinsic::x86_sse2_psll_w;
9428 case Intrinsic::x86_sse2_pslli_d:
9429 NewIntNo = Intrinsic::x86_sse2_psll_d;
9431 case Intrinsic::x86_sse2_pslli_q:
9432 NewIntNo = Intrinsic::x86_sse2_psll_q;
9434 case Intrinsic::x86_sse2_psrli_w:
9435 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9437 case Intrinsic::x86_sse2_psrli_d:
9438 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9440 case Intrinsic::x86_sse2_psrli_q:
9441 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9443 case Intrinsic::x86_sse2_psrai_w:
9444 NewIntNo = Intrinsic::x86_sse2_psra_w;
9446 case Intrinsic::x86_sse2_psrai_d:
9447 NewIntNo = Intrinsic::x86_sse2_psra_d;
9449 case Intrinsic::x86_avx2_pslli_w:
9450 NewIntNo = Intrinsic::x86_avx2_psll_w;
9452 case Intrinsic::x86_avx2_pslli_d:
9453 NewIntNo = Intrinsic::x86_avx2_psll_d;
9455 case Intrinsic::x86_avx2_pslli_q:
9456 NewIntNo = Intrinsic::x86_avx2_psll_q;
9458 case Intrinsic::x86_avx2_psrli_w:
9459 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9461 case Intrinsic::x86_avx2_psrli_d:
9462 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9464 case Intrinsic::x86_avx2_psrli_q:
9465 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9467 case Intrinsic::x86_avx2_psrai_w:
9468 NewIntNo = Intrinsic::x86_avx2_psra_w;
9470 case Intrinsic::x86_avx2_psrai_d:
9471 NewIntNo = Intrinsic::x86_avx2_psra_d;
9474 ShAmtVT = MVT::v2i32;
9476 case Intrinsic::x86_mmx_pslli_w:
9477 NewIntNo = Intrinsic::x86_mmx_psll_w;
9479 case Intrinsic::x86_mmx_pslli_d:
9480 NewIntNo = Intrinsic::x86_mmx_psll_d;
9482 case Intrinsic::x86_mmx_pslli_q:
9483 NewIntNo = Intrinsic::x86_mmx_psll_q;
9485 case Intrinsic::x86_mmx_psrli_w:
9486 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9488 case Intrinsic::x86_mmx_psrli_d:
9489 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9491 case Intrinsic::x86_mmx_psrli_q:
9492 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9494 case Intrinsic::x86_mmx_psrai_w:
9495 NewIntNo = Intrinsic::x86_mmx_psra_w;
9497 case Intrinsic::x86_mmx_psrai_d:
9498 NewIntNo = Intrinsic::x86_mmx_psra_d;
9500 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9506 // The vector shift intrinsics with scalars uses 32b shift amounts but
9507 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9511 ShOps[1] = DAG.getConstant(0, MVT::i32);
9512 if (ShAmtVT == MVT::v4i32) {
9513 ShOps[2] = DAG.getUNDEF(MVT::i32);
9514 ShOps[3] = DAG.getUNDEF(MVT::i32);
9515 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9517 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9518 // FIXME this must be lowered to get rid of the invalid type.
9521 EVT VT = Op.getValueType();
9522 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9523 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9524 DAG.getConstant(NewIntNo, MVT::i32),
9525 Op.getOperand(1), ShAmt);
9530 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9531 SelectionDAG &DAG) const {
9532 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9533 MFI->setReturnAddressIsTaken(true);
9535 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9536 DebugLoc dl = Op.getDebugLoc();
9539 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9541 DAG.getConstant(TD->getPointerSize(),
9542 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9543 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9544 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9546 MachinePointerInfo(), false, false, false, 0);
9549 // Just load the return address.
9550 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9551 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9552 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9555 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9556 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9557 MFI->setFrameAddressIsTaken(true);
9559 EVT VT = Op.getValueType();
9560 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9561 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9562 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9563 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9565 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9566 MachinePointerInfo(),
9567 false, false, false, 0);
9571 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9572 SelectionDAG &DAG) const {
9573 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9576 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9577 MachineFunction &MF = DAG.getMachineFunction();
9578 SDValue Chain = Op.getOperand(0);
9579 SDValue Offset = Op.getOperand(1);
9580 SDValue Handler = Op.getOperand(2);
9581 DebugLoc dl = Op.getDebugLoc();
9583 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9584 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9586 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9588 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9589 DAG.getIntPtrConstant(TD->getPointerSize()));
9590 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9591 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9593 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9594 MF.getRegInfo().addLiveOut(StoreAddrReg);
9596 return DAG.getNode(X86ISD::EH_RETURN, dl,
9598 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9601 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9602 SelectionDAG &DAG) const {
9603 return Op.getOperand(0);
9606 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9607 SelectionDAG &DAG) const {
9608 SDValue Root = Op.getOperand(0);
9609 SDValue Trmp = Op.getOperand(1); // trampoline
9610 SDValue FPtr = Op.getOperand(2); // nested function
9611 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9612 DebugLoc dl = Op.getDebugLoc();
9614 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9616 if (Subtarget->is64Bit()) {
9617 SDValue OutChains[6];
9619 // Large code-model.
9620 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9621 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9623 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9624 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9626 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9628 // Load the pointer to the nested function into R11.
9629 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9630 SDValue Addr = Trmp;
9631 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9632 Addr, MachinePointerInfo(TrmpAddr),
9635 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9636 DAG.getConstant(2, MVT::i64));
9637 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9638 MachinePointerInfo(TrmpAddr, 2),
9641 // Load the 'nest' parameter value into R10.
9642 // R10 is specified in X86CallingConv.td
9643 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9644 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9645 DAG.getConstant(10, MVT::i64));
9646 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9647 Addr, MachinePointerInfo(TrmpAddr, 10),
9650 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9651 DAG.getConstant(12, MVT::i64));
9652 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9653 MachinePointerInfo(TrmpAddr, 12),
9656 // Jump to the nested function.
9657 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9658 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9659 DAG.getConstant(20, MVT::i64));
9660 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9661 Addr, MachinePointerInfo(TrmpAddr, 20),
9664 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9665 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9666 DAG.getConstant(22, MVT::i64));
9667 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9668 MachinePointerInfo(TrmpAddr, 22),
9671 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9673 const Function *Func =
9674 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9675 CallingConv::ID CC = Func->getCallingConv();
9680 llvm_unreachable("Unsupported calling convention");
9681 case CallingConv::C:
9682 case CallingConv::X86_StdCall: {
9683 // Pass 'nest' parameter in ECX.
9684 // Must be kept in sync with X86CallingConv.td
9687 // Check that ECX wasn't needed by an 'inreg' parameter.
9688 FunctionType *FTy = Func->getFunctionType();
9689 const AttrListPtr &Attrs = Func->getAttributes();
9691 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9692 unsigned InRegCount = 0;
9695 for (FunctionType::param_iterator I = FTy->param_begin(),
9696 E = FTy->param_end(); I != E; ++I, ++Idx)
9697 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9698 // FIXME: should only count parameters that are lowered to integers.
9699 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9701 if (InRegCount > 2) {
9702 report_fatal_error("Nest register in use - reduce number of inreg"
9708 case CallingConv::X86_FastCall:
9709 case CallingConv::X86_ThisCall:
9710 case CallingConv::Fast:
9711 // Pass 'nest' parameter in EAX.
9712 // Must be kept in sync with X86CallingConv.td
9717 SDValue OutChains[4];
9720 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9721 DAG.getConstant(10, MVT::i32));
9722 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9724 // This is storing the opcode for MOV32ri.
9725 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9726 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9727 OutChains[0] = DAG.getStore(Root, dl,
9728 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9729 Trmp, MachinePointerInfo(TrmpAddr),
9732 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9733 DAG.getConstant(1, MVT::i32));
9734 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9735 MachinePointerInfo(TrmpAddr, 1),
9738 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9739 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9740 DAG.getConstant(5, MVT::i32));
9741 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9742 MachinePointerInfo(TrmpAddr, 5),
9745 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9746 DAG.getConstant(6, MVT::i32));
9747 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9748 MachinePointerInfo(TrmpAddr, 6),
9751 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9755 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9756 SelectionDAG &DAG) const {
9758 The rounding mode is in bits 11:10 of FPSR, and has the following
9765 FLT_ROUNDS, on the other hand, expects the following:
9772 To perform the conversion, we do:
9773 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9776 MachineFunction &MF = DAG.getMachineFunction();
9777 const TargetMachine &TM = MF.getTarget();
9778 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9779 unsigned StackAlignment = TFI.getStackAlignment();
9780 EVT VT = Op.getValueType();
9781 DebugLoc DL = Op.getDebugLoc();
9783 // Save FP Control Word to stack slot
9784 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9785 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9788 MachineMemOperand *MMO =
9789 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9790 MachineMemOperand::MOStore, 2, 2);
9792 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9793 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9794 DAG.getVTList(MVT::Other),
9795 Ops, 2, MVT::i16, MMO);
9797 // Load FP Control Word from stack slot
9798 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9799 MachinePointerInfo(), false, false, false, 0);
9801 // Transform as necessary
9803 DAG.getNode(ISD::SRL, DL, MVT::i16,
9804 DAG.getNode(ISD::AND, DL, MVT::i16,
9805 CWD, DAG.getConstant(0x800, MVT::i16)),
9806 DAG.getConstant(11, MVT::i8));
9808 DAG.getNode(ISD::SRL, DL, MVT::i16,
9809 DAG.getNode(ISD::AND, DL, MVT::i16,
9810 CWD, DAG.getConstant(0x400, MVT::i16)),
9811 DAG.getConstant(9, MVT::i8));
9814 DAG.getNode(ISD::AND, DL, MVT::i16,
9815 DAG.getNode(ISD::ADD, DL, MVT::i16,
9816 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9817 DAG.getConstant(1, MVT::i16)),
9818 DAG.getConstant(3, MVT::i16));
9821 return DAG.getNode((VT.getSizeInBits() < 16 ?
9822 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9825 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9826 EVT VT = Op.getValueType();
9828 unsigned NumBits = VT.getSizeInBits();
9829 DebugLoc dl = Op.getDebugLoc();
9831 Op = Op.getOperand(0);
9832 if (VT == MVT::i8) {
9833 // Zero extend to i32 since there is not an i8 bsr.
9835 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9838 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9839 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9840 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9842 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9845 DAG.getConstant(NumBits+NumBits-1, OpVT),
9846 DAG.getConstant(X86::COND_E, MVT::i8),
9849 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9851 // Finally xor with NumBits-1.
9852 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9855 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9859 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
9860 SelectionDAG &DAG) const {
9861 EVT VT = Op.getValueType();
9863 unsigned NumBits = VT.getSizeInBits();
9864 DebugLoc dl = Op.getDebugLoc();
9866 Op = Op.getOperand(0);
9867 if (VT == MVT::i8) {
9868 // Zero extend to i32 since there is not an i8 bsr.
9870 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9873 // Issue a bsr (scan bits in reverse).
9874 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9875 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9877 // And xor with NumBits-1.
9878 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9881 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9885 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9886 EVT VT = Op.getValueType();
9887 unsigned NumBits = VT.getSizeInBits();
9888 DebugLoc dl = Op.getDebugLoc();
9889 Op = Op.getOperand(0);
9891 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9892 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9893 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9895 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9898 DAG.getConstant(NumBits, VT),
9899 DAG.getConstant(X86::COND_E, MVT::i8),
9902 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
9905 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9906 // ones, and then concatenate the result back.
9907 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9908 EVT VT = Op.getValueType();
9910 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9911 "Unsupported value type for operation");
9913 int NumElems = VT.getVectorNumElements();
9914 DebugLoc dl = Op.getDebugLoc();
9915 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9916 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9918 // Extract the LHS vectors
9919 SDValue LHS = Op.getOperand(0);
9920 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9921 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9923 // Extract the RHS vectors
9924 SDValue RHS = Op.getOperand(1);
9925 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9926 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9928 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9929 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9931 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9932 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9933 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9936 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9937 assert(Op.getValueType().getSizeInBits() == 256 &&
9938 Op.getValueType().isInteger() &&
9939 "Only handle AVX 256-bit vector integer operation");
9940 return Lower256IntArith(Op, DAG);
9943 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9944 assert(Op.getValueType().getSizeInBits() == 256 &&
9945 Op.getValueType().isInteger() &&
9946 "Only handle AVX 256-bit vector integer operation");
9947 return Lower256IntArith(Op, DAG);
9950 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9951 EVT VT = Op.getValueType();
9953 // Decompose 256-bit ops into smaller 128-bit ops.
9954 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9955 return Lower256IntArith(Op, DAG);
9957 DebugLoc dl = Op.getDebugLoc();
9959 SDValue A = Op.getOperand(0);
9960 SDValue B = Op.getOperand(1);
9962 if (VT == MVT::v4i64) {
9963 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9965 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9966 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9967 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9968 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9969 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9971 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9972 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9973 // return AloBlo + AloBhi + AhiBlo;
9975 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9976 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9977 A, DAG.getConstant(32, MVT::i32));
9978 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9979 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9980 B, DAG.getConstant(32, MVT::i32));
9981 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9982 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9984 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9985 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9987 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9988 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9990 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9991 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9992 AloBhi, DAG.getConstant(32, MVT::i32));
9993 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9994 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9995 AhiBlo, DAG.getConstant(32, MVT::i32));
9996 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9997 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10001 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10003 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10004 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10005 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10006 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10007 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10009 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10010 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10011 // return AloBlo + AloBhi + AhiBlo;
10013 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10014 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10015 A, DAG.getConstant(32, MVT::i32));
10016 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10017 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10018 B, DAG.getConstant(32, MVT::i32));
10019 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10020 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10022 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10023 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10025 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10026 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10028 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10029 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10030 AloBhi, DAG.getConstant(32, MVT::i32));
10031 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10032 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10033 AhiBlo, DAG.getConstant(32, MVT::i32));
10034 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10035 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10039 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10041 EVT VT = Op.getValueType();
10042 DebugLoc dl = Op.getDebugLoc();
10043 SDValue R = Op.getOperand(0);
10044 SDValue Amt = Op.getOperand(1);
10045 LLVMContext *Context = DAG.getContext();
10047 if (!Subtarget->hasXMMInt())
10050 // Optimize shl/srl/sra with constant shift amount.
10051 if (isSplatVector(Amt.getNode())) {
10052 SDValue SclrAmt = Amt->getOperand(0);
10053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10054 uint64_t ShiftAmt = C->getZExtValue();
10056 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10057 // Make a large shift.
10059 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10060 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10061 R, DAG.getConstant(ShiftAmt, MVT::i32));
10062 // Zero out the rightmost bits.
10063 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10065 return DAG.getNode(ISD::AND, dl, VT, SHL,
10066 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10069 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10070 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10071 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10072 R, DAG.getConstant(ShiftAmt, MVT::i32));
10074 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10075 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10076 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10077 R, DAG.getConstant(ShiftAmt, MVT::i32));
10079 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10080 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10081 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10082 R, DAG.getConstant(ShiftAmt, MVT::i32));
10084 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10085 // Make a large shift.
10087 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10088 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10089 R, DAG.getConstant(ShiftAmt, MVT::i32));
10090 // Zero out the leftmost bits.
10091 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10093 return DAG.getNode(ISD::AND, dl, VT, SRL,
10094 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10097 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10098 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10099 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10100 R, DAG.getConstant(ShiftAmt, MVT::i32));
10102 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10103 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10104 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10105 R, DAG.getConstant(ShiftAmt, MVT::i32));
10107 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10108 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10109 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10110 R, DAG.getConstant(ShiftAmt, MVT::i32));
10112 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10113 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10114 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10115 R, DAG.getConstant(ShiftAmt, MVT::i32));
10117 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10118 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10119 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10120 R, DAG.getConstant(ShiftAmt, MVT::i32));
10122 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10123 if (ShiftAmt == 7) {
10124 // R s>> 7 === R s< 0
10125 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10126 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10129 // R s>> a === ((R u>> a) ^ m) - m
10130 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10131 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10133 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10134 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10135 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10139 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10140 if (Op.getOpcode() == ISD::SHL) {
10141 // Make a large shift.
10143 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10144 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10145 R, DAG.getConstant(ShiftAmt, MVT::i32));
10146 // Zero out the rightmost bits.
10147 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10149 return DAG.getNode(ISD::AND, dl, VT, SHL,
10150 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10152 if (Op.getOpcode() == ISD::SRL) {
10153 // Make a large shift.
10155 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10156 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10157 R, DAG.getConstant(ShiftAmt, MVT::i32));
10158 // Zero out the leftmost bits.
10159 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10161 return DAG.getNode(ISD::AND, dl, VT, SRL,
10162 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10164 if (Op.getOpcode() == ISD::SRA) {
10165 if (ShiftAmt == 7) {
10166 // R s>> 7 === R s< 0
10167 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10168 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10171 // R s>> a === ((R u>> a) ^ m) - m
10172 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10173 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10175 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10176 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10177 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10184 // Lower SHL with variable shift amount.
10185 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10186 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10187 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10188 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10190 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10192 std::vector<Constant*> CV(4, CI);
10193 Constant *C = ConstantVector::get(CV);
10194 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10195 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10196 MachinePointerInfo::getConstantPool(),
10197 false, false, false, 16);
10199 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10200 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10201 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10202 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10204 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10205 assert((Subtarget->hasSSE2() || Subtarget->hasAVX()) &&
10206 "Need SSE2 for pslli/pcmpeq.");
10209 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10210 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10211 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10213 // Turn 'a' into a mask suitable for VSELECT
10214 SDValue VSelM = DAG.getConstant(0x80, VT);
10215 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10216 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10217 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10220 SDValue CM1 = DAG.getConstant(0x0f, VT);
10221 SDValue CM2 = DAG.getConstant(0x3f, VT);
10223 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10224 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10225 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10226 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10227 DAG.getConstant(4, MVT::i32));
10228 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10231 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10232 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10233 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10234 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10237 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10238 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10239 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10240 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10241 DAG.getConstant(2, MVT::i32));
10242 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10245 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10246 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10247 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10248 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10251 // return VSELECT(r, r+r, a);
10252 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10253 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10257 // Decompose 256-bit shifts into smaller 128-bit shifts.
10258 if (VT.getSizeInBits() == 256) {
10259 int NumElems = VT.getVectorNumElements();
10260 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10261 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10263 // Extract the two vectors
10264 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10265 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10268 // Recreate the shift amount vectors
10269 SDValue Amt1, Amt2;
10270 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10271 // Constant shift amount
10272 SmallVector<SDValue, 4> Amt1Csts;
10273 SmallVector<SDValue, 4> Amt2Csts;
10274 for (int i = 0; i < NumElems/2; ++i)
10275 Amt1Csts.push_back(Amt->getOperand(i));
10276 for (int i = NumElems/2; i < NumElems; ++i)
10277 Amt2Csts.push_back(Amt->getOperand(i));
10279 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10280 &Amt1Csts[0], NumElems/2);
10281 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10282 &Amt2Csts[0], NumElems/2);
10284 // Variable shift amount
10285 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10286 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10290 // Issue new vector shifts for the smaller types
10291 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10292 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10294 // Concatenate the result back
10295 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10301 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10302 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10303 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10304 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10305 // has only one use.
10306 SDNode *N = Op.getNode();
10307 SDValue LHS = N->getOperand(0);
10308 SDValue RHS = N->getOperand(1);
10309 unsigned BaseOp = 0;
10311 DebugLoc DL = Op.getDebugLoc();
10312 switch (Op.getOpcode()) {
10313 default: llvm_unreachable("Unknown ovf instruction!");
10315 // A subtract of one will be selected as a INC. Note that INC doesn't
10316 // set CF, so we can't do this for UADDO.
10317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10319 BaseOp = X86ISD::INC;
10320 Cond = X86::COND_O;
10323 BaseOp = X86ISD::ADD;
10324 Cond = X86::COND_O;
10327 BaseOp = X86ISD::ADD;
10328 Cond = X86::COND_B;
10331 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10332 // set CF, so we can't do this for USUBO.
10333 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10335 BaseOp = X86ISD::DEC;
10336 Cond = X86::COND_O;
10339 BaseOp = X86ISD::SUB;
10340 Cond = X86::COND_O;
10343 BaseOp = X86ISD::SUB;
10344 Cond = X86::COND_B;
10347 BaseOp = X86ISD::SMUL;
10348 Cond = X86::COND_O;
10350 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10351 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10353 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10356 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10357 DAG.getConstant(X86::COND_O, MVT::i32),
10358 SDValue(Sum.getNode(), 2));
10360 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10364 // Also sets EFLAGS.
10365 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10366 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10369 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10370 DAG.getConstant(Cond, MVT::i32),
10371 SDValue(Sum.getNode(), 1));
10373 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10376 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10377 SelectionDAG &DAG) const {
10378 DebugLoc dl = Op.getDebugLoc();
10379 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10380 EVT VT = Op.getValueType();
10382 if (Subtarget->hasXMMInt() && VT.isVector()) {
10383 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10384 ExtraVT.getScalarType().getSizeInBits();
10385 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10387 unsigned SHLIntrinsicsID = 0;
10388 unsigned SRAIntrinsicsID = 0;
10389 switch (VT.getSimpleVT().SimpleTy) {
10393 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10394 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10397 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10398 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10402 if (!Subtarget->hasAVX())
10404 if (!Subtarget->hasAVX2()) {
10405 // needs to be split
10406 int NumElems = VT.getVectorNumElements();
10407 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10408 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10410 // Extract the LHS vectors
10411 SDValue LHS = Op.getOperand(0);
10412 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10413 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10415 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10416 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10418 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10419 int ExtraNumElems = ExtraVT.getVectorNumElements();
10420 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10422 SDValue Extra = DAG.getValueType(ExtraVT);
10424 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10425 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10427 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10429 if (VT == MVT::v8i32) {
10430 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10431 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10433 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10434 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10438 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10439 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10440 Op.getOperand(0), ShAmt);
10442 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10443 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10451 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10452 DebugLoc dl = Op.getDebugLoc();
10454 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10455 // There isn't any reason to disable it if the target processor supports it.
10456 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10457 SDValue Chain = Op.getOperand(0);
10458 SDValue Zero = DAG.getConstant(0, MVT::i32);
10460 DAG.getRegister(X86::ESP, MVT::i32), // Base
10461 DAG.getTargetConstant(1, MVT::i8), // Scale
10462 DAG.getRegister(0, MVT::i32), // Index
10463 DAG.getTargetConstant(0, MVT::i32), // Disp
10464 DAG.getRegister(0, MVT::i32), // Segment.
10469 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10470 array_lengthof(Ops));
10471 return SDValue(Res, 0);
10474 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10476 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10478 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10479 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10480 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10481 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10483 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10484 if (!Op1 && !Op2 && !Op3 && Op4)
10485 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10487 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10488 if (Op1 && !Op2 && !Op3 && !Op4)
10489 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10491 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10493 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10496 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10497 SelectionDAG &DAG) const {
10498 DebugLoc dl = Op.getDebugLoc();
10499 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10500 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10501 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10502 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10504 // The only fence that needs an instruction is a sequentially-consistent
10505 // cross-thread fence.
10506 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10507 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10508 // no-sse2). There isn't any reason to disable it if the target processor
10510 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10511 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10513 SDValue Chain = Op.getOperand(0);
10514 SDValue Zero = DAG.getConstant(0, MVT::i32);
10516 DAG.getRegister(X86::ESP, MVT::i32), // Base
10517 DAG.getTargetConstant(1, MVT::i8), // Scale
10518 DAG.getRegister(0, MVT::i32), // Index
10519 DAG.getTargetConstant(0, MVT::i32), // Disp
10520 DAG.getRegister(0, MVT::i32), // Segment.
10525 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10526 array_lengthof(Ops));
10527 return SDValue(Res, 0);
10530 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10531 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10535 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10536 EVT T = Op.getValueType();
10537 DebugLoc DL = Op.getDebugLoc();
10540 switch(T.getSimpleVT().SimpleTy) {
10542 assert(false && "Invalid value type!");
10543 case MVT::i8: Reg = X86::AL; size = 1; break;
10544 case MVT::i16: Reg = X86::AX; size = 2; break;
10545 case MVT::i32: Reg = X86::EAX; size = 4; break;
10547 assert(Subtarget->is64Bit() && "Node not type legal!");
10548 Reg = X86::RAX; size = 8;
10551 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10552 Op.getOperand(2), SDValue());
10553 SDValue Ops[] = { cpIn.getValue(0),
10556 DAG.getTargetConstant(size, MVT::i8),
10557 cpIn.getValue(1) };
10558 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10559 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10560 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10563 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10567 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10568 SelectionDAG &DAG) const {
10569 assert(Subtarget->is64Bit() && "Result not type legalized?");
10570 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10571 SDValue TheChain = Op.getOperand(0);
10572 DebugLoc dl = Op.getDebugLoc();
10573 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10574 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10575 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10577 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10578 DAG.getConstant(32, MVT::i8));
10580 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10583 return DAG.getMergeValues(Ops, 2, dl);
10586 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10587 SelectionDAG &DAG) const {
10588 EVT SrcVT = Op.getOperand(0).getValueType();
10589 EVT DstVT = Op.getValueType();
10590 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10591 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10592 assert((DstVT == MVT::i64 ||
10593 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10594 "Unexpected custom BITCAST");
10595 // i64 <=> MMX conversions are Legal.
10596 if (SrcVT==MVT::i64 && DstVT.isVector())
10598 if (DstVT==MVT::i64 && SrcVT.isVector())
10600 // MMX <=> MMX conversions are Legal.
10601 if (SrcVT.isVector() && DstVT.isVector())
10603 // All other conversions need to be expanded.
10607 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10608 SDNode *Node = Op.getNode();
10609 DebugLoc dl = Node->getDebugLoc();
10610 EVT T = Node->getValueType(0);
10611 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10612 DAG.getConstant(0, T), Node->getOperand(2));
10613 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10614 cast<AtomicSDNode>(Node)->getMemoryVT(),
10615 Node->getOperand(0),
10616 Node->getOperand(1), negOp,
10617 cast<AtomicSDNode>(Node)->getSrcValue(),
10618 cast<AtomicSDNode>(Node)->getAlignment(),
10619 cast<AtomicSDNode>(Node)->getOrdering(),
10620 cast<AtomicSDNode>(Node)->getSynchScope());
10623 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10624 SDNode *Node = Op.getNode();
10625 DebugLoc dl = Node->getDebugLoc();
10626 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10628 // Convert seq_cst store -> xchg
10629 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10630 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10631 // (The only way to get a 16-byte store is cmpxchg16b)
10632 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10633 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10634 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10635 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10636 cast<AtomicSDNode>(Node)->getMemoryVT(),
10637 Node->getOperand(0),
10638 Node->getOperand(1), Node->getOperand(2),
10639 cast<AtomicSDNode>(Node)->getMemOperand(),
10640 cast<AtomicSDNode>(Node)->getOrdering(),
10641 cast<AtomicSDNode>(Node)->getSynchScope());
10642 return Swap.getValue(1);
10644 // Other atomic stores have a simple pattern.
10648 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10649 EVT VT = Op.getNode()->getValueType(0);
10651 // Let legalize expand this if it isn't a legal type yet.
10652 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10655 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10658 bool ExtraOp = false;
10659 switch (Op.getOpcode()) {
10660 default: assert(0 && "Invalid code");
10661 case ISD::ADDC: Opc = X86ISD::ADD; break;
10662 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10663 case ISD::SUBC: Opc = X86ISD::SUB; break;
10664 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10668 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10670 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10671 Op.getOperand(1), Op.getOperand(2));
10674 /// LowerOperation - Provide custom lowering hooks for some operations.
10676 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10677 switch (Op.getOpcode()) {
10678 default: llvm_unreachable("Should not custom lower this!");
10679 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10680 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10681 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10682 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10683 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10684 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10685 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10686 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10687 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10688 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10689 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10690 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10691 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10692 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10693 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10694 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10695 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10696 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10697 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10698 case ISD::SHL_PARTS:
10699 case ISD::SRA_PARTS:
10700 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10701 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10702 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10703 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10704 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10705 case ISD::FABS: return LowerFABS(Op, DAG);
10706 case ISD::FNEG: return LowerFNEG(Op, DAG);
10707 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10708 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10709 case ISD::SETCC: return LowerSETCC(Op, DAG);
10710 case ISD::SELECT: return LowerSELECT(Op, DAG);
10711 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10712 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10713 case ISD::VASTART: return LowerVASTART(Op, DAG);
10714 case ISD::VAARG: return LowerVAARG(Op, DAG);
10715 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10716 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10717 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10718 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10719 case ISD::FRAME_TO_ARGS_OFFSET:
10720 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10721 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10722 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10723 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10724 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10725 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10726 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10727 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10728 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10729 case ISD::MUL: return LowerMUL(Op, DAG);
10732 case ISD::SHL: return LowerShift(Op, DAG);
10738 case ISD::UMULO: return LowerXALUO(Op, DAG);
10739 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10740 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10744 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10745 case ISD::ADD: return LowerADD(Op, DAG);
10746 case ISD::SUB: return LowerSUB(Op, DAG);
10750 static void ReplaceATOMIC_LOAD(SDNode *Node,
10751 SmallVectorImpl<SDValue> &Results,
10752 SelectionDAG &DAG) {
10753 DebugLoc dl = Node->getDebugLoc();
10754 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10756 // Convert wide load -> cmpxchg8b/cmpxchg16b
10757 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10758 // (The only way to get a 16-byte load is cmpxchg16b)
10759 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10760 SDValue Zero = DAG.getConstant(0, VT);
10761 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10762 Node->getOperand(0),
10763 Node->getOperand(1), Zero, Zero,
10764 cast<AtomicSDNode>(Node)->getMemOperand(),
10765 cast<AtomicSDNode>(Node)->getOrdering(),
10766 cast<AtomicSDNode>(Node)->getSynchScope());
10767 Results.push_back(Swap.getValue(0));
10768 Results.push_back(Swap.getValue(1));
10771 void X86TargetLowering::
10772 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10773 SelectionDAG &DAG, unsigned NewOp) const {
10774 DebugLoc dl = Node->getDebugLoc();
10775 assert (Node->getValueType(0) == MVT::i64 &&
10776 "Only know how to expand i64 atomics");
10778 SDValue Chain = Node->getOperand(0);
10779 SDValue In1 = Node->getOperand(1);
10780 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10781 Node->getOperand(2), DAG.getIntPtrConstant(0));
10782 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10783 Node->getOperand(2), DAG.getIntPtrConstant(1));
10784 SDValue Ops[] = { Chain, In1, In2L, In2H };
10785 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10787 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10788 cast<MemSDNode>(Node)->getMemOperand());
10789 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10790 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10791 Results.push_back(Result.getValue(2));
10794 /// ReplaceNodeResults - Replace a node with an illegal result type
10795 /// with a new node built out of custom code.
10796 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10797 SmallVectorImpl<SDValue>&Results,
10798 SelectionDAG &DAG) const {
10799 DebugLoc dl = N->getDebugLoc();
10800 switch (N->getOpcode()) {
10802 assert(false && "Do not know how to custom type legalize this operation!");
10804 case ISD::SIGN_EXTEND_INREG:
10809 // We don't want to expand or promote these.
10811 case ISD::FP_TO_SINT: {
10812 std::pair<SDValue,SDValue> Vals =
10813 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10814 SDValue FIST = Vals.first, StackSlot = Vals.second;
10815 if (FIST.getNode() != 0) {
10816 EVT VT = N->getValueType(0);
10817 // Return a load from the stack slot.
10818 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10819 MachinePointerInfo(),
10820 false, false, false, 0));
10824 case ISD::READCYCLECOUNTER: {
10825 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10826 SDValue TheChain = N->getOperand(0);
10827 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10828 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10830 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10832 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10833 SDValue Ops[] = { eax, edx };
10834 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10835 Results.push_back(edx.getValue(1));
10838 case ISD::ATOMIC_CMP_SWAP: {
10839 EVT T = N->getValueType(0);
10840 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10841 bool Regs64bit = T == MVT::i128;
10842 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10843 SDValue cpInL, cpInH;
10844 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10845 DAG.getConstant(0, HalfT));
10846 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10847 DAG.getConstant(1, HalfT));
10848 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10849 Regs64bit ? X86::RAX : X86::EAX,
10851 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10852 Regs64bit ? X86::RDX : X86::EDX,
10853 cpInH, cpInL.getValue(1));
10854 SDValue swapInL, swapInH;
10855 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10856 DAG.getConstant(0, HalfT));
10857 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10858 DAG.getConstant(1, HalfT));
10859 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10860 Regs64bit ? X86::RBX : X86::EBX,
10861 swapInL, cpInH.getValue(1));
10862 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10863 Regs64bit ? X86::RCX : X86::ECX,
10864 swapInH, swapInL.getValue(1));
10865 SDValue Ops[] = { swapInH.getValue(0),
10867 swapInH.getValue(1) };
10868 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10869 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10870 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10871 X86ISD::LCMPXCHG8_DAG;
10872 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10874 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10875 Regs64bit ? X86::RAX : X86::EAX,
10876 HalfT, Result.getValue(1));
10877 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10878 Regs64bit ? X86::RDX : X86::EDX,
10879 HalfT, cpOutL.getValue(2));
10880 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10881 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10882 Results.push_back(cpOutH.getValue(1));
10885 case ISD::ATOMIC_LOAD_ADD:
10886 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10888 case ISD::ATOMIC_LOAD_AND:
10889 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10891 case ISD::ATOMIC_LOAD_NAND:
10892 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10894 case ISD::ATOMIC_LOAD_OR:
10895 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10897 case ISD::ATOMIC_LOAD_SUB:
10898 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10900 case ISD::ATOMIC_LOAD_XOR:
10901 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10903 case ISD::ATOMIC_SWAP:
10904 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10906 case ISD::ATOMIC_LOAD:
10907 ReplaceATOMIC_LOAD(N, Results, DAG);
10911 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10913 default: return NULL;
10914 case X86ISD::BSF: return "X86ISD::BSF";
10915 case X86ISD::BSR: return "X86ISD::BSR";
10916 case X86ISD::SHLD: return "X86ISD::SHLD";
10917 case X86ISD::SHRD: return "X86ISD::SHRD";
10918 case X86ISD::FAND: return "X86ISD::FAND";
10919 case X86ISD::FOR: return "X86ISD::FOR";
10920 case X86ISD::FXOR: return "X86ISD::FXOR";
10921 case X86ISD::FSRL: return "X86ISD::FSRL";
10922 case X86ISD::FILD: return "X86ISD::FILD";
10923 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10924 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10925 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10926 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10927 case X86ISD::FLD: return "X86ISD::FLD";
10928 case X86ISD::FST: return "X86ISD::FST";
10929 case X86ISD::CALL: return "X86ISD::CALL";
10930 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10931 case X86ISD::BT: return "X86ISD::BT";
10932 case X86ISD::CMP: return "X86ISD::CMP";
10933 case X86ISD::COMI: return "X86ISD::COMI";
10934 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10935 case X86ISD::SETCC: return "X86ISD::SETCC";
10936 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10937 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10938 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10939 case X86ISD::CMOV: return "X86ISD::CMOV";
10940 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10941 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10942 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10943 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10944 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10945 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10946 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10947 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10948 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10949 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10950 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10951 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10952 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10953 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10954 case X86ISD::PSIGN: return "X86ISD::PSIGN";
10955 case X86ISD::BLENDV: return "X86ISD::BLENDV";
10956 case X86ISD::HADD: return "X86ISD::HADD";
10957 case X86ISD::HSUB: return "X86ISD::HSUB";
10958 case X86ISD::FHADD: return "X86ISD::FHADD";
10959 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10960 case X86ISD::FMAX: return "X86ISD::FMAX";
10961 case X86ISD::FMIN: return "X86ISD::FMIN";
10962 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10963 case X86ISD::FRCP: return "X86ISD::FRCP";
10964 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10965 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10966 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10967 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10968 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10969 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10970 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10971 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10972 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10973 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10974 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10975 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10976 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10977 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10978 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10979 case X86ISD::VSHL: return "X86ISD::VSHL";
10980 case X86ISD::VSRL: return "X86ISD::VSRL";
10981 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10982 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10983 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10984 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10985 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10986 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10987 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10988 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10989 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10990 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10991 case X86ISD::ADD: return "X86ISD::ADD";
10992 case X86ISD::SUB: return "X86ISD::SUB";
10993 case X86ISD::ADC: return "X86ISD::ADC";
10994 case X86ISD::SBB: return "X86ISD::SBB";
10995 case X86ISD::SMUL: return "X86ISD::SMUL";
10996 case X86ISD::UMUL: return "X86ISD::UMUL";
10997 case X86ISD::INC: return "X86ISD::INC";
10998 case X86ISD::DEC: return "X86ISD::DEC";
10999 case X86ISD::OR: return "X86ISD::OR";
11000 case X86ISD::XOR: return "X86ISD::XOR";
11001 case X86ISD::AND: return "X86ISD::AND";
11002 case X86ISD::ANDN: return "X86ISD::ANDN";
11003 case X86ISD::BLSI: return "X86ISD::BLSI";
11004 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11005 case X86ISD::BLSR: return "X86ISD::BLSR";
11006 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11007 case X86ISD::PTEST: return "X86ISD::PTEST";
11008 case X86ISD::TESTP: return "X86ISD::TESTP";
11009 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11010 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11011 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11012 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
11013 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11014 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
11015 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11016 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11017 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11018 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11019 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11020 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11021 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11022 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11023 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11024 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
11025 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
11026 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11027 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11028 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11029 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11030 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11031 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11032 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11033 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11034 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11035 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11036 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11037 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11041 // isLegalAddressingMode - Return true if the addressing mode represented
11042 // by AM is legal for this target, for a load/store of the specified type.
11043 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11045 // X86 supports extremely general addressing modes.
11046 CodeModel::Model M = getTargetMachine().getCodeModel();
11047 Reloc::Model R = getTargetMachine().getRelocationModel();
11049 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11050 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11055 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11057 // If a reference to this global requires an extra load, we can't fold it.
11058 if (isGlobalStubReference(GVFlags))
11061 // If BaseGV requires a register for the PIC base, we cannot also have a
11062 // BaseReg specified.
11063 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11066 // If lower 4G is not available, then we must use rip-relative addressing.
11067 if ((M != CodeModel::Small || R != Reloc::Static) &&
11068 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11072 switch (AM.Scale) {
11078 // These scales always work.
11083 // These scales are formed with basereg+scalereg. Only accept if there is
11088 default: // Other stuff never works.
11096 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11097 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11099 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11100 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11101 if (NumBits1 <= NumBits2)
11106 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11107 if (!VT1.isInteger() || !VT2.isInteger())
11109 unsigned NumBits1 = VT1.getSizeInBits();
11110 unsigned NumBits2 = VT2.getSizeInBits();
11111 if (NumBits1 <= NumBits2)
11116 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11117 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11118 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11121 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11122 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11123 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11126 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11127 // i16 instructions are longer (0x66 prefix) and potentially slower.
11128 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11131 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11132 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11133 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11134 /// are assumed to be legal.
11136 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11138 // Very little shuffling can be done for 64-bit vectors right now.
11139 if (VT.getSizeInBits() == 64)
11142 // FIXME: pshufb, blends, shifts.
11143 return (VT.getVectorNumElements() == 2 ||
11144 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11145 isMOVLMask(M, VT) ||
11146 isSHUFPMask(M, VT) ||
11147 isPSHUFDMask(M, VT) ||
11148 isPSHUFHWMask(M, VT) ||
11149 isPSHUFLWMask(M, VT) ||
11150 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11151 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11152 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11153 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11154 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11158 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11160 unsigned NumElts = VT.getVectorNumElements();
11161 // FIXME: This collection of masks seems suspect.
11164 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11165 return (isMOVLMask(Mask, VT) ||
11166 isCommutedMOVLMask(Mask, VT, true) ||
11167 isSHUFPMask(Mask, VT) ||
11168 isSHUFPMask(Mask, VT, /* Commuted */ true));
11173 //===----------------------------------------------------------------------===//
11174 // X86 Scheduler Hooks
11175 //===----------------------------------------------------------------------===//
11177 // private utility function
11178 MachineBasicBlock *
11179 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11180 MachineBasicBlock *MBB,
11187 TargetRegisterClass *RC,
11188 bool invSrc) const {
11189 // For the atomic bitwise operator, we generate
11192 // ld t1 = [bitinstr.addr]
11193 // op t2 = t1, [bitinstr.val]
11195 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11197 // fallthrough -->nextMBB
11198 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11199 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11200 MachineFunction::iterator MBBIter = MBB;
11203 /// First build the CFG
11204 MachineFunction *F = MBB->getParent();
11205 MachineBasicBlock *thisMBB = MBB;
11206 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11207 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11208 F->insert(MBBIter, newMBB);
11209 F->insert(MBBIter, nextMBB);
11211 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11212 nextMBB->splice(nextMBB->begin(), thisMBB,
11213 llvm::next(MachineBasicBlock::iterator(bInstr)),
11215 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11217 // Update thisMBB to fall through to newMBB
11218 thisMBB->addSuccessor(newMBB);
11220 // newMBB jumps to itself and fall through to nextMBB
11221 newMBB->addSuccessor(nextMBB);
11222 newMBB->addSuccessor(newMBB);
11224 // Insert instructions into newMBB based on incoming instruction
11225 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11226 "unexpected number of operands");
11227 DebugLoc dl = bInstr->getDebugLoc();
11228 MachineOperand& destOper = bInstr->getOperand(0);
11229 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11230 int numArgs = bInstr->getNumOperands() - 1;
11231 for (int i=0; i < numArgs; ++i)
11232 argOpers[i] = &bInstr->getOperand(i+1);
11234 // x86 address has 4 operands: base, index, scale, and displacement
11235 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11236 int valArgIndx = lastAddrIndx + 1;
11238 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11239 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11240 for (int i=0; i <= lastAddrIndx; ++i)
11241 (*MIB).addOperand(*argOpers[i]);
11243 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11245 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11250 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11251 assert((argOpers[valArgIndx]->isReg() ||
11252 argOpers[valArgIndx]->isImm()) &&
11253 "invalid operand");
11254 if (argOpers[valArgIndx]->isReg())
11255 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11257 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11259 (*MIB).addOperand(*argOpers[valArgIndx]);
11261 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11264 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11265 for (int i=0; i <= lastAddrIndx; ++i)
11266 (*MIB).addOperand(*argOpers[i]);
11268 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11269 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11270 bInstr->memoperands_end());
11272 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11273 MIB.addReg(EAXreg);
11276 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11278 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11282 // private utility function: 64 bit atomics on 32 bit host.
11283 MachineBasicBlock *
11284 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11285 MachineBasicBlock *MBB,
11290 bool invSrc) const {
11291 // For the atomic bitwise operator, we generate
11292 // thisMBB (instructions are in pairs, except cmpxchg8b)
11293 // ld t1,t2 = [bitinstr.addr]
11295 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11296 // op t5, t6 <- out1, out2, [bitinstr.val]
11297 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11298 // mov ECX, EBX <- t5, t6
11299 // mov EAX, EDX <- t1, t2
11300 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11301 // mov t3, t4 <- EAX, EDX
11303 // result in out1, out2
11304 // fallthrough -->nextMBB
11306 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11307 const unsigned LoadOpc = X86::MOV32rm;
11308 const unsigned NotOpc = X86::NOT32r;
11309 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11310 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11311 MachineFunction::iterator MBBIter = MBB;
11314 /// First build the CFG
11315 MachineFunction *F = MBB->getParent();
11316 MachineBasicBlock *thisMBB = MBB;
11317 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11318 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11319 F->insert(MBBIter, newMBB);
11320 F->insert(MBBIter, nextMBB);
11322 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11323 nextMBB->splice(nextMBB->begin(), thisMBB,
11324 llvm::next(MachineBasicBlock::iterator(bInstr)),
11326 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11328 // Update thisMBB to fall through to newMBB
11329 thisMBB->addSuccessor(newMBB);
11331 // newMBB jumps to itself and fall through to nextMBB
11332 newMBB->addSuccessor(nextMBB);
11333 newMBB->addSuccessor(newMBB);
11335 DebugLoc dl = bInstr->getDebugLoc();
11336 // Insert instructions into newMBB based on incoming instruction
11337 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11338 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11339 "unexpected number of operands");
11340 MachineOperand& dest1Oper = bInstr->getOperand(0);
11341 MachineOperand& dest2Oper = bInstr->getOperand(1);
11342 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11343 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11344 argOpers[i] = &bInstr->getOperand(i+2);
11346 // We use some of the operands multiple times, so conservatively just
11347 // clear any kill flags that might be present.
11348 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11349 argOpers[i]->setIsKill(false);
11352 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11353 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11355 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11356 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11357 for (int i=0; i <= lastAddrIndx; ++i)
11358 (*MIB).addOperand(*argOpers[i]);
11359 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11360 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11361 // add 4 to displacement.
11362 for (int i=0; i <= lastAddrIndx-2; ++i)
11363 (*MIB).addOperand(*argOpers[i]);
11364 MachineOperand newOp3 = *(argOpers[3]);
11365 if (newOp3.isImm())
11366 newOp3.setImm(newOp3.getImm()+4);
11368 newOp3.setOffset(newOp3.getOffset()+4);
11369 (*MIB).addOperand(newOp3);
11370 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11372 // t3/4 are defined later, at the bottom of the loop
11373 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11374 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11375 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11376 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11377 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11378 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11380 // The subsequent operations should be using the destination registers of
11381 //the PHI instructions.
11383 t1 = F->getRegInfo().createVirtualRegister(RC);
11384 t2 = F->getRegInfo().createVirtualRegister(RC);
11385 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11386 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11388 t1 = dest1Oper.getReg();
11389 t2 = dest2Oper.getReg();
11392 int valArgIndx = lastAddrIndx + 1;
11393 assert((argOpers[valArgIndx]->isReg() ||
11394 argOpers[valArgIndx]->isImm()) &&
11395 "invalid operand");
11396 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11397 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11398 if (argOpers[valArgIndx]->isReg())
11399 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11401 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11402 if (regOpcL != X86::MOV32rr)
11404 (*MIB).addOperand(*argOpers[valArgIndx]);
11405 assert(argOpers[valArgIndx + 1]->isReg() ==
11406 argOpers[valArgIndx]->isReg());
11407 assert(argOpers[valArgIndx + 1]->isImm() ==
11408 argOpers[valArgIndx]->isImm());
11409 if (argOpers[valArgIndx + 1]->isReg())
11410 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11412 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11413 if (regOpcH != X86::MOV32rr)
11415 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11417 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11419 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11422 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11424 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11427 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11428 for (int i=0; i <= lastAddrIndx; ++i)
11429 (*MIB).addOperand(*argOpers[i]);
11431 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11432 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11433 bInstr->memoperands_end());
11435 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11436 MIB.addReg(X86::EAX);
11437 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11438 MIB.addReg(X86::EDX);
11441 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11443 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11447 // private utility function
11448 MachineBasicBlock *
11449 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11450 MachineBasicBlock *MBB,
11451 unsigned cmovOpc) const {
11452 // For the atomic min/max operator, we generate
11455 // ld t1 = [min/max.addr]
11456 // mov t2 = [min/max.val]
11458 // cmov[cond] t2 = t1
11460 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11462 // fallthrough -->nextMBB
11464 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11465 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11466 MachineFunction::iterator MBBIter = MBB;
11469 /// First build the CFG
11470 MachineFunction *F = MBB->getParent();
11471 MachineBasicBlock *thisMBB = MBB;
11472 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11473 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11474 F->insert(MBBIter, newMBB);
11475 F->insert(MBBIter, nextMBB);
11477 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11478 nextMBB->splice(nextMBB->begin(), thisMBB,
11479 llvm::next(MachineBasicBlock::iterator(mInstr)),
11481 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11483 // Update thisMBB to fall through to newMBB
11484 thisMBB->addSuccessor(newMBB);
11486 // newMBB jumps to newMBB and fall through to nextMBB
11487 newMBB->addSuccessor(nextMBB);
11488 newMBB->addSuccessor(newMBB);
11490 DebugLoc dl = mInstr->getDebugLoc();
11491 // Insert instructions into newMBB based on incoming instruction
11492 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11493 "unexpected number of operands");
11494 MachineOperand& destOper = mInstr->getOperand(0);
11495 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11496 int numArgs = mInstr->getNumOperands() - 1;
11497 for (int i=0; i < numArgs; ++i)
11498 argOpers[i] = &mInstr->getOperand(i+1);
11500 // x86 address has 4 operands: base, index, scale, and displacement
11501 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11502 int valArgIndx = lastAddrIndx + 1;
11504 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11505 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11506 for (int i=0; i <= lastAddrIndx; ++i)
11507 (*MIB).addOperand(*argOpers[i]);
11509 // We only support register and immediate values
11510 assert((argOpers[valArgIndx]->isReg() ||
11511 argOpers[valArgIndx]->isImm()) &&
11512 "invalid operand");
11514 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11515 if (argOpers[valArgIndx]->isReg())
11516 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11518 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11519 (*MIB).addOperand(*argOpers[valArgIndx]);
11521 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11524 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11529 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11530 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11534 // Cmp and exchange if none has modified the memory location
11535 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11536 for (int i=0; i <= lastAddrIndx; ++i)
11537 (*MIB).addOperand(*argOpers[i]);
11539 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11540 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11541 mInstr->memoperands_end());
11543 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11544 MIB.addReg(X86::EAX);
11547 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11549 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11553 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11554 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11555 // in the .td file.
11556 MachineBasicBlock *
11557 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11558 unsigned numArgs, bool memArg) const {
11559 assert(Subtarget->hasSSE42orAVX() &&
11560 "Target must have SSE4.2 or AVX features enabled");
11562 DebugLoc dl = MI->getDebugLoc();
11563 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11565 if (!Subtarget->hasAVX()) {
11567 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11569 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11572 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11574 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11577 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11578 for (unsigned i = 0; i < numArgs; ++i) {
11579 MachineOperand &Op = MI->getOperand(i+1);
11580 if (!(Op.isReg() && Op.isImplicit()))
11581 MIB.addOperand(Op);
11583 BuildMI(*BB, MI, dl,
11584 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11585 MI->getOperand(0).getReg())
11586 .addReg(X86::XMM0);
11588 MI->eraseFromParent();
11592 MachineBasicBlock *
11593 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11594 DebugLoc dl = MI->getDebugLoc();
11595 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11597 // Address into RAX/EAX, other two args into ECX, EDX.
11598 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11599 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11600 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11601 for (int i = 0; i < X86::AddrNumOperands; ++i)
11602 MIB.addOperand(MI->getOperand(i));
11604 unsigned ValOps = X86::AddrNumOperands;
11605 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11606 .addReg(MI->getOperand(ValOps).getReg());
11607 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11608 .addReg(MI->getOperand(ValOps+1).getReg());
11610 // The instruction doesn't actually take any operands though.
11611 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11613 MI->eraseFromParent(); // The pseudo is gone now.
11617 MachineBasicBlock *
11618 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11619 DebugLoc dl = MI->getDebugLoc();
11620 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11622 // First arg in ECX, the second in EAX.
11623 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11624 .addReg(MI->getOperand(0).getReg());
11625 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11626 .addReg(MI->getOperand(1).getReg());
11628 // The instruction doesn't actually take any operands though.
11629 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11631 MI->eraseFromParent(); // The pseudo is gone now.
11635 MachineBasicBlock *
11636 X86TargetLowering::EmitVAARG64WithCustomInserter(
11638 MachineBasicBlock *MBB) const {
11639 // Emit va_arg instruction on X86-64.
11641 // Operands to this pseudo-instruction:
11642 // 0 ) Output : destination address (reg)
11643 // 1-5) Input : va_list address (addr, i64mem)
11644 // 6 ) ArgSize : Size (in bytes) of vararg type
11645 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11646 // 8 ) Align : Alignment of type
11647 // 9 ) EFLAGS (implicit-def)
11649 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11650 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11652 unsigned DestReg = MI->getOperand(0).getReg();
11653 MachineOperand &Base = MI->getOperand(1);
11654 MachineOperand &Scale = MI->getOperand(2);
11655 MachineOperand &Index = MI->getOperand(3);
11656 MachineOperand &Disp = MI->getOperand(4);
11657 MachineOperand &Segment = MI->getOperand(5);
11658 unsigned ArgSize = MI->getOperand(6).getImm();
11659 unsigned ArgMode = MI->getOperand(7).getImm();
11660 unsigned Align = MI->getOperand(8).getImm();
11662 // Memory Reference
11663 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11664 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11665 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11667 // Machine Information
11668 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11669 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11670 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11671 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11672 DebugLoc DL = MI->getDebugLoc();
11674 // struct va_list {
11677 // i64 overflow_area (address)
11678 // i64 reg_save_area (address)
11680 // sizeof(va_list) = 24
11681 // alignment(va_list) = 8
11683 unsigned TotalNumIntRegs = 6;
11684 unsigned TotalNumXMMRegs = 8;
11685 bool UseGPOffset = (ArgMode == 1);
11686 bool UseFPOffset = (ArgMode == 2);
11687 unsigned MaxOffset = TotalNumIntRegs * 8 +
11688 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11690 /* Align ArgSize to a multiple of 8 */
11691 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11692 bool NeedsAlign = (Align > 8);
11694 MachineBasicBlock *thisMBB = MBB;
11695 MachineBasicBlock *overflowMBB;
11696 MachineBasicBlock *offsetMBB;
11697 MachineBasicBlock *endMBB;
11699 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11700 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11701 unsigned OffsetReg = 0;
11703 if (!UseGPOffset && !UseFPOffset) {
11704 // If we only pull from the overflow region, we don't create a branch.
11705 // We don't need to alter control flow.
11706 OffsetDestReg = 0; // unused
11707 OverflowDestReg = DestReg;
11710 overflowMBB = thisMBB;
11713 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11714 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11715 // If not, pull from overflow_area. (branch to overflowMBB)
11720 // offsetMBB overflowMBB
11725 // Registers for the PHI in endMBB
11726 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11727 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11729 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11730 MachineFunction *MF = MBB->getParent();
11731 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11732 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11733 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11735 MachineFunction::iterator MBBIter = MBB;
11738 // Insert the new basic blocks
11739 MF->insert(MBBIter, offsetMBB);
11740 MF->insert(MBBIter, overflowMBB);
11741 MF->insert(MBBIter, endMBB);
11743 // Transfer the remainder of MBB and its successor edges to endMBB.
11744 endMBB->splice(endMBB->begin(), thisMBB,
11745 llvm::next(MachineBasicBlock::iterator(MI)),
11747 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11749 // Make offsetMBB and overflowMBB successors of thisMBB
11750 thisMBB->addSuccessor(offsetMBB);
11751 thisMBB->addSuccessor(overflowMBB);
11753 // endMBB is a successor of both offsetMBB and overflowMBB
11754 offsetMBB->addSuccessor(endMBB);
11755 overflowMBB->addSuccessor(endMBB);
11757 // Load the offset value into a register
11758 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11759 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11763 .addDisp(Disp, UseFPOffset ? 4 : 0)
11764 .addOperand(Segment)
11765 .setMemRefs(MMOBegin, MMOEnd);
11767 // Check if there is enough room left to pull this argument.
11768 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11770 .addImm(MaxOffset + 8 - ArgSizeA8);
11772 // Branch to "overflowMBB" if offset >= max
11773 // Fall through to "offsetMBB" otherwise
11774 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11775 .addMBB(overflowMBB);
11778 // In offsetMBB, emit code to use the reg_save_area.
11780 assert(OffsetReg != 0);
11782 // Read the reg_save_area address.
11783 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11784 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11789 .addOperand(Segment)
11790 .setMemRefs(MMOBegin, MMOEnd);
11792 // Zero-extend the offset
11793 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11794 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11797 .addImm(X86::sub_32bit);
11799 // Add the offset to the reg_save_area to get the final address.
11800 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11801 .addReg(OffsetReg64)
11802 .addReg(RegSaveReg);
11804 // Compute the offset for the next argument
11805 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11806 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11808 .addImm(UseFPOffset ? 16 : 8);
11810 // Store it back into the va_list.
11811 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11815 .addDisp(Disp, UseFPOffset ? 4 : 0)
11816 .addOperand(Segment)
11817 .addReg(NextOffsetReg)
11818 .setMemRefs(MMOBegin, MMOEnd);
11821 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11826 // Emit code to use overflow area
11829 // Load the overflow_area address into a register.
11830 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11831 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11836 .addOperand(Segment)
11837 .setMemRefs(MMOBegin, MMOEnd);
11839 // If we need to align it, do so. Otherwise, just copy the address
11840 // to OverflowDestReg.
11842 // Align the overflow address
11843 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11844 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11846 // aligned_addr = (addr + (align-1)) & ~(align-1)
11847 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11848 .addReg(OverflowAddrReg)
11851 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11853 .addImm(~(uint64_t)(Align-1));
11855 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11856 .addReg(OverflowAddrReg);
11859 // Compute the next overflow address after this argument.
11860 // (the overflow address should be kept 8-byte aligned)
11861 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11862 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11863 .addReg(OverflowDestReg)
11864 .addImm(ArgSizeA8);
11866 // Store the new overflow address.
11867 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11872 .addOperand(Segment)
11873 .addReg(NextAddrReg)
11874 .setMemRefs(MMOBegin, MMOEnd);
11876 // If we branched, emit the PHI to the front of endMBB.
11878 BuildMI(*endMBB, endMBB->begin(), DL,
11879 TII->get(X86::PHI), DestReg)
11880 .addReg(OffsetDestReg).addMBB(offsetMBB)
11881 .addReg(OverflowDestReg).addMBB(overflowMBB);
11884 // Erase the pseudo instruction
11885 MI->eraseFromParent();
11890 MachineBasicBlock *
11891 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11893 MachineBasicBlock *MBB) const {
11894 // Emit code to save XMM registers to the stack. The ABI says that the
11895 // number of registers to save is given in %al, so it's theoretically
11896 // possible to do an indirect jump trick to avoid saving all of them,
11897 // however this code takes a simpler approach and just executes all
11898 // of the stores if %al is non-zero. It's less code, and it's probably
11899 // easier on the hardware branch predictor, and stores aren't all that
11900 // expensive anyway.
11902 // Create the new basic blocks. One block contains all the XMM stores,
11903 // and one block is the final destination regardless of whether any
11904 // stores were performed.
11905 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11906 MachineFunction *F = MBB->getParent();
11907 MachineFunction::iterator MBBIter = MBB;
11909 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11910 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11911 F->insert(MBBIter, XMMSaveMBB);
11912 F->insert(MBBIter, EndMBB);
11914 // Transfer the remainder of MBB and its successor edges to EndMBB.
11915 EndMBB->splice(EndMBB->begin(), MBB,
11916 llvm::next(MachineBasicBlock::iterator(MI)),
11918 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11920 // The original block will now fall through to the XMM save block.
11921 MBB->addSuccessor(XMMSaveMBB);
11922 // The XMMSaveMBB will fall through to the end block.
11923 XMMSaveMBB->addSuccessor(EndMBB);
11925 // Now add the instructions.
11926 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11927 DebugLoc DL = MI->getDebugLoc();
11929 unsigned CountReg = MI->getOperand(0).getReg();
11930 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11931 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11933 if (!Subtarget->isTargetWin64()) {
11934 // If %al is 0, branch around the XMM save block.
11935 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11936 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11937 MBB->addSuccessor(EndMBB);
11940 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11941 // In the XMM save block, save all the XMM argument registers.
11942 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11943 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11944 MachineMemOperand *MMO =
11945 F->getMachineMemOperand(
11946 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11947 MachineMemOperand::MOStore,
11948 /*Size=*/16, /*Align=*/16);
11949 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11950 .addFrameIndex(RegSaveFrameIndex)
11951 .addImm(/*Scale=*/1)
11952 .addReg(/*IndexReg=*/0)
11953 .addImm(/*Disp=*/Offset)
11954 .addReg(/*Segment=*/0)
11955 .addReg(MI->getOperand(i).getReg())
11956 .addMemOperand(MMO);
11959 MI->eraseFromParent(); // The pseudo instruction is gone now.
11964 MachineBasicBlock *
11965 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11966 MachineBasicBlock *BB) const {
11967 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11968 DebugLoc DL = MI->getDebugLoc();
11970 // To "insert" a SELECT_CC instruction, we actually have to insert the
11971 // diamond control-flow pattern. The incoming instruction knows the
11972 // destination vreg to set, the condition code register to branch on, the
11973 // true/false values to select between, and a branch opcode to use.
11974 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11975 MachineFunction::iterator It = BB;
11981 // cmpTY ccX, r1, r2
11983 // fallthrough --> copy0MBB
11984 MachineBasicBlock *thisMBB = BB;
11985 MachineFunction *F = BB->getParent();
11986 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11987 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11988 F->insert(It, copy0MBB);
11989 F->insert(It, sinkMBB);
11991 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11992 // live into the sink and copy blocks.
11993 if (!MI->killsRegister(X86::EFLAGS)) {
11994 copy0MBB->addLiveIn(X86::EFLAGS);
11995 sinkMBB->addLiveIn(X86::EFLAGS);
11998 // Transfer the remainder of BB and its successor edges to sinkMBB.
11999 sinkMBB->splice(sinkMBB->begin(), BB,
12000 llvm::next(MachineBasicBlock::iterator(MI)),
12002 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12004 // Add the true and fallthrough blocks as its successors.
12005 BB->addSuccessor(copy0MBB);
12006 BB->addSuccessor(sinkMBB);
12008 // Create the conditional branch instruction.
12010 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12011 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12014 // %FalseValue = ...
12015 // # fallthrough to sinkMBB
12016 copy0MBB->addSuccessor(sinkMBB);
12019 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12021 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12022 TII->get(X86::PHI), MI->getOperand(0).getReg())
12023 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12024 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12026 MI->eraseFromParent(); // The pseudo instruction is gone now.
12030 MachineBasicBlock *
12031 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12032 bool Is64Bit) const {
12033 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12034 DebugLoc DL = MI->getDebugLoc();
12035 MachineFunction *MF = BB->getParent();
12036 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12038 assert(getTargetMachine().Options.EnableSegmentedStacks);
12040 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12041 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12044 // ... [Till the alloca]
12045 // If stacklet is not large enough, jump to mallocMBB
12048 // Allocate by subtracting from RSP
12049 // Jump to continueMBB
12052 // Allocate by call to runtime
12056 // [rest of original BB]
12059 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12060 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12061 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12063 MachineRegisterInfo &MRI = MF->getRegInfo();
12064 const TargetRegisterClass *AddrRegClass =
12065 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12067 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12068 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12069 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12070 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12071 sizeVReg = MI->getOperand(1).getReg(),
12072 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12074 MachineFunction::iterator MBBIter = BB;
12077 MF->insert(MBBIter, bumpMBB);
12078 MF->insert(MBBIter, mallocMBB);
12079 MF->insert(MBBIter, continueMBB);
12081 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12082 (MachineBasicBlock::iterator(MI)), BB->end());
12083 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12085 // Add code to the main basic block to check if the stack limit has been hit,
12086 // and if so, jump to mallocMBB otherwise to bumpMBB.
12087 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12088 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12089 .addReg(tmpSPVReg).addReg(sizeVReg);
12090 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12091 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12092 .addReg(SPLimitVReg);
12093 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12095 // bumpMBB simply decreases the stack pointer, since we know the current
12096 // stacklet has enough space.
12097 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12098 .addReg(SPLimitVReg);
12099 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12100 .addReg(SPLimitVReg);
12101 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12103 // Calls into a routine in libgcc to allocate more space from the heap.
12105 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12107 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12108 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12110 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12112 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12113 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12114 .addExternalSymbol("__morestack_allocate_stack_space");
12118 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12121 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12122 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12123 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12125 // Set up the CFG correctly.
12126 BB->addSuccessor(bumpMBB);
12127 BB->addSuccessor(mallocMBB);
12128 mallocMBB->addSuccessor(continueMBB);
12129 bumpMBB->addSuccessor(continueMBB);
12131 // Take care of the PHI nodes.
12132 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12133 MI->getOperand(0).getReg())
12134 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12135 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12137 // Delete the original pseudo instruction.
12138 MI->eraseFromParent();
12141 return continueMBB;
12144 MachineBasicBlock *
12145 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12146 MachineBasicBlock *BB) const {
12147 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12148 DebugLoc DL = MI->getDebugLoc();
12150 assert(!Subtarget->isTargetEnvMacho());
12152 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12153 // non-trivial part is impdef of ESP.
12155 if (Subtarget->isTargetWin64()) {
12156 if (Subtarget->isTargetCygMing()) {
12157 // ___chkstk(Mingw64):
12158 // Clobbers R10, R11, RAX and EFLAGS.
12160 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12161 .addExternalSymbol("___chkstk")
12162 .addReg(X86::RAX, RegState::Implicit)
12163 .addReg(X86::RSP, RegState::Implicit)
12164 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12165 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12166 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12168 // __chkstk(MSVCRT): does not update stack pointer.
12169 // Clobbers R10, R11 and EFLAGS.
12170 // FIXME: RAX(allocated size) might be reused and not killed.
12171 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12172 .addExternalSymbol("__chkstk")
12173 .addReg(X86::RAX, RegState::Implicit)
12174 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12175 // RAX has the offset to subtracted from RSP.
12176 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12181 const char *StackProbeSymbol =
12182 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12184 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12185 .addExternalSymbol(StackProbeSymbol)
12186 .addReg(X86::EAX, RegState::Implicit)
12187 .addReg(X86::ESP, RegState::Implicit)
12188 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12189 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12190 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12193 MI->eraseFromParent(); // The pseudo instruction is gone now.
12197 MachineBasicBlock *
12198 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12199 MachineBasicBlock *BB) const {
12200 // This is pretty easy. We're taking the value that we received from
12201 // our load from the relocation, sticking it in either RDI (x86-64)
12202 // or EAX and doing an indirect call. The return value will then
12203 // be in the normal return register.
12204 const X86InstrInfo *TII
12205 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12206 DebugLoc DL = MI->getDebugLoc();
12207 MachineFunction *F = BB->getParent();
12209 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12210 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12212 if (Subtarget->is64Bit()) {
12213 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12214 TII->get(X86::MOV64rm), X86::RDI)
12216 .addImm(0).addReg(0)
12217 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12218 MI->getOperand(3).getTargetFlags())
12220 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12221 addDirectMem(MIB, X86::RDI);
12222 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12223 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12224 TII->get(X86::MOV32rm), X86::EAX)
12226 .addImm(0).addReg(0)
12227 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12228 MI->getOperand(3).getTargetFlags())
12230 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12231 addDirectMem(MIB, X86::EAX);
12233 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12234 TII->get(X86::MOV32rm), X86::EAX)
12235 .addReg(TII->getGlobalBaseReg(F))
12236 .addImm(0).addReg(0)
12237 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12238 MI->getOperand(3).getTargetFlags())
12240 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12241 addDirectMem(MIB, X86::EAX);
12244 MI->eraseFromParent(); // The pseudo instruction is gone now.
12248 MachineBasicBlock *
12249 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12250 MachineBasicBlock *BB) const {
12251 switch (MI->getOpcode()) {
12252 default: assert(0 && "Unexpected instr type to insert");
12253 case X86::TAILJMPd64:
12254 case X86::TAILJMPr64:
12255 case X86::TAILJMPm64:
12256 assert(0 && "TAILJMP64 would not be touched here.");
12257 case X86::TCRETURNdi64:
12258 case X86::TCRETURNri64:
12259 case X86::TCRETURNmi64:
12260 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12261 // On AMD64, additional defs should be added before register allocation.
12262 if (!Subtarget->isTargetWin64()) {
12263 MI->addRegisterDefined(X86::RSI);
12264 MI->addRegisterDefined(X86::RDI);
12265 MI->addRegisterDefined(X86::XMM6);
12266 MI->addRegisterDefined(X86::XMM7);
12267 MI->addRegisterDefined(X86::XMM8);
12268 MI->addRegisterDefined(X86::XMM9);
12269 MI->addRegisterDefined(X86::XMM10);
12270 MI->addRegisterDefined(X86::XMM11);
12271 MI->addRegisterDefined(X86::XMM12);
12272 MI->addRegisterDefined(X86::XMM13);
12273 MI->addRegisterDefined(X86::XMM14);
12274 MI->addRegisterDefined(X86::XMM15);
12277 case X86::WIN_ALLOCA:
12278 return EmitLoweredWinAlloca(MI, BB);
12279 case X86::SEG_ALLOCA_32:
12280 return EmitLoweredSegAlloca(MI, BB, false);
12281 case X86::SEG_ALLOCA_64:
12282 return EmitLoweredSegAlloca(MI, BB, true);
12283 case X86::TLSCall_32:
12284 case X86::TLSCall_64:
12285 return EmitLoweredTLSCall(MI, BB);
12286 case X86::CMOV_GR8:
12287 case X86::CMOV_FR32:
12288 case X86::CMOV_FR64:
12289 case X86::CMOV_V4F32:
12290 case X86::CMOV_V2F64:
12291 case X86::CMOV_V2I64:
12292 case X86::CMOV_V8F32:
12293 case X86::CMOV_V4F64:
12294 case X86::CMOV_V4I64:
12295 case X86::CMOV_GR16:
12296 case X86::CMOV_GR32:
12297 case X86::CMOV_RFP32:
12298 case X86::CMOV_RFP64:
12299 case X86::CMOV_RFP80:
12300 return EmitLoweredSelect(MI, BB);
12302 case X86::FP32_TO_INT16_IN_MEM:
12303 case X86::FP32_TO_INT32_IN_MEM:
12304 case X86::FP32_TO_INT64_IN_MEM:
12305 case X86::FP64_TO_INT16_IN_MEM:
12306 case X86::FP64_TO_INT32_IN_MEM:
12307 case X86::FP64_TO_INT64_IN_MEM:
12308 case X86::FP80_TO_INT16_IN_MEM:
12309 case X86::FP80_TO_INT32_IN_MEM:
12310 case X86::FP80_TO_INT64_IN_MEM: {
12311 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12312 DebugLoc DL = MI->getDebugLoc();
12314 // Change the floating point control register to use "round towards zero"
12315 // mode when truncating to an integer value.
12316 MachineFunction *F = BB->getParent();
12317 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12318 addFrameReference(BuildMI(*BB, MI, DL,
12319 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12321 // Load the old value of the high byte of the control word...
12323 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12324 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12327 // Set the high part to be round to zero...
12328 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12331 // Reload the modified control word now...
12332 addFrameReference(BuildMI(*BB, MI, DL,
12333 TII->get(X86::FLDCW16m)), CWFrameIdx);
12335 // Restore the memory image of control word to original value
12336 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12339 // Get the X86 opcode to use.
12341 switch (MI->getOpcode()) {
12342 default: llvm_unreachable("illegal opcode!");
12343 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12344 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12345 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12346 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12347 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12348 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12349 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12350 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12351 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12355 MachineOperand &Op = MI->getOperand(0);
12357 AM.BaseType = X86AddressMode::RegBase;
12358 AM.Base.Reg = Op.getReg();
12360 AM.BaseType = X86AddressMode::FrameIndexBase;
12361 AM.Base.FrameIndex = Op.getIndex();
12363 Op = MI->getOperand(1);
12365 AM.Scale = Op.getImm();
12366 Op = MI->getOperand(2);
12368 AM.IndexReg = Op.getImm();
12369 Op = MI->getOperand(3);
12370 if (Op.isGlobal()) {
12371 AM.GV = Op.getGlobal();
12373 AM.Disp = Op.getImm();
12375 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12376 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12378 // Reload the original control word now.
12379 addFrameReference(BuildMI(*BB, MI, DL,
12380 TII->get(X86::FLDCW16m)), CWFrameIdx);
12382 MI->eraseFromParent(); // The pseudo instruction is gone now.
12385 // String/text processing lowering.
12386 case X86::PCMPISTRM128REG:
12387 case X86::VPCMPISTRM128REG:
12388 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12389 case X86::PCMPISTRM128MEM:
12390 case X86::VPCMPISTRM128MEM:
12391 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12392 case X86::PCMPESTRM128REG:
12393 case X86::VPCMPESTRM128REG:
12394 return EmitPCMP(MI, BB, 5, false /* in mem */);
12395 case X86::PCMPESTRM128MEM:
12396 case X86::VPCMPESTRM128MEM:
12397 return EmitPCMP(MI, BB, 5, true /* in mem */);
12399 // Thread synchronization.
12401 return EmitMonitor(MI, BB);
12403 return EmitMwait(MI, BB);
12405 // Atomic Lowering.
12406 case X86::ATOMAND32:
12407 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12408 X86::AND32ri, X86::MOV32rm,
12410 X86::NOT32r, X86::EAX,
12411 X86::GR32RegisterClass);
12412 case X86::ATOMOR32:
12413 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12414 X86::OR32ri, X86::MOV32rm,
12416 X86::NOT32r, X86::EAX,
12417 X86::GR32RegisterClass);
12418 case X86::ATOMXOR32:
12419 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12420 X86::XOR32ri, X86::MOV32rm,
12422 X86::NOT32r, X86::EAX,
12423 X86::GR32RegisterClass);
12424 case X86::ATOMNAND32:
12425 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12426 X86::AND32ri, X86::MOV32rm,
12428 X86::NOT32r, X86::EAX,
12429 X86::GR32RegisterClass, true);
12430 case X86::ATOMMIN32:
12431 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12432 case X86::ATOMMAX32:
12433 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12434 case X86::ATOMUMIN32:
12435 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12436 case X86::ATOMUMAX32:
12437 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12439 case X86::ATOMAND16:
12440 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12441 X86::AND16ri, X86::MOV16rm,
12443 X86::NOT16r, X86::AX,
12444 X86::GR16RegisterClass);
12445 case X86::ATOMOR16:
12446 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12447 X86::OR16ri, X86::MOV16rm,
12449 X86::NOT16r, X86::AX,
12450 X86::GR16RegisterClass);
12451 case X86::ATOMXOR16:
12452 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12453 X86::XOR16ri, X86::MOV16rm,
12455 X86::NOT16r, X86::AX,
12456 X86::GR16RegisterClass);
12457 case X86::ATOMNAND16:
12458 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12459 X86::AND16ri, X86::MOV16rm,
12461 X86::NOT16r, X86::AX,
12462 X86::GR16RegisterClass, true);
12463 case X86::ATOMMIN16:
12464 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12465 case X86::ATOMMAX16:
12466 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12467 case X86::ATOMUMIN16:
12468 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12469 case X86::ATOMUMAX16:
12470 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12472 case X86::ATOMAND8:
12473 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12474 X86::AND8ri, X86::MOV8rm,
12476 X86::NOT8r, X86::AL,
12477 X86::GR8RegisterClass);
12479 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12480 X86::OR8ri, X86::MOV8rm,
12482 X86::NOT8r, X86::AL,
12483 X86::GR8RegisterClass);
12484 case X86::ATOMXOR8:
12485 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12486 X86::XOR8ri, X86::MOV8rm,
12488 X86::NOT8r, X86::AL,
12489 X86::GR8RegisterClass);
12490 case X86::ATOMNAND8:
12491 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12492 X86::AND8ri, X86::MOV8rm,
12494 X86::NOT8r, X86::AL,
12495 X86::GR8RegisterClass, true);
12496 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12497 // This group is for 64-bit host.
12498 case X86::ATOMAND64:
12499 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12500 X86::AND64ri32, X86::MOV64rm,
12502 X86::NOT64r, X86::RAX,
12503 X86::GR64RegisterClass);
12504 case X86::ATOMOR64:
12505 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12506 X86::OR64ri32, X86::MOV64rm,
12508 X86::NOT64r, X86::RAX,
12509 X86::GR64RegisterClass);
12510 case X86::ATOMXOR64:
12511 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12512 X86::XOR64ri32, X86::MOV64rm,
12514 X86::NOT64r, X86::RAX,
12515 X86::GR64RegisterClass);
12516 case X86::ATOMNAND64:
12517 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12518 X86::AND64ri32, X86::MOV64rm,
12520 X86::NOT64r, X86::RAX,
12521 X86::GR64RegisterClass, true);
12522 case X86::ATOMMIN64:
12523 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12524 case X86::ATOMMAX64:
12525 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12526 case X86::ATOMUMIN64:
12527 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12528 case X86::ATOMUMAX64:
12529 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12531 // This group does 64-bit operations on a 32-bit host.
12532 case X86::ATOMAND6432:
12533 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12534 X86::AND32rr, X86::AND32rr,
12535 X86::AND32ri, X86::AND32ri,
12537 case X86::ATOMOR6432:
12538 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12539 X86::OR32rr, X86::OR32rr,
12540 X86::OR32ri, X86::OR32ri,
12542 case X86::ATOMXOR6432:
12543 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12544 X86::XOR32rr, X86::XOR32rr,
12545 X86::XOR32ri, X86::XOR32ri,
12547 case X86::ATOMNAND6432:
12548 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12549 X86::AND32rr, X86::AND32rr,
12550 X86::AND32ri, X86::AND32ri,
12552 case X86::ATOMADD6432:
12553 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12554 X86::ADD32rr, X86::ADC32rr,
12555 X86::ADD32ri, X86::ADC32ri,
12557 case X86::ATOMSUB6432:
12558 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12559 X86::SUB32rr, X86::SBB32rr,
12560 X86::SUB32ri, X86::SBB32ri,
12562 case X86::ATOMSWAP6432:
12563 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12564 X86::MOV32rr, X86::MOV32rr,
12565 X86::MOV32ri, X86::MOV32ri,
12567 case X86::VASTART_SAVE_XMM_REGS:
12568 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12570 case X86::VAARG_64:
12571 return EmitVAARG64WithCustomInserter(MI, BB);
12575 //===----------------------------------------------------------------------===//
12576 // X86 Optimization Hooks
12577 //===----------------------------------------------------------------------===//
12579 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12583 const SelectionDAG &DAG,
12584 unsigned Depth) const {
12585 unsigned Opc = Op.getOpcode();
12586 assert((Opc >= ISD::BUILTIN_OP_END ||
12587 Opc == ISD::INTRINSIC_WO_CHAIN ||
12588 Opc == ISD::INTRINSIC_W_CHAIN ||
12589 Opc == ISD::INTRINSIC_VOID) &&
12590 "Should use MaskedValueIsZero if you don't know whether Op"
12591 " is a target node!");
12593 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12607 // These nodes' second result is a boolean.
12608 if (Op.getResNo() == 0)
12611 case X86ISD::SETCC:
12612 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12613 Mask.getBitWidth() - 1);
12615 case ISD::INTRINSIC_WO_CHAIN: {
12616 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12617 unsigned NumLoBits = 0;
12620 case Intrinsic::x86_sse_movmsk_ps:
12621 case Intrinsic::x86_avx_movmsk_ps_256:
12622 case Intrinsic::x86_sse2_movmsk_pd:
12623 case Intrinsic::x86_avx_movmsk_pd_256:
12624 case Intrinsic::x86_mmx_pmovmskb:
12625 case Intrinsic::x86_sse2_pmovmskb_128:
12626 case Intrinsic::x86_avx2_pmovmskb: {
12627 // High bits of movmskp{s|d}, pmovmskb are known zero.
12629 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12630 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12631 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12632 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12633 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12634 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12635 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
12637 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12638 Mask.getBitWidth() - NumLoBits);
12647 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12648 unsigned Depth) const {
12649 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12650 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12651 return Op.getValueType().getScalarType().getSizeInBits();
12657 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12658 /// node is a GlobalAddress + offset.
12659 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12660 const GlobalValue* &GA,
12661 int64_t &Offset) const {
12662 if (N->getOpcode() == X86ISD::Wrapper) {
12663 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12664 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12665 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12669 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12672 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12673 /// same as extracting the high 128-bit part of 256-bit vector and then
12674 /// inserting the result into the low part of a new 256-bit vector
12675 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12676 EVT VT = SVOp->getValueType(0);
12677 int NumElems = VT.getVectorNumElements();
12679 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12680 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12681 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12682 SVOp->getMaskElt(j) >= 0)
12688 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12689 /// same as extracting the low 128-bit part of 256-bit vector and then
12690 /// inserting the result into the high part of a new 256-bit vector
12691 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12692 EVT VT = SVOp->getValueType(0);
12693 int NumElems = VT.getVectorNumElements();
12695 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12696 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12697 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12698 SVOp->getMaskElt(j) >= 0)
12704 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12705 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12706 TargetLowering::DAGCombinerInfo &DCI) {
12707 DebugLoc dl = N->getDebugLoc();
12708 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12709 SDValue V1 = SVOp->getOperand(0);
12710 SDValue V2 = SVOp->getOperand(1);
12711 EVT VT = SVOp->getValueType(0);
12712 int NumElems = VT.getVectorNumElements();
12714 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12715 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12719 // V UNDEF BUILD_VECTOR UNDEF
12721 // CONCAT_VECTOR CONCAT_VECTOR
12724 // RESULT: V + zero extended
12726 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12727 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12728 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12731 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12734 // To match the shuffle mask, the first half of the mask should
12735 // be exactly the first vector, and all the rest a splat with the
12736 // first element of the second one.
12737 for (int i = 0; i < NumElems/2; ++i)
12738 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12739 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12742 // Emit a zeroed vector and insert the desired subvector on its
12744 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12745 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12746 DAG.getConstant(0, MVT::i32), DAG, dl);
12747 return DCI.CombineTo(N, InsV);
12750 //===--------------------------------------------------------------------===//
12751 // Combine some shuffles into subvector extracts and inserts:
12754 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12755 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12756 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12758 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12759 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12760 return DCI.CombineTo(N, InsV);
12763 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12764 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12765 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12766 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12767 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12768 return DCI.CombineTo(N, InsV);
12774 /// PerformShuffleCombine - Performs several different shuffle combines.
12775 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12776 TargetLowering::DAGCombinerInfo &DCI,
12777 const X86Subtarget *Subtarget) {
12778 DebugLoc dl = N->getDebugLoc();
12779 EVT VT = N->getValueType(0);
12781 // Don't create instructions with illegal types after legalize types has run.
12782 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12783 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12786 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12787 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12788 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12789 return PerformShuffleCombine256(N, DAG, DCI);
12791 // Only handle 128 wide vector from here on.
12792 if (VT.getSizeInBits() != 128)
12795 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12796 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12797 // consecutive, non-overlapping, and in the right order.
12798 SmallVector<SDValue, 16> Elts;
12799 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12800 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12802 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12805 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12806 /// generation and convert it from being a bunch of shuffles and extracts
12807 /// to a simple store and scalar loads to extract the elements.
12808 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12809 const TargetLowering &TLI) {
12810 SDValue InputVector = N->getOperand(0);
12812 // Only operate on vectors of 4 elements, where the alternative shuffling
12813 // gets to be more expensive.
12814 if (InputVector.getValueType() != MVT::v4i32)
12817 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12818 // single use which is a sign-extend or zero-extend, and all elements are
12820 SmallVector<SDNode *, 4> Uses;
12821 unsigned ExtractedElements = 0;
12822 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12823 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12824 if (UI.getUse().getResNo() != InputVector.getResNo())
12827 SDNode *Extract = *UI;
12828 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12831 if (Extract->getValueType(0) != MVT::i32)
12833 if (!Extract->hasOneUse())
12835 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12836 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12838 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12841 // Record which element was extracted.
12842 ExtractedElements |=
12843 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12845 Uses.push_back(Extract);
12848 // If not all the elements were used, this may not be worthwhile.
12849 if (ExtractedElements != 15)
12852 // Ok, we've now decided to do the transformation.
12853 DebugLoc dl = InputVector.getDebugLoc();
12855 // Store the value to a temporary stack slot.
12856 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12857 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12858 MachinePointerInfo(), false, false, 0);
12860 // Replace each use (extract) with a load of the appropriate element.
12861 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12862 UE = Uses.end(); UI != UE; ++UI) {
12863 SDNode *Extract = *UI;
12865 // cOMpute the element's address.
12866 SDValue Idx = Extract->getOperand(1);
12868 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12869 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12870 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12872 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12873 StackPtr, OffsetVal);
12875 // Load the scalar.
12876 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12877 ScalarAddr, MachinePointerInfo(),
12878 false, false, false, 0);
12880 // Replace the exact with the load.
12881 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12884 // The replacement was made in place; don't return anything.
12888 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12890 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12891 const X86Subtarget *Subtarget) {
12892 DebugLoc DL = N->getDebugLoc();
12893 SDValue Cond = N->getOperand(0);
12894 // Get the LHS/RHS of the select.
12895 SDValue LHS = N->getOperand(1);
12896 SDValue RHS = N->getOperand(2);
12897 EVT VT = LHS.getValueType();
12899 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12900 // instructions match the semantics of the common C idiom x<y?x:y but not
12901 // x<=y?x:y, because of how they handle negative zero (which can be
12902 // ignored in unsafe-math mode).
12903 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12904 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12905 (Subtarget->hasXMMInt() ||
12906 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12907 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12909 unsigned Opcode = 0;
12910 // Check for x CC y ? x : y.
12911 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12912 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12916 // Converting this to a min would handle NaNs incorrectly, and swapping
12917 // the operands would cause it to handle comparisons between positive
12918 // and negative zero incorrectly.
12919 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12920 if (!DAG.getTarget().Options.UnsafeFPMath &&
12921 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12923 std::swap(LHS, RHS);
12925 Opcode = X86ISD::FMIN;
12928 // Converting this to a min would handle comparisons between positive
12929 // and negative zero incorrectly.
12930 if (!DAG.getTarget().Options.UnsafeFPMath &&
12931 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12933 Opcode = X86ISD::FMIN;
12936 // Converting this to a min would handle both negative zeros and NaNs
12937 // incorrectly, but we can swap the operands to fix both.
12938 std::swap(LHS, RHS);
12942 Opcode = X86ISD::FMIN;
12946 // Converting this to a max would handle comparisons between positive
12947 // and negative zero incorrectly.
12948 if (!DAG.getTarget().Options.UnsafeFPMath &&
12949 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12951 Opcode = X86ISD::FMAX;
12954 // Converting this to a max would handle NaNs incorrectly, and swapping
12955 // the operands would cause it to handle comparisons between positive
12956 // and negative zero incorrectly.
12957 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12958 if (!DAG.getTarget().Options.UnsafeFPMath &&
12959 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12961 std::swap(LHS, RHS);
12963 Opcode = X86ISD::FMAX;
12966 // Converting this to a max would handle both negative zeros and NaNs
12967 // incorrectly, but we can swap the operands to fix both.
12968 std::swap(LHS, RHS);
12972 Opcode = X86ISD::FMAX;
12975 // Check for x CC y ? y : x -- a min/max with reversed arms.
12976 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12977 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12981 // Converting this to a min would handle comparisons between positive
12982 // and negative zero incorrectly, and swapping the operands would
12983 // cause it to handle NaNs incorrectly.
12984 if (!DAG.getTarget().Options.UnsafeFPMath &&
12985 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12986 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12988 std::swap(LHS, RHS);
12990 Opcode = X86ISD::FMIN;
12993 // Converting this to a min would handle NaNs incorrectly.
12994 if (!DAG.getTarget().Options.UnsafeFPMath &&
12995 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12997 Opcode = X86ISD::FMIN;
13000 // Converting this to a min would handle both negative zeros and NaNs
13001 // incorrectly, but we can swap the operands to fix both.
13002 std::swap(LHS, RHS);
13006 Opcode = X86ISD::FMIN;
13010 // Converting this to a max would handle NaNs incorrectly.
13011 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13013 Opcode = X86ISD::FMAX;
13016 // Converting this to a max would handle comparisons between positive
13017 // and negative zero incorrectly, and swapping the operands would
13018 // cause it to handle NaNs incorrectly.
13019 if (!DAG.getTarget().Options.UnsafeFPMath &&
13020 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13021 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13023 std::swap(LHS, RHS);
13025 Opcode = X86ISD::FMAX;
13028 // Converting this to a max would handle both negative zeros and NaNs
13029 // incorrectly, but we can swap the operands to fix both.
13030 std::swap(LHS, RHS);
13034 Opcode = X86ISD::FMAX;
13040 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13043 // If this is a select between two integer constants, try to do some
13045 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13046 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13047 // Don't do this for crazy integer types.
13048 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13049 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13050 // so that TrueC (the true value) is larger than FalseC.
13051 bool NeedsCondInvert = false;
13053 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13054 // Efficiently invertible.
13055 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13056 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13057 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13058 NeedsCondInvert = true;
13059 std::swap(TrueC, FalseC);
13062 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13063 if (FalseC->getAPIntValue() == 0 &&
13064 TrueC->getAPIntValue().isPowerOf2()) {
13065 if (NeedsCondInvert) // Invert the condition if needed.
13066 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13067 DAG.getConstant(1, Cond.getValueType()));
13069 // Zero extend the condition if needed.
13070 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13072 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13073 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13074 DAG.getConstant(ShAmt, MVT::i8));
13077 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13078 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13079 if (NeedsCondInvert) // Invert the condition if needed.
13080 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13081 DAG.getConstant(1, Cond.getValueType()));
13083 // Zero extend the condition if needed.
13084 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13085 FalseC->getValueType(0), Cond);
13086 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13087 SDValue(FalseC, 0));
13090 // Optimize cases that will turn into an LEA instruction. This requires
13091 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13092 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13093 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13094 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13096 bool isFastMultiplier = false;
13098 switch ((unsigned char)Diff) {
13100 case 1: // result = add base, cond
13101 case 2: // result = lea base( , cond*2)
13102 case 3: // result = lea base(cond, cond*2)
13103 case 4: // result = lea base( , cond*4)
13104 case 5: // result = lea base(cond, cond*4)
13105 case 8: // result = lea base( , cond*8)
13106 case 9: // result = lea base(cond, cond*8)
13107 isFastMultiplier = true;
13112 if (isFastMultiplier) {
13113 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13114 if (NeedsCondInvert) // Invert the condition if needed.
13115 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13116 DAG.getConstant(1, Cond.getValueType()));
13118 // Zero extend the condition if needed.
13119 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13121 // Scale the condition by the difference.
13123 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13124 DAG.getConstant(Diff, Cond.getValueType()));
13126 // Add the base if non-zero.
13127 if (FalseC->getAPIntValue() != 0)
13128 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13129 SDValue(FalseC, 0));
13139 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13140 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13141 TargetLowering::DAGCombinerInfo &DCI) {
13142 DebugLoc DL = N->getDebugLoc();
13144 // If the flag operand isn't dead, don't touch this CMOV.
13145 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13148 SDValue FalseOp = N->getOperand(0);
13149 SDValue TrueOp = N->getOperand(1);
13150 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13151 SDValue Cond = N->getOperand(3);
13152 if (CC == X86::COND_E || CC == X86::COND_NE) {
13153 switch (Cond.getOpcode()) {
13157 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13158 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13159 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13163 // If this is a select between two integer constants, try to do some
13164 // optimizations. Note that the operands are ordered the opposite of SELECT
13166 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13167 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13168 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13169 // larger than FalseC (the false value).
13170 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13171 CC = X86::GetOppositeBranchCondition(CC);
13172 std::swap(TrueC, FalseC);
13175 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13176 // This is efficient for any integer data type (including i8/i16) and
13178 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13179 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13180 DAG.getConstant(CC, MVT::i8), Cond);
13182 // Zero extend the condition if needed.
13183 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13185 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13186 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13187 DAG.getConstant(ShAmt, MVT::i8));
13188 if (N->getNumValues() == 2) // Dead flag value?
13189 return DCI.CombineTo(N, Cond, SDValue());
13193 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13194 // for any integer data type, including i8/i16.
13195 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13196 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13197 DAG.getConstant(CC, MVT::i8), Cond);
13199 // Zero extend the condition if needed.
13200 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13201 FalseC->getValueType(0), Cond);
13202 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13203 SDValue(FalseC, 0));
13205 if (N->getNumValues() == 2) // Dead flag value?
13206 return DCI.CombineTo(N, Cond, SDValue());
13210 // Optimize cases that will turn into an LEA instruction. This requires
13211 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13212 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13213 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13214 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13216 bool isFastMultiplier = false;
13218 switch ((unsigned char)Diff) {
13220 case 1: // result = add base, cond
13221 case 2: // result = lea base( , cond*2)
13222 case 3: // result = lea base(cond, cond*2)
13223 case 4: // result = lea base( , cond*4)
13224 case 5: // result = lea base(cond, cond*4)
13225 case 8: // result = lea base( , cond*8)
13226 case 9: // result = lea base(cond, cond*8)
13227 isFastMultiplier = true;
13232 if (isFastMultiplier) {
13233 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13234 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13235 DAG.getConstant(CC, MVT::i8), Cond);
13236 // Zero extend the condition if needed.
13237 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13239 // Scale the condition by the difference.
13241 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13242 DAG.getConstant(Diff, Cond.getValueType()));
13244 // Add the base if non-zero.
13245 if (FalseC->getAPIntValue() != 0)
13246 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13247 SDValue(FalseC, 0));
13248 if (N->getNumValues() == 2) // Dead flag value?
13249 return DCI.CombineTo(N, Cond, SDValue());
13259 /// PerformMulCombine - Optimize a single multiply with constant into two
13260 /// in order to implement it with two cheaper instructions, e.g.
13261 /// LEA + SHL, LEA + LEA.
13262 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13263 TargetLowering::DAGCombinerInfo &DCI) {
13264 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13267 EVT VT = N->getValueType(0);
13268 if (VT != MVT::i64)
13271 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13274 uint64_t MulAmt = C->getZExtValue();
13275 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13278 uint64_t MulAmt1 = 0;
13279 uint64_t MulAmt2 = 0;
13280 if ((MulAmt % 9) == 0) {
13282 MulAmt2 = MulAmt / 9;
13283 } else if ((MulAmt % 5) == 0) {
13285 MulAmt2 = MulAmt / 5;
13286 } else if ((MulAmt % 3) == 0) {
13288 MulAmt2 = MulAmt / 3;
13291 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13292 DebugLoc DL = N->getDebugLoc();
13294 if (isPowerOf2_64(MulAmt2) &&
13295 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13296 // If second multiplifer is pow2, issue it first. We want the multiply by
13297 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13299 std::swap(MulAmt1, MulAmt2);
13302 if (isPowerOf2_64(MulAmt1))
13303 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13304 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13306 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13307 DAG.getConstant(MulAmt1, VT));
13309 if (isPowerOf2_64(MulAmt2))
13310 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13311 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13313 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13314 DAG.getConstant(MulAmt2, VT));
13316 // Do not add new nodes to DAG combiner worklist.
13317 DCI.CombineTo(N, NewMul, false);
13322 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13323 SDValue N0 = N->getOperand(0);
13324 SDValue N1 = N->getOperand(1);
13325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13326 EVT VT = N0.getValueType();
13328 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13329 // since the result of setcc_c is all zero's or all ones.
13330 if (VT.isInteger() && !VT.isVector() &&
13331 N1C && N0.getOpcode() == ISD::AND &&
13332 N0.getOperand(1).getOpcode() == ISD::Constant) {
13333 SDValue N00 = N0.getOperand(0);
13334 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13335 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13336 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13337 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13338 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13339 APInt ShAmt = N1C->getAPIntValue();
13340 Mask = Mask.shl(ShAmt);
13342 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13343 N00, DAG.getConstant(Mask, VT));
13348 // Hardware support for vector shifts is sparse which makes us scalarize the
13349 // vector operations in many cases. Also, on sandybridge ADD is faster than
13351 // (shl V, 1) -> add V,V
13352 if (isSplatVector(N1.getNode())) {
13353 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13355 // We shift all of the values by one. In many cases we do not have
13356 // hardware support for this operation. This is better expressed as an ADD
13358 if (N1C && (1 == N1C->getZExtValue())) {
13359 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13366 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13368 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13369 const X86Subtarget *Subtarget) {
13370 EVT VT = N->getValueType(0);
13371 if (N->getOpcode() == ISD::SHL) {
13372 SDValue V = PerformSHLCombine(N, DAG);
13373 if (V.getNode()) return V;
13376 // On X86 with SSE2 support, we can transform this to a vector shift if
13377 // all elements are shifted by the same amount. We can't do this in legalize
13378 // because the a constant vector is typically transformed to a constant pool
13379 // so we have no knowledge of the shift amount.
13380 if (!Subtarget->hasXMMInt())
13383 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13384 (!Subtarget->hasAVX2() ||
13385 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13388 SDValue ShAmtOp = N->getOperand(1);
13389 EVT EltVT = VT.getVectorElementType();
13390 DebugLoc DL = N->getDebugLoc();
13391 SDValue BaseShAmt = SDValue();
13392 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13393 unsigned NumElts = VT.getVectorNumElements();
13395 for (; i != NumElts; ++i) {
13396 SDValue Arg = ShAmtOp.getOperand(i);
13397 if (Arg.getOpcode() == ISD::UNDEF) continue;
13401 for (; i != NumElts; ++i) {
13402 SDValue Arg = ShAmtOp.getOperand(i);
13403 if (Arg.getOpcode() == ISD::UNDEF) continue;
13404 if (Arg != BaseShAmt) {
13408 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13409 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13410 SDValue InVec = ShAmtOp.getOperand(0);
13411 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13412 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13414 for (; i != NumElts; ++i) {
13415 SDValue Arg = InVec.getOperand(i);
13416 if (Arg.getOpcode() == ISD::UNDEF) continue;
13420 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13422 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13423 if (C->getZExtValue() == SplatIdx)
13424 BaseShAmt = InVec.getOperand(1);
13427 if (BaseShAmt.getNode() == 0)
13428 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13429 DAG.getIntPtrConstant(0));
13433 // The shift amount is an i32.
13434 if (EltVT.bitsGT(MVT::i32))
13435 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13436 else if (EltVT.bitsLT(MVT::i32))
13437 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13439 // The shift amount is identical so we can do a vector shift.
13440 SDValue ValOp = N->getOperand(0);
13441 switch (N->getOpcode()) {
13443 llvm_unreachable("Unknown shift opcode!");
13446 if (VT == MVT::v2i64)
13447 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13448 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13450 if (VT == MVT::v4i32)
13451 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13452 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13454 if (VT == MVT::v8i16)
13455 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13456 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13458 if (VT == MVT::v4i64)
13459 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13460 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13462 if (VT == MVT::v8i32)
13463 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13464 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13466 if (VT == MVT::v16i16)
13467 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13468 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13472 if (VT == MVT::v4i32)
13473 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13474 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13476 if (VT == MVT::v8i16)
13477 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13478 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13480 if (VT == MVT::v8i32)
13481 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13482 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13484 if (VT == MVT::v16i16)
13485 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13486 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13490 if (VT == MVT::v2i64)
13491 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13492 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13494 if (VT == MVT::v4i32)
13495 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13496 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13498 if (VT == MVT::v8i16)
13499 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13500 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13502 if (VT == MVT::v4i64)
13503 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13504 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13506 if (VT == MVT::v8i32)
13507 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13508 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13510 if (VT == MVT::v16i16)
13511 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13512 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13520 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13521 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13522 // and friends. Likewise for OR -> CMPNEQSS.
13523 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13524 TargetLowering::DAGCombinerInfo &DCI,
13525 const X86Subtarget *Subtarget) {
13528 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13529 // we're requiring SSE2 for both.
13530 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13531 SDValue N0 = N->getOperand(0);
13532 SDValue N1 = N->getOperand(1);
13533 SDValue CMP0 = N0->getOperand(1);
13534 SDValue CMP1 = N1->getOperand(1);
13535 DebugLoc DL = N->getDebugLoc();
13537 // The SETCCs should both refer to the same CMP.
13538 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13541 SDValue CMP00 = CMP0->getOperand(0);
13542 SDValue CMP01 = CMP0->getOperand(1);
13543 EVT VT = CMP00.getValueType();
13545 if (VT == MVT::f32 || VT == MVT::f64) {
13546 bool ExpectingFlags = false;
13547 // Check for any users that want flags:
13548 for (SDNode::use_iterator UI = N->use_begin(),
13550 !ExpectingFlags && UI != UE; ++UI)
13551 switch (UI->getOpcode()) {
13556 ExpectingFlags = true;
13558 case ISD::CopyToReg:
13559 case ISD::SIGN_EXTEND:
13560 case ISD::ZERO_EXTEND:
13561 case ISD::ANY_EXTEND:
13565 if (!ExpectingFlags) {
13566 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13567 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13569 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13570 X86::CondCode tmp = cc0;
13575 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13576 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13577 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13578 X86ISD::NodeType NTOperator = is64BitFP ?
13579 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13580 // FIXME: need symbolic constants for these magic numbers.
13581 // See X86ATTInstPrinter.cpp:printSSECC().
13582 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13583 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13584 DAG.getConstant(x86cc, MVT::i8));
13585 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13587 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13588 DAG.getConstant(1, MVT::i32));
13589 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13590 return OneBitOfTruth;
13598 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13599 /// so it can be folded inside ANDNP.
13600 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13601 EVT VT = N->getValueType(0);
13603 // Match direct AllOnes for 128 and 256-bit vectors
13604 if (ISD::isBuildVectorAllOnes(N))
13607 // Look through a bit convert.
13608 if (N->getOpcode() == ISD::BITCAST)
13609 N = N->getOperand(0).getNode();
13611 // Sometimes the operand may come from a insert_subvector building a 256-bit
13613 if (VT.getSizeInBits() == 256 &&
13614 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13615 SDValue V1 = N->getOperand(0);
13616 SDValue V2 = N->getOperand(1);
13618 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13619 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13620 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13621 ISD::isBuildVectorAllOnes(V2.getNode()))
13628 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13629 TargetLowering::DAGCombinerInfo &DCI,
13630 const X86Subtarget *Subtarget) {
13631 if (DCI.isBeforeLegalizeOps())
13634 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13638 EVT VT = N->getValueType(0);
13640 // Create ANDN, BLSI, and BLSR instructions
13641 // BLSI is X & (-X)
13642 // BLSR is X & (X-1)
13643 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13644 SDValue N0 = N->getOperand(0);
13645 SDValue N1 = N->getOperand(1);
13646 DebugLoc DL = N->getDebugLoc();
13648 // Check LHS for not
13649 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13650 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13651 // Check RHS for not
13652 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13653 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13655 // Check LHS for neg
13656 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13657 isZero(N0.getOperand(0)))
13658 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13660 // Check RHS for neg
13661 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13662 isZero(N1.getOperand(0)))
13663 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13665 // Check LHS for X-1
13666 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13667 isAllOnes(N0.getOperand(1)))
13668 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13670 // Check RHS for X-1
13671 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13672 isAllOnes(N1.getOperand(1)))
13673 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13678 // Want to form ANDNP nodes:
13679 // 1) In the hopes of then easily combining them with OR and AND nodes
13680 // to form PBLEND/PSIGN.
13681 // 2) To match ANDN packed intrinsics
13682 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13685 SDValue N0 = N->getOperand(0);
13686 SDValue N1 = N->getOperand(1);
13687 DebugLoc DL = N->getDebugLoc();
13689 // Check LHS for vnot
13690 if (N0.getOpcode() == ISD::XOR &&
13691 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13692 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13693 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13695 // Check RHS for vnot
13696 if (N1.getOpcode() == ISD::XOR &&
13697 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13698 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13699 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13704 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13705 TargetLowering::DAGCombinerInfo &DCI,
13706 const X86Subtarget *Subtarget) {
13707 if (DCI.isBeforeLegalizeOps())
13710 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13714 EVT VT = N->getValueType(0);
13716 SDValue N0 = N->getOperand(0);
13717 SDValue N1 = N->getOperand(1);
13719 // look for psign/blend
13720 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13721 if (!Subtarget->hasSSSE3orAVX() ||
13722 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13725 // Canonicalize pandn to RHS
13726 if (N0.getOpcode() == X86ISD::ANDNP)
13728 // or (and (m, x), (pandn m, y))
13729 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13730 SDValue Mask = N1.getOperand(0);
13731 SDValue X = N1.getOperand(1);
13733 if (N0.getOperand(0) == Mask)
13734 Y = N0.getOperand(1);
13735 if (N0.getOperand(1) == Mask)
13736 Y = N0.getOperand(0);
13738 // Check to see if the mask appeared in both the AND and ANDNP and
13742 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13743 if (Mask.getOpcode() != ISD::BITCAST ||
13744 X.getOpcode() != ISD::BITCAST ||
13745 Y.getOpcode() != ISD::BITCAST)
13748 // Look through mask bitcast.
13749 Mask = Mask.getOperand(0);
13750 EVT MaskVT = Mask.getValueType();
13752 // Validate that the Mask operand is a vector sra node. The sra node
13753 // will be an intrinsic.
13754 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13757 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13758 // there is no psrai.b
13759 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13760 case Intrinsic::x86_sse2_psrai_w:
13761 case Intrinsic::x86_sse2_psrai_d:
13762 case Intrinsic::x86_avx2_psrai_w:
13763 case Intrinsic::x86_avx2_psrai_d:
13765 default: return SDValue();
13768 // Check that the SRA is all signbits.
13769 SDValue SraC = Mask.getOperand(2);
13770 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13771 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13772 if ((SraAmt + 1) != EltBits)
13775 DebugLoc DL = N->getDebugLoc();
13777 // Now we know we at least have a plendvb with the mask val. See if
13778 // we can form a psignb/w/d.
13779 // psign = x.type == y.type == mask.type && y = sub(0, x);
13780 X = X.getOperand(0);
13781 Y = Y.getOperand(0);
13782 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13783 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13784 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13785 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13786 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13787 Mask.getOperand(1));
13788 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13790 // PBLENDVB only available on SSE 4.1
13791 if (!Subtarget->hasSSE41orAVX())
13794 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13796 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13797 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13798 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13799 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13800 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13804 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13807 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13808 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13810 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13812 if (!N0.hasOneUse() || !N1.hasOneUse())
13815 SDValue ShAmt0 = N0.getOperand(1);
13816 if (ShAmt0.getValueType() != MVT::i8)
13818 SDValue ShAmt1 = N1.getOperand(1);
13819 if (ShAmt1.getValueType() != MVT::i8)
13821 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13822 ShAmt0 = ShAmt0.getOperand(0);
13823 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13824 ShAmt1 = ShAmt1.getOperand(0);
13826 DebugLoc DL = N->getDebugLoc();
13827 unsigned Opc = X86ISD::SHLD;
13828 SDValue Op0 = N0.getOperand(0);
13829 SDValue Op1 = N1.getOperand(0);
13830 if (ShAmt0.getOpcode() == ISD::SUB) {
13831 Opc = X86ISD::SHRD;
13832 std::swap(Op0, Op1);
13833 std::swap(ShAmt0, ShAmt1);
13836 unsigned Bits = VT.getSizeInBits();
13837 if (ShAmt1.getOpcode() == ISD::SUB) {
13838 SDValue Sum = ShAmt1.getOperand(0);
13839 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13840 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13841 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13842 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13843 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13844 return DAG.getNode(Opc, DL, VT,
13846 DAG.getNode(ISD::TRUNCATE, DL,
13849 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13850 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13852 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13853 return DAG.getNode(Opc, DL, VT,
13854 N0.getOperand(0), N1.getOperand(0),
13855 DAG.getNode(ISD::TRUNCATE, DL,
13862 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
13863 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13864 TargetLowering::DAGCombinerInfo &DCI,
13865 const X86Subtarget *Subtarget) {
13866 if (DCI.isBeforeLegalizeOps())
13869 EVT VT = N->getValueType(0);
13871 if (VT != MVT::i32 && VT != MVT::i64)
13874 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
13876 // Create BLSMSK instructions by finding X ^ (X-1)
13877 SDValue N0 = N->getOperand(0);
13878 SDValue N1 = N->getOperand(1);
13879 DebugLoc DL = N->getDebugLoc();
13881 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13882 isAllOnes(N0.getOperand(1)))
13883 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13885 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13886 isAllOnes(N1.getOperand(1)))
13887 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13892 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13893 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13894 const X86Subtarget *Subtarget) {
13895 LoadSDNode *Ld = cast<LoadSDNode>(N);
13896 EVT RegVT = Ld->getValueType(0);
13897 EVT MemVT = Ld->getMemoryVT();
13898 DebugLoc dl = Ld->getDebugLoc();
13899 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13901 ISD::LoadExtType Ext = Ld->getExtensionType();
13903 // If this is a vector EXT Load then attempt to optimize it using a
13904 // shuffle. We need SSE4 for the shuffles.
13905 // TODO: It is possible to support ZExt by zeroing the undef values
13906 // during the shuffle phase or after the shuffle.
13907 if (RegVT.isVector() && RegVT.isInteger() &&
13908 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13909 assert(MemVT != RegVT && "Cannot extend to the same type");
13910 assert(MemVT.isVector() && "Must load a vector from memory");
13912 unsigned NumElems = RegVT.getVectorNumElements();
13913 unsigned RegSz = RegVT.getSizeInBits();
13914 unsigned MemSz = MemVT.getSizeInBits();
13915 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13916 // All sizes must be a power of two
13917 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13919 // Attempt to load the original value using a single load op.
13920 // Find a scalar type which is equal to the loaded word size.
13921 MVT SclrLoadTy = MVT::i8;
13922 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13923 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13924 MVT Tp = (MVT::SimpleValueType)tp;
13925 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13931 // Proceed if a load word is found.
13932 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13934 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13935 RegSz/SclrLoadTy.getSizeInBits());
13937 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13938 RegSz/MemVT.getScalarType().getSizeInBits());
13939 // Can't shuffle using an illegal type.
13940 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13942 // Perform a single load.
13943 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13945 Ld->getPointerInfo(), Ld->isVolatile(),
13946 Ld->isNonTemporal(), Ld->isInvariant(),
13947 Ld->getAlignment());
13949 // Insert the word loaded into a vector.
13950 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13951 LoadUnitVecVT, ScalarLoad);
13953 // Bitcast the loaded value to a vector of the original element type, in
13954 // the size of the target vector type.
13955 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13956 unsigned SizeRatio = RegSz/MemSz;
13958 // Redistribute the loaded elements into the different locations.
13959 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13960 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13962 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13963 DAG.getUNDEF(SlicedVec.getValueType()),
13964 ShuffleVec.data());
13966 // Bitcast to the requested type.
13967 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13968 // Replace the original load with the new sequence
13969 // and return the new chain.
13970 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13971 return SDValue(ScalarLoad.getNode(), 1);
13977 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13978 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13979 const X86Subtarget *Subtarget) {
13980 StoreSDNode *St = cast<StoreSDNode>(N);
13981 EVT VT = St->getValue().getValueType();
13982 EVT StVT = St->getMemoryVT();
13983 DebugLoc dl = St->getDebugLoc();
13984 SDValue StoredVal = St->getOperand(1);
13985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13987 // If we are saving a concatenation of two XMM registers, perform two stores.
13988 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13989 // 128-bit ones. If in the future the cost becomes only one memory access the
13990 // first version would be better.
13991 if (VT.getSizeInBits() == 256 &&
13992 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13993 StoredVal.getNumOperands() == 2) {
13995 SDValue Value0 = StoredVal.getOperand(0);
13996 SDValue Value1 = StoredVal.getOperand(1);
13998 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13999 SDValue Ptr0 = St->getBasePtr();
14000 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14002 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14003 St->getPointerInfo(), St->isVolatile(),
14004 St->isNonTemporal(), St->getAlignment());
14005 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14006 St->getPointerInfo(), St->isVolatile(),
14007 St->isNonTemporal(), St->getAlignment());
14008 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14011 // Optimize trunc store (of multiple scalars) to shuffle and store.
14012 // First, pack all of the elements in one place. Next, store to memory
14013 // in fewer chunks.
14014 if (St->isTruncatingStore() && VT.isVector()) {
14015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14016 unsigned NumElems = VT.getVectorNumElements();
14017 assert(StVT != VT && "Cannot truncate to the same type");
14018 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14019 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14021 // From, To sizes and ElemCount must be pow of two
14022 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14023 // We are going to use the original vector elt for storing.
14024 // Accumulated smaller vector elements must be a multiple of the store size.
14025 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14027 unsigned SizeRatio = FromSz / ToSz;
14029 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14031 // Create a type on which we perform the shuffle
14032 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14033 StVT.getScalarType(), NumElems*SizeRatio);
14035 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14037 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14038 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14039 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14041 // Can't shuffle using an illegal type
14042 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14044 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14045 DAG.getUNDEF(WideVec.getValueType()),
14046 ShuffleVec.data());
14047 // At this point all of the data is stored at the bottom of the
14048 // register. We now need to save it to mem.
14050 // Find the largest store unit
14051 MVT StoreType = MVT::i8;
14052 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14053 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14054 MVT Tp = (MVT::SimpleValueType)tp;
14055 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14059 // Bitcast the original vector into a vector of store-size units
14060 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14061 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14062 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14063 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14064 SmallVector<SDValue, 8> Chains;
14065 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14066 TLI.getPointerTy());
14067 SDValue Ptr = St->getBasePtr();
14069 // Perform one or more big stores into memory.
14070 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14071 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14072 StoreType, ShuffWide,
14073 DAG.getIntPtrConstant(i));
14074 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14075 St->getPointerInfo(), St->isVolatile(),
14076 St->isNonTemporal(), St->getAlignment());
14077 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14078 Chains.push_back(Ch);
14081 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14086 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14087 // the FP state in cases where an emms may be missing.
14088 // A preferable solution to the general problem is to figure out the right
14089 // places to insert EMMS. This qualifies as a quick hack.
14091 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14092 if (VT.getSizeInBits() != 64)
14095 const Function *F = DAG.getMachineFunction().getFunction();
14096 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14097 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14098 && Subtarget->hasXMMInt();
14099 if ((VT.isVector() ||
14100 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14101 isa<LoadSDNode>(St->getValue()) &&
14102 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14103 St->getChain().hasOneUse() && !St->isVolatile()) {
14104 SDNode* LdVal = St->getValue().getNode();
14105 LoadSDNode *Ld = 0;
14106 int TokenFactorIndex = -1;
14107 SmallVector<SDValue, 8> Ops;
14108 SDNode* ChainVal = St->getChain().getNode();
14109 // Must be a store of a load. We currently handle two cases: the load
14110 // is a direct child, and it's under an intervening TokenFactor. It is
14111 // possible to dig deeper under nested TokenFactors.
14112 if (ChainVal == LdVal)
14113 Ld = cast<LoadSDNode>(St->getChain());
14114 else if (St->getValue().hasOneUse() &&
14115 ChainVal->getOpcode() == ISD::TokenFactor) {
14116 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14117 if (ChainVal->getOperand(i).getNode() == LdVal) {
14118 TokenFactorIndex = i;
14119 Ld = cast<LoadSDNode>(St->getValue());
14121 Ops.push_back(ChainVal->getOperand(i));
14125 if (!Ld || !ISD::isNormalLoad(Ld))
14128 // If this is not the MMX case, i.e. we are just turning i64 load/store
14129 // into f64 load/store, avoid the transformation if there are multiple
14130 // uses of the loaded value.
14131 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14134 DebugLoc LdDL = Ld->getDebugLoc();
14135 DebugLoc StDL = N->getDebugLoc();
14136 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14137 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14139 if (Subtarget->is64Bit() || F64IsLegal) {
14140 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14141 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14142 Ld->getPointerInfo(), Ld->isVolatile(),
14143 Ld->isNonTemporal(), Ld->isInvariant(),
14144 Ld->getAlignment());
14145 SDValue NewChain = NewLd.getValue(1);
14146 if (TokenFactorIndex != -1) {
14147 Ops.push_back(NewChain);
14148 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14151 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14152 St->getPointerInfo(),
14153 St->isVolatile(), St->isNonTemporal(),
14154 St->getAlignment());
14157 // Otherwise, lower to two pairs of 32-bit loads / stores.
14158 SDValue LoAddr = Ld->getBasePtr();
14159 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14160 DAG.getConstant(4, MVT::i32));
14162 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14163 Ld->getPointerInfo(),
14164 Ld->isVolatile(), Ld->isNonTemporal(),
14165 Ld->isInvariant(), Ld->getAlignment());
14166 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14167 Ld->getPointerInfo().getWithOffset(4),
14168 Ld->isVolatile(), Ld->isNonTemporal(),
14170 MinAlign(Ld->getAlignment(), 4));
14172 SDValue NewChain = LoLd.getValue(1);
14173 if (TokenFactorIndex != -1) {
14174 Ops.push_back(LoLd);
14175 Ops.push_back(HiLd);
14176 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14180 LoAddr = St->getBasePtr();
14181 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14182 DAG.getConstant(4, MVT::i32));
14184 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14185 St->getPointerInfo(),
14186 St->isVolatile(), St->isNonTemporal(),
14187 St->getAlignment());
14188 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14189 St->getPointerInfo().getWithOffset(4),
14191 St->isNonTemporal(),
14192 MinAlign(St->getAlignment(), 4));
14193 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14198 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14199 /// and return the operands for the horizontal operation in LHS and RHS. A
14200 /// horizontal operation performs the binary operation on successive elements
14201 /// of its first operand, then on successive elements of its second operand,
14202 /// returning the resulting values in a vector. For example, if
14203 /// A = < float a0, float a1, float a2, float a3 >
14205 /// B = < float b0, float b1, float b2, float b3 >
14206 /// then the result of doing a horizontal operation on A and B is
14207 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14208 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14209 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14210 /// set to A, RHS to B, and the routine returns 'true'.
14211 /// Note that the binary operation should have the property that if one of the
14212 /// operands is UNDEF then the result is UNDEF.
14213 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14214 // Look for the following pattern: if
14215 // A = < float a0, float a1, float a2, float a3 >
14216 // B = < float b0, float b1, float b2, float b3 >
14218 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14219 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14220 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14221 // which is A horizontal-op B.
14223 // At least one of the operands should be a vector shuffle.
14224 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14225 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14228 EVT VT = LHS.getValueType();
14230 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14231 "Unsupported vector type for horizontal add/sub");
14233 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14234 // operate independently on 128-bit lanes.
14235 unsigned NumElts = VT.getVectorNumElements();
14236 unsigned NumLanes = VT.getSizeInBits()/128;
14237 unsigned NumLaneElts = NumElts / NumLanes;
14238 assert((NumLaneElts % 2 == 0) &&
14239 "Vector type should have an even number of elements in each lane");
14240 unsigned HalfLaneElts = NumLaneElts/2;
14242 // View LHS in the form
14243 // LHS = VECTOR_SHUFFLE A, B, LMask
14244 // If LHS is not a shuffle then pretend it is the shuffle
14245 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14246 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14249 SmallVector<int, 16> LMask(NumElts);
14250 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14251 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14252 A = LHS.getOperand(0);
14253 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14254 B = LHS.getOperand(1);
14255 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14257 if (LHS.getOpcode() != ISD::UNDEF)
14259 for (unsigned i = 0; i != NumElts; ++i)
14263 // Likewise, view RHS in the form
14264 // RHS = VECTOR_SHUFFLE C, D, RMask
14266 SmallVector<int, 16> RMask(NumElts);
14267 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14268 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14269 C = RHS.getOperand(0);
14270 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14271 D = RHS.getOperand(1);
14272 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14274 if (RHS.getOpcode() != ISD::UNDEF)
14276 for (unsigned i = 0; i != NumElts; ++i)
14280 // Check that the shuffles are both shuffling the same vectors.
14281 if (!(A == C && B == D) && !(A == D && B == C))
14284 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14285 if (!A.getNode() && !B.getNode())
14288 // If A and B occur in reverse order in RHS, then "swap" them (which means
14289 // rewriting the mask).
14291 CommuteVectorShuffleMask(RMask, NumElts);
14293 // At this point LHS and RHS are equivalent to
14294 // LHS = VECTOR_SHUFFLE A, B, LMask
14295 // RHS = VECTOR_SHUFFLE A, B, RMask
14296 // Check that the masks correspond to performing a horizontal operation.
14297 for (unsigned i = 0; i != NumElts; ++i) {
14298 int LIdx = LMask[i], RIdx = RMask[i];
14300 // Ignore any UNDEF components.
14301 if (LIdx < 0 || RIdx < 0 ||
14302 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14303 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14306 // Check that successive elements are being operated on. If not, this is
14307 // not a horizontal operation.
14308 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14309 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14310 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14311 if (!(LIdx == Index && RIdx == Index + 1) &&
14312 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14316 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14317 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14321 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14322 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14323 const X86Subtarget *Subtarget) {
14324 EVT VT = N->getValueType(0);
14325 SDValue LHS = N->getOperand(0);
14326 SDValue RHS = N->getOperand(1);
14328 // Try to synthesize horizontal adds from adds of shuffles.
14329 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14330 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14331 isHorizontalBinOp(LHS, RHS, true))
14332 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14336 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14337 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14338 const X86Subtarget *Subtarget) {
14339 EVT VT = N->getValueType(0);
14340 SDValue LHS = N->getOperand(0);
14341 SDValue RHS = N->getOperand(1);
14343 // Try to synthesize horizontal subs from subs of shuffles.
14344 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14345 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14346 isHorizontalBinOp(LHS, RHS, false))
14347 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14351 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14352 /// X86ISD::FXOR nodes.
14353 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14354 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14355 // F[X]OR(0.0, x) -> x
14356 // F[X]OR(x, 0.0) -> x
14357 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14358 if (C->getValueAPF().isPosZero())
14359 return N->getOperand(1);
14360 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14361 if (C->getValueAPF().isPosZero())
14362 return N->getOperand(0);
14366 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14367 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14368 // FAND(0.0, x) -> 0.0
14369 // FAND(x, 0.0) -> 0.0
14370 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14371 if (C->getValueAPF().isPosZero())
14372 return N->getOperand(0);
14373 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14374 if (C->getValueAPF().isPosZero())
14375 return N->getOperand(1);
14379 static SDValue PerformBTCombine(SDNode *N,
14381 TargetLowering::DAGCombinerInfo &DCI) {
14382 // BT ignores high bits in the bit index operand.
14383 SDValue Op1 = N->getOperand(1);
14384 if (Op1.hasOneUse()) {
14385 unsigned BitWidth = Op1.getValueSizeInBits();
14386 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14387 APInt KnownZero, KnownOne;
14388 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14389 !DCI.isBeforeLegalizeOps());
14390 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14391 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14392 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14393 DCI.CommitTargetLoweringOpt(TLO);
14398 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14399 SDValue Op = N->getOperand(0);
14400 if (Op.getOpcode() == ISD::BITCAST)
14401 Op = Op.getOperand(0);
14402 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14403 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14404 VT.getVectorElementType().getSizeInBits() ==
14405 OpVT.getVectorElementType().getSizeInBits()) {
14406 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14411 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14412 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14413 // (and (i32 x86isd::setcc_carry), 1)
14414 // This eliminates the zext. This transformation is necessary because
14415 // ISD::SETCC is always legalized to i8.
14416 DebugLoc dl = N->getDebugLoc();
14417 SDValue N0 = N->getOperand(0);
14418 EVT VT = N->getValueType(0);
14419 if (N0.getOpcode() == ISD::AND &&
14421 N0.getOperand(0).hasOneUse()) {
14422 SDValue N00 = N0.getOperand(0);
14423 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14425 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14426 if (!C || C->getZExtValue() != 1)
14428 return DAG.getNode(ISD::AND, dl, VT,
14429 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14430 N00.getOperand(0), N00.getOperand(1)),
14431 DAG.getConstant(1, VT));
14437 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14438 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14439 unsigned X86CC = N->getConstantOperandVal(0);
14440 SDValue EFLAG = N->getOperand(1);
14441 DebugLoc DL = N->getDebugLoc();
14443 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14444 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14446 if (X86CC == X86::COND_B)
14447 return DAG.getNode(ISD::AND, DL, MVT::i8,
14448 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14449 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14450 DAG.getConstant(1, MVT::i8));
14455 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14456 const X86TargetLowering *XTLI) {
14457 SDValue Op0 = N->getOperand(0);
14458 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14459 // a 32-bit target where SSE doesn't support i64->FP operations.
14460 if (Op0.getOpcode() == ISD::LOAD) {
14461 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14462 EVT VT = Ld->getValueType(0);
14463 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14464 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14465 !XTLI->getSubtarget()->is64Bit() &&
14466 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14467 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14468 Ld->getChain(), Op0, DAG);
14469 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14476 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14477 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14478 X86TargetLowering::DAGCombinerInfo &DCI) {
14479 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14480 // the result is either zero or one (depending on the input carry bit).
14481 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14482 if (X86::isZeroNode(N->getOperand(0)) &&
14483 X86::isZeroNode(N->getOperand(1)) &&
14484 // We don't have a good way to replace an EFLAGS use, so only do this when
14486 SDValue(N, 1).use_empty()) {
14487 DebugLoc DL = N->getDebugLoc();
14488 EVT VT = N->getValueType(0);
14489 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14490 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14491 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14492 DAG.getConstant(X86::COND_B,MVT::i8),
14494 DAG.getConstant(1, VT));
14495 return DCI.CombineTo(N, Res1, CarryOut);
14501 // fold (add Y, (sete X, 0)) -> adc 0, Y
14502 // (add Y, (setne X, 0)) -> sbb -1, Y
14503 // (sub (sete X, 0), Y) -> sbb 0, Y
14504 // (sub (setne X, 0), Y) -> adc -1, Y
14505 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14506 DebugLoc DL = N->getDebugLoc();
14508 // Look through ZExts.
14509 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14510 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14513 SDValue SetCC = Ext.getOperand(0);
14514 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14517 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14518 if (CC != X86::COND_E && CC != X86::COND_NE)
14521 SDValue Cmp = SetCC.getOperand(1);
14522 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14523 !X86::isZeroNode(Cmp.getOperand(1)) ||
14524 !Cmp.getOperand(0).getValueType().isInteger())
14527 SDValue CmpOp0 = Cmp.getOperand(0);
14528 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14529 DAG.getConstant(1, CmpOp0.getValueType()));
14531 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14532 if (CC == X86::COND_NE)
14533 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14534 DL, OtherVal.getValueType(), OtherVal,
14535 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14536 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14537 DL, OtherVal.getValueType(), OtherVal,
14538 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14541 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14542 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14543 const X86Subtarget *Subtarget) {
14544 EVT VT = N->getValueType(0);
14545 SDValue Op0 = N->getOperand(0);
14546 SDValue Op1 = N->getOperand(1);
14548 // Try to synthesize horizontal adds from adds of shuffles.
14549 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14550 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14551 isHorizontalBinOp(Op0, Op1, true))
14552 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14554 return OptimizeConditionalInDecrement(N, DAG);
14557 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14558 const X86Subtarget *Subtarget) {
14559 SDValue Op0 = N->getOperand(0);
14560 SDValue Op1 = N->getOperand(1);
14562 // X86 can't encode an immediate LHS of a sub. See if we can push the
14563 // negation into a preceding instruction.
14564 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14565 // If the RHS of the sub is a XOR with one use and a constant, invert the
14566 // immediate. Then add one to the LHS of the sub so we can turn
14567 // X-Y -> X+~Y+1, saving one register.
14568 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14569 isa<ConstantSDNode>(Op1.getOperand(1))) {
14570 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14571 EVT VT = Op0.getValueType();
14572 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14574 DAG.getConstant(~XorC, VT));
14575 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14576 DAG.getConstant(C->getAPIntValue()+1, VT));
14580 // Try to synthesize horizontal adds from adds of shuffles.
14581 EVT VT = N->getValueType(0);
14582 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14583 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14584 isHorizontalBinOp(Op0, Op1, true))
14585 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14587 return OptimizeConditionalInDecrement(N, DAG);
14590 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14591 DAGCombinerInfo &DCI) const {
14592 SelectionDAG &DAG = DCI.DAG;
14593 switch (N->getOpcode()) {
14595 case ISD::EXTRACT_VECTOR_ELT:
14596 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14598 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14599 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14600 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14601 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14602 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14603 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14606 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14607 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14608 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14609 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14610 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14611 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14612 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14613 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14614 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14616 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14617 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14618 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14619 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14620 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14621 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14622 case X86ISD::SHUFP: // Handle all target specific shuffles
14623 case X86ISD::PALIGN:
14624 case X86ISD::UNPCKH:
14625 case X86ISD::UNPCKL:
14626 case X86ISD::MOVHLPS:
14627 case X86ISD::MOVLHPS:
14628 case X86ISD::PSHUFD:
14629 case X86ISD::PSHUFHW:
14630 case X86ISD::PSHUFLW:
14631 case X86ISD::MOVSS:
14632 case X86ISD::MOVSD:
14633 case X86ISD::VPERMILP:
14634 case X86ISD::VPERM2X128:
14635 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14641 /// isTypeDesirableForOp - Return true if the target has native support for
14642 /// the specified value type and it is 'desirable' to use the type for the
14643 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14644 /// instruction encodings are longer and some i16 instructions are slow.
14645 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14646 if (!isTypeLegal(VT))
14648 if (VT != MVT::i16)
14655 case ISD::SIGN_EXTEND:
14656 case ISD::ZERO_EXTEND:
14657 case ISD::ANY_EXTEND:
14670 /// IsDesirableToPromoteOp - This method query the target whether it is
14671 /// beneficial for dag combiner to promote the specified node. If true, it
14672 /// should return the desired promotion type by reference.
14673 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14674 EVT VT = Op.getValueType();
14675 if (VT != MVT::i16)
14678 bool Promote = false;
14679 bool Commute = false;
14680 switch (Op.getOpcode()) {
14683 LoadSDNode *LD = cast<LoadSDNode>(Op);
14684 // If the non-extending load has a single use and it's not live out, then it
14685 // might be folded.
14686 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14687 Op.hasOneUse()*/) {
14688 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14689 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14690 // The only case where we'd want to promote LOAD (rather then it being
14691 // promoted as an operand is when it's only use is liveout.
14692 if (UI->getOpcode() != ISD::CopyToReg)
14699 case ISD::SIGN_EXTEND:
14700 case ISD::ZERO_EXTEND:
14701 case ISD::ANY_EXTEND:
14706 SDValue N0 = Op.getOperand(0);
14707 // Look out for (store (shl (load), x)).
14708 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14721 SDValue N0 = Op.getOperand(0);
14722 SDValue N1 = Op.getOperand(1);
14723 if (!Commute && MayFoldLoad(N1))
14725 // Avoid disabling potential load folding opportunities.
14726 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14728 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14738 //===----------------------------------------------------------------------===//
14739 // X86 Inline Assembly Support
14740 //===----------------------------------------------------------------------===//
14743 // Helper to match a string separated by whitespace.
14744 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
14745 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
14747 for (unsigned i = 0, e = args.size(); i != e; ++i) {
14748 StringRef piece(*args[i]);
14749 if (!s.startswith(piece)) // Check if the piece matches.
14752 s = s.substr(piece.size());
14753 StringRef::size_type pos = s.find_first_not_of(" \t");
14754 if (pos == 0) // We matched a prefix.
14762 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
14765 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14766 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14768 std::string AsmStr = IA->getAsmString();
14770 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14771 if (!Ty || Ty->getBitWidth() % 16 != 0)
14774 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14775 SmallVector<StringRef, 4> AsmPieces;
14776 SplitString(AsmStr, AsmPieces, ";\n");
14778 switch (AsmPieces.size()) {
14779 default: return false;
14781 // FIXME: this should verify that we are targeting a 486 or better. If not,
14782 // we will turn this bswap into something that will be lowered to logical
14783 // ops instead of emitting the bswap asm. For now, we don't support 486 or
14784 // lower so don't worry about this.
14786 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
14787 matchAsm(AsmPieces[0], "bswapl", "$0") ||
14788 matchAsm(AsmPieces[0], "bswapq", "$0") ||
14789 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
14790 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
14791 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
14792 // No need to check constraints, nothing other than the equivalent of
14793 // "=r,0" would be valid here.
14794 return IntrinsicLowering::LowerToByteSwap(CI);
14797 // rorw $$8, ${0:w} --> llvm.bswap.i16
14798 if (CI->getType()->isIntegerTy(16) &&
14799 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14800 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
14801 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
14803 const std::string &ConstraintsStr = IA->getConstraintString();
14804 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14805 std::sort(AsmPieces.begin(), AsmPieces.end());
14806 if (AsmPieces.size() == 4 &&
14807 AsmPieces[0] == "~{cc}" &&
14808 AsmPieces[1] == "~{dirflag}" &&
14809 AsmPieces[2] == "~{flags}" &&
14810 AsmPieces[3] == "~{fpsr}")
14811 return IntrinsicLowering::LowerToByteSwap(CI);
14815 if (CI->getType()->isIntegerTy(32) &&
14816 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14817 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
14818 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
14819 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
14821 const std::string &ConstraintsStr = IA->getConstraintString();
14822 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14823 std::sort(AsmPieces.begin(), AsmPieces.end());
14824 if (AsmPieces.size() == 4 &&
14825 AsmPieces[0] == "~{cc}" &&
14826 AsmPieces[1] == "~{dirflag}" &&
14827 AsmPieces[2] == "~{flags}" &&
14828 AsmPieces[3] == "~{fpsr}")
14829 return IntrinsicLowering::LowerToByteSwap(CI);
14832 if (CI->getType()->isIntegerTy(64)) {
14833 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14834 if (Constraints.size() >= 2 &&
14835 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14836 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14837 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14838 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
14839 matchAsm(AsmPieces[1], "bswap", "%edx") &&
14840 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
14841 return IntrinsicLowering::LowerToByteSwap(CI);
14851 /// getConstraintType - Given a constraint letter, return the type of
14852 /// constraint it is for this target.
14853 X86TargetLowering::ConstraintType
14854 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14855 if (Constraint.size() == 1) {
14856 switch (Constraint[0]) {
14867 return C_RegisterClass;
14891 return TargetLowering::getConstraintType(Constraint);
14894 /// Examine constraint type and operand type and determine a weight value.
14895 /// This object must already have been set up with the operand type
14896 /// and the current alternative constraint selected.
14897 TargetLowering::ConstraintWeight
14898 X86TargetLowering::getSingleConstraintMatchWeight(
14899 AsmOperandInfo &info, const char *constraint) const {
14900 ConstraintWeight weight = CW_Invalid;
14901 Value *CallOperandVal = info.CallOperandVal;
14902 // If we don't have a value, we can't do a match,
14903 // but allow it at the lowest weight.
14904 if (CallOperandVal == NULL)
14906 Type *type = CallOperandVal->getType();
14907 // Look at the constraint type.
14908 switch (*constraint) {
14910 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14921 if (CallOperandVal->getType()->isIntegerTy())
14922 weight = CW_SpecificReg;
14927 if (type->isFloatingPointTy())
14928 weight = CW_SpecificReg;
14931 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14932 weight = CW_SpecificReg;
14936 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14937 weight = CW_Register;
14940 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14941 if (C->getZExtValue() <= 31)
14942 weight = CW_Constant;
14946 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14947 if (C->getZExtValue() <= 63)
14948 weight = CW_Constant;
14952 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14953 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14954 weight = CW_Constant;
14958 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14959 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14960 weight = CW_Constant;
14964 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14965 if (C->getZExtValue() <= 3)
14966 weight = CW_Constant;
14970 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14971 if (C->getZExtValue() <= 0xff)
14972 weight = CW_Constant;
14977 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14978 weight = CW_Constant;
14982 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14983 if ((C->getSExtValue() >= -0x80000000LL) &&
14984 (C->getSExtValue() <= 0x7fffffffLL))
14985 weight = CW_Constant;
14989 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14990 if (C->getZExtValue() <= 0xffffffff)
14991 weight = CW_Constant;
14998 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14999 /// with another that has more specific requirements based on the type of the
15000 /// corresponding operand.
15001 const char *X86TargetLowering::
15002 LowerXConstraint(EVT ConstraintVT) const {
15003 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15004 // 'f' like normal targets.
15005 if (ConstraintVT.isFloatingPoint()) {
15006 if (Subtarget->hasXMMInt())
15008 if (Subtarget->hasXMM())
15012 return TargetLowering::LowerXConstraint(ConstraintVT);
15015 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15016 /// vector. If it is invalid, don't add anything to Ops.
15017 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15018 std::string &Constraint,
15019 std::vector<SDValue>&Ops,
15020 SelectionDAG &DAG) const {
15021 SDValue Result(0, 0);
15023 // Only support length 1 constraints for now.
15024 if (Constraint.length() > 1) return;
15026 char ConstraintLetter = Constraint[0];
15027 switch (ConstraintLetter) {
15030 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15031 if (C->getZExtValue() <= 31) {
15032 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15039 if (C->getZExtValue() <= 63) {
15040 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15046 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15047 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15048 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15055 if (C->getZExtValue() <= 255) {
15056 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15062 // 32-bit signed value
15063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15064 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15065 C->getSExtValue())) {
15066 // Widen to 64 bits here to get it sign extended.
15067 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15070 // FIXME gcc accepts some relocatable values here too, but only in certain
15071 // memory models; it's complicated.
15076 // 32-bit unsigned value
15077 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15078 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15079 C->getZExtValue())) {
15080 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15084 // FIXME gcc accepts some relocatable values here too, but only in certain
15085 // memory models; it's complicated.
15089 // Literal immediates are always ok.
15090 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15091 // Widen to 64 bits here to get it sign extended.
15092 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15096 // In any sort of PIC mode addresses need to be computed at runtime by
15097 // adding in a register or some sort of table lookup. These can't
15098 // be used as immediates.
15099 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15102 // If we are in non-pic codegen mode, we allow the address of a global (with
15103 // an optional displacement) to be used with 'i'.
15104 GlobalAddressSDNode *GA = 0;
15105 int64_t Offset = 0;
15107 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15109 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15110 Offset += GA->getOffset();
15112 } else if (Op.getOpcode() == ISD::ADD) {
15113 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15114 Offset += C->getZExtValue();
15115 Op = Op.getOperand(0);
15118 } else if (Op.getOpcode() == ISD::SUB) {
15119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15120 Offset += -C->getZExtValue();
15121 Op = Op.getOperand(0);
15126 // Otherwise, this isn't something we can handle, reject it.
15130 const GlobalValue *GV = GA->getGlobal();
15131 // If we require an extra load to get this address, as in PIC mode, we
15132 // can't accept it.
15133 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15134 getTargetMachine())))
15137 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15138 GA->getValueType(0), Offset);
15143 if (Result.getNode()) {
15144 Ops.push_back(Result);
15147 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15150 std::pair<unsigned, const TargetRegisterClass*>
15151 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15153 // First, see if this is a constraint that directly corresponds to an LLVM
15155 if (Constraint.size() == 1) {
15156 // GCC Constraint Letters
15157 switch (Constraint[0]) {
15159 // TODO: Slight differences here in allocation order and leaving
15160 // RIP in the class. Do they matter any more here than they do
15161 // in the normal allocation?
15162 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15163 if (Subtarget->is64Bit()) {
15164 if (VT == MVT::i32 || VT == MVT::f32)
15165 return std::make_pair(0U, X86::GR32RegisterClass);
15166 else if (VT == MVT::i16)
15167 return std::make_pair(0U, X86::GR16RegisterClass);
15168 else if (VT == MVT::i8 || VT == MVT::i1)
15169 return std::make_pair(0U, X86::GR8RegisterClass);
15170 else if (VT == MVT::i64 || VT == MVT::f64)
15171 return std::make_pair(0U, X86::GR64RegisterClass);
15174 // 32-bit fallthrough
15175 case 'Q': // Q_REGS
15176 if (VT == MVT::i32 || VT == MVT::f32)
15177 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15178 else if (VT == MVT::i16)
15179 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15180 else if (VT == MVT::i8 || VT == MVT::i1)
15181 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15182 else if (VT == MVT::i64)
15183 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15185 case 'r': // GENERAL_REGS
15186 case 'l': // INDEX_REGS
15187 if (VT == MVT::i8 || VT == MVT::i1)
15188 return std::make_pair(0U, X86::GR8RegisterClass);
15189 if (VT == MVT::i16)
15190 return std::make_pair(0U, X86::GR16RegisterClass);
15191 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15192 return std::make_pair(0U, X86::GR32RegisterClass);
15193 return std::make_pair(0U, X86::GR64RegisterClass);
15194 case 'R': // LEGACY_REGS
15195 if (VT == MVT::i8 || VT == MVT::i1)
15196 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15197 if (VT == MVT::i16)
15198 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15199 if (VT == MVT::i32 || !Subtarget->is64Bit())
15200 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15201 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15202 case 'f': // FP Stack registers.
15203 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15204 // value to the correct fpstack register class.
15205 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15206 return std::make_pair(0U, X86::RFP32RegisterClass);
15207 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15208 return std::make_pair(0U, X86::RFP64RegisterClass);
15209 return std::make_pair(0U, X86::RFP80RegisterClass);
15210 case 'y': // MMX_REGS if MMX allowed.
15211 if (!Subtarget->hasMMX()) break;
15212 return std::make_pair(0U, X86::VR64RegisterClass);
15213 case 'Y': // SSE_REGS if SSE2 allowed
15214 if (!Subtarget->hasXMMInt()) break;
15216 case 'x': // SSE_REGS if SSE1 allowed
15217 if (!Subtarget->hasXMM()) break;
15219 switch (VT.getSimpleVT().SimpleTy) {
15221 // Scalar SSE types.
15224 return std::make_pair(0U, X86::FR32RegisterClass);
15227 return std::make_pair(0U, X86::FR64RegisterClass);
15235 return std::make_pair(0U, X86::VR128RegisterClass);
15241 // Use the default implementation in TargetLowering to convert the register
15242 // constraint into a member of a register class.
15243 std::pair<unsigned, const TargetRegisterClass*> Res;
15244 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15246 // Not found as a standard register?
15247 if (Res.second == 0) {
15248 // Map st(0) -> st(7) -> ST0
15249 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15250 tolower(Constraint[1]) == 's' &&
15251 tolower(Constraint[2]) == 't' &&
15252 Constraint[3] == '(' &&
15253 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15254 Constraint[5] == ')' &&
15255 Constraint[6] == '}') {
15257 Res.first = X86::ST0+Constraint[4]-'0';
15258 Res.second = X86::RFP80RegisterClass;
15262 // GCC allows "st(0)" to be called just plain "st".
15263 if (StringRef("{st}").equals_lower(Constraint)) {
15264 Res.first = X86::ST0;
15265 Res.second = X86::RFP80RegisterClass;
15270 if (StringRef("{flags}").equals_lower(Constraint)) {
15271 Res.first = X86::EFLAGS;
15272 Res.second = X86::CCRRegisterClass;
15276 // 'A' means EAX + EDX.
15277 if (Constraint == "A") {
15278 Res.first = X86::EAX;
15279 Res.second = X86::GR32_ADRegisterClass;
15285 // Otherwise, check to see if this is a register class of the wrong value
15286 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15287 // turn into {ax},{dx}.
15288 if (Res.second->hasType(VT))
15289 return Res; // Correct type already, nothing to do.
15291 // All of the single-register GCC register classes map their values onto
15292 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15293 // really want an 8-bit or 32-bit register, map to the appropriate register
15294 // class and return the appropriate register.
15295 if (Res.second == X86::GR16RegisterClass) {
15296 if (VT == MVT::i8) {
15297 unsigned DestReg = 0;
15298 switch (Res.first) {
15300 case X86::AX: DestReg = X86::AL; break;
15301 case X86::DX: DestReg = X86::DL; break;
15302 case X86::CX: DestReg = X86::CL; break;
15303 case X86::BX: DestReg = X86::BL; break;
15306 Res.first = DestReg;
15307 Res.second = X86::GR8RegisterClass;
15309 } else if (VT == MVT::i32) {
15310 unsigned DestReg = 0;
15311 switch (Res.first) {
15313 case X86::AX: DestReg = X86::EAX; break;
15314 case X86::DX: DestReg = X86::EDX; break;
15315 case X86::CX: DestReg = X86::ECX; break;
15316 case X86::BX: DestReg = X86::EBX; break;
15317 case X86::SI: DestReg = X86::ESI; break;
15318 case X86::DI: DestReg = X86::EDI; break;
15319 case X86::BP: DestReg = X86::EBP; break;
15320 case X86::SP: DestReg = X86::ESP; break;
15323 Res.first = DestReg;
15324 Res.second = X86::GR32RegisterClass;
15326 } else if (VT == MVT::i64) {
15327 unsigned DestReg = 0;
15328 switch (Res.first) {
15330 case X86::AX: DestReg = X86::RAX; break;
15331 case X86::DX: DestReg = X86::RDX; break;
15332 case X86::CX: DestReg = X86::RCX; break;
15333 case X86::BX: DestReg = X86::RBX; break;
15334 case X86::SI: DestReg = X86::RSI; break;
15335 case X86::DI: DestReg = X86::RDI; break;
15336 case X86::BP: DestReg = X86::RBP; break;
15337 case X86::SP: DestReg = X86::RSP; break;
15340 Res.first = DestReg;
15341 Res.second = X86::GR64RegisterClass;
15344 } else if (Res.second == X86::FR32RegisterClass ||
15345 Res.second == X86::FR64RegisterClass ||
15346 Res.second == X86::VR128RegisterClass) {
15347 // Handle references to XMM physical registers that got mapped into the
15348 // wrong class. This can happen with constraints like {xmm0} where the
15349 // target independent register mapper will just pick the first match it can
15350 // find, ignoring the required type.
15351 if (VT == MVT::f32)
15352 Res.second = X86::FR32RegisterClass;
15353 else if (VT == MVT::f64)
15354 Res.second = X86::FR64RegisterClass;
15355 else if (X86::VR128RegisterClass->hasType(VT))
15356 Res.second = X86::VR128RegisterClass;