1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
163 RegInfo = TM.getRegisterInfo();
164 TD = getTargetData();
166 // Set up the TargetLowering object.
167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
169 // X86 is weird, it always uses i8 for shift amounts and setcc results.
170 setBooleanContents(ZeroOrOneBooleanContent);
171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 // For 64-bit since we have so many registers use the ILP scheduler, for
175 // 32-bit code use the register pressure specific scheduling.
176 // For Atom, always use ILP scheduling.
177 if (Subtarget->isAtom())
178 setSchedulingPreference(Sched::ILP);
179 else if (Subtarget->is64Bit())
180 setSchedulingPreference(Sched::ILP);
182 setSchedulingPreference(Sched::RegPressure);
183 setStackPointerRegisterToSaveRestore(X86StackPtr);
185 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
186 // Setup Windows compiler runtime calls.
187 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
188 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
189 setLibcallName(RTLIB::SREM_I64, "_allrem");
190 setLibcallName(RTLIB::UREM_I64, "_aullrem");
191 setLibcallName(RTLIB::MUL_I64, "_allmul");
192 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
193 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
194 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
195 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
198 // The _ftol2 runtime function has an unusual calling conv, which
199 // is modeled by a special pseudo-instruction.
200 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
201 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
202 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
203 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
206 if (Subtarget->isTargetDarwin()) {
207 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
208 setUseUnderscoreSetJmp(false);
209 setUseUnderscoreLongJmp(false);
210 } else if (Subtarget->isTargetMingw()) {
211 // MS runtime is weird: it exports _setjmp, but longjmp!
212 setUseUnderscoreSetJmp(true);
213 setUseUnderscoreLongJmp(false);
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(true);
219 // Set up the register classes.
220 addRegisterClass(MVT::i8, &X86::GR8RegClass);
221 addRegisterClass(MVT::i16, &X86::GR16RegClass);
222 addRegisterClass(MVT::i32, &X86::GR32RegClass);
223 if (Subtarget->is64Bit())
224 addRegisterClass(MVT::i64, &X86::GR64RegClass);
226 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
228 // We don't accept any truncstore of integer registers.
229 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
230 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
231 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
232 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
233 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
234 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
236 // SETOEQ and SETUNE require checking two conditions.
237 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
238 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
239 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
240 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
244 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
246 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
247 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
248 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
250 if (Subtarget->is64Bit()) {
251 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
253 } else if (!TM.Options.UseSoftFloat) {
254 // We have an algorithm for SSE2->double, and we turn this into a
255 // 64-bit FILD followed by conditional FADD for other targets.
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 // We have an algorithm for SSE2, and we turn this into a 64-bit
258 // FILD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
262 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
264 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
265 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
267 if (!TM.Options.UseSoftFloat) {
268 // SSE has no i16 to fp conversion, only i32
269 if (X86ScalarSSEf32) {
270 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
271 // f32 and f64 cases are Legal, f80 case is not
272 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
282 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
283 // are Legal, f80 is custom lowered.
284 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
287 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
289 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
290 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
292 if (X86ScalarSSEf32) {
293 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
294 // f32 and f64 cases are Legal, f80 case is not
295 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 // Handle FP_TO_UINT by promoting the destination to a larger signed
303 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
304 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
305 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
307 if (Subtarget->is64Bit()) {
308 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
310 } else if (!TM.Options.UseSoftFloat) {
311 // Since AVX is a superset of SSE3, only check for SSE here.
312 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
313 // Expand FP_TO_UINT into a select.
314 // FIXME: We would like to use a Custom expander here eventually to do
315 // the optimal thing for SSE vs. the default expansion in the legalizer.
316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
318 // With SSE3 we can use fisttpll to convert to a signed i64; without
319 // SSE, we're stuck with a fistpll.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
323 if (isTargetFTOL()) {
324 // Use the _ftol2 runtime function, which has a pseudo-instruction
325 // to handle its weird calling convention.
326 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
329 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330 if (!X86ScalarSSEf64) {
331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
335 // Without SSE, i64->f64 goes through memory.
336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
340 // Scalar integer divide and remainder are lowered to use operations that
341 // produce two results, to match the available instructions. This exposes
342 // the two-result form to trivial CSE, which is able to combine x/y and x%y
343 // into a single instruction.
345 // Scalar integer multiply-high is also lowered to use two-result
346 // operations, to match the available instructions. However, plain multiply
347 // (low) operations are left as Legal, as there are single-result
348 // instructions for this in x86. Using the two-result multiply instructions
349 // when both high and low results are needed must be arranged by dagcombine.
350 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
352 setOperationAction(ISD::MULHS, VT, Expand);
353 setOperationAction(ISD::MULHU, VT, Expand);
354 setOperationAction(ISD::SDIV, VT, Expand);
355 setOperationAction(ISD::UDIV, VT, Expand);
356 setOperationAction(ISD::SREM, VT, Expand);
357 setOperationAction(ISD::UREM, VT, Expand);
359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360 setOperationAction(ISD::ADDC, VT, Custom);
361 setOperationAction(ISD::ADDE, VT, Custom);
362 setOperationAction(ISD::SUBC, VT, Custom);
363 setOperationAction(ISD::SUBE, VT, Custom);
366 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
367 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
368 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
370 if (Subtarget->is64Bit())
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
376 setOperationAction(ISD::FREM , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f64 , Expand);
378 setOperationAction(ISD::FREM , MVT::f80 , Expand);
379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
381 // Promote the i8 variants and force them on up to i32 which has a shorter
383 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
384 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
385 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
386 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
387 if (Subtarget->hasBMI()) {
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
390 if (Subtarget->is64Bit())
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
393 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
394 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
399 if (Subtarget->hasLZCNT()) {
400 // When promoting the i8 variants, force them to i32 for a shorter
402 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
403 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
404 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
405 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
406 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
408 if (Subtarget->is64Bit())
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
411 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
412 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
413 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
417 if (Subtarget->is64Bit()) {
418 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423 if (Subtarget->hasPOPCNT()) {
424 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
426 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
427 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
428 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
429 if (Subtarget->is64Bit())
430 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
433 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
434 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
436 // These should be promoted to a larger select which is supported.
437 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
438 // X86 wants to expand cmov itself.
439 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
440 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
441 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
442 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
443 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
445 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
446 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
448 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
449 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
450 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
451 if (Subtarget->is64Bit()) {
452 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
455 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
458 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
459 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
460 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
461 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
462 if (Subtarget->is64Bit())
463 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
464 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
465 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
466 if (Subtarget->is64Bit()) {
467 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
468 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
469 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
470 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
471 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
473 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
474 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
475 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
476 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
479 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
480 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
483 if (Subtarget->hasSSE1())
484 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
486 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
487 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
489 // On X86 and X86-64, atomic operations are lowered to locked instructions.
490 // Locked instructions, in turn, have implicit fence semantics (all memory
491 // operations are flushed before issuing the locked instruction, and they
492 // are not buffered), so we can fold away the common pattern of
493 // fence-atomic-fence.
494 setShouldFoldAtomicFences(true);
496 // Expand certain atomics
497 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
499 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
500 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
504 if (!Subtarget->is64Bit()) {
505 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
506 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
515 if (Subtarget->hasCmpxchg16b()) {
516 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
519 // FIXME - use subtarget debug flags
520 if (!Subtarget->isTargetDarwin() &&
521 !Subtarget->isTargetELF() &&
522 !Subtarget->isTargetCygMing()) {
523 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
526 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
527 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
528 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
529 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
530 if (Subtarget->is64Bit()) {
531 setExceptionPointerRegister(X86::RAX);
532 setExceptionSelectorRegister(X86::RDX);
534 setExceptionPointerRegister(X86::EAX);
535 setExceptionSelectorRegister(X86::EDX);
537 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
538 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
540 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
541 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
543 setOperationAction(ISD::TRAP, MVT::Other, Legal);
545 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
546 setOperationAction(ISD::VASTART , MVT::Other, Custom);
547 setOperationAction(ISD::VAEND , MVT::Other, Expand);
548 if (Subtarget->is64Bit()) {
549 setOperationAction(ISD::VAARG , MVT::Other, Custom);
550 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
552 setOperationAction(ISD::VAARG , MVT::Other, Expand);
553 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
556 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
557 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
559 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
560 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561 MVT::i64 : MVT::i32, Custom);
562 else if (TM.Options.EnableSegmentedStacks)
563 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
564 MVT::i64 : MVT::i32, Custom);
566 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
567 MVT::i64 : MVT::i32, Expand);
569 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
570 // f32 and f64 use SSE.
571 // Set up the FP register classes.
572 addRegisterClass(MVT::f32, &X86::FR32RegClass);
573 addRegisterClass(MVT::f64, &X86::FR64RegClass);
575 // Use ANDPD to simulate FABS.
576 setOperationAction(ISD::FABS , MVT::f64, Custom);
577 setOperationAction(ISD::FABS , MVT::f32, Custom);
579 // Use XORP to simulate FNEG.
580 setOperationAction(ISD::FNEG , MVT::f64, Custom);
581 setOperationAction(ISD::FNEG , MVT::f32, Custom);
583 // Use ANDPD and ORPD to simulate FCOPYSIGN.
584 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
585 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
587 // Lower this to FGETSIGNx86 plus an AND.
588 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
591 // We don't support sin/cos/fmod
592 setOperationAction(ISD::FSIN , MVT::f64, Expand);
593 setOperationAction(ISD::FCOS , MVT::f64, Expand);
594 setOperationAction(ISD::FSIN , MVT::f32, Expand);
595 setOperationAction(ISD::FCOS , MVT::f32, Expand);
597 // Expand FP immediates into loads from the stack, except for the special
599 addLegalFPImmediate(APFloat(+0.0)); // xorpd
600 addLegalFPImmediate(APFloat(+0.0f)); // xorps
601 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
602 // Use SSE for f32, x87 for f64.
603 // Set up the FP register classes.
604 addRegisterClass(MVT::f32, &X86::FR32RegClass);
605 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
607 // Use ANDPS to simulate FABS.
608 setOperationAction(ISD::FABS , MVT::f32, Custom);
610 // Use XORP to simulate FNEG.
611 setOperationAction(ISD::FNEG , MVT::f32, Custom);
613 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
615 // Use ANDPS and ORPS to simulate FCOPYSIGN.
616 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
619 // We don't support sin/cos/fmod
620 setOperationAction(ISD::FSIN , MVT::f32, Expand);
621 setOperationAction(ISD::FCOS , MVT::f32, Expand);
623 // Special cases we handle for FP constants.
624 addLegalFPImmediate(APFloat(+0.0f)); // xorps
625 addLegalFPImmediate(APFloat(+0.0)); // FLD0
626 addLegalFPImmediate(APFloat(+1.0)); // FLD1
627 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
628 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
630 if (!TM.Options.UnsafeFPMath) {
631 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
632 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
634 } else if (!TM.Options.UseSoftFloat) {
635 // f32 and f64 in x87.
636 // Set up the FP register classes.
637 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
640 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
641 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
642 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
645 if (!TM.Options.UnsafeFPMath) {
646 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
647 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
649 addLegalFPImmediate(APFloat(+0.0)); // FLD0
650 addLegalFPImmediate(APFloat(+1.0)); // FLD1
651 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
652 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
653 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
654 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
655 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
656 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
659 // We don't support FMA.
660 setOperationAction(ISD::FMA, MVT::f64, Expand);
661 setOperationAction(ISD::FMA, MVT::f32, Expand);
663 // Long double always uses X87.
664 if (!TM.Options.UseSoftFloat) {
665 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
666 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
667 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
669 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
670 addLegalFPImmediate(TmpFlt); // FLD0
672 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
675 APFloat TmpFlt2(+1.0);
676 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
678 addLegalFPImmediate(TmpFlt2); // FLD1
679 TmpFlt2.changeSign();
680 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
683 if (!TM.Options.UnsafeFPMath) {
684 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
685 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
688 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
689 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
690 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
691 setOperationAction(ISD::FRINT, MVT::f80, Expand);
692 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
693 setOperationAction(ISD::FMA, MVT::f80, Expand);
696 // Always use a library call for pow.
697 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
698 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
699 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
701 setOperationAction(ISD::FLOG, MVT::f80, Expand);
702 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
703 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
704 setOperationAction(ISD::FEXP, MVT::f80, Expand);
705 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
707 // First set operation action for all vector types to either promote
708 // (for widening) or expand (for scalarization). Then we will selectively
709 // turn on ones that can be effectively codegen'd.
710 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
711 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
712 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
727 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FMA, (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 (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
771 InnerVT <= 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::VR64RegClass);
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->hasSSE1()) {
819 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
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);
834 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
835 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
837 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
838 // registers cannot be used even for integer operations.
839 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
840 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
841 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
842 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
844 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
845 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
846 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
847 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
848 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
849 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
850 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
851 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
852 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
853 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
854 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
855 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
856 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
857 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
858 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
859 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
861 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
862 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
863 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
864 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
866 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
867 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
868 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
872 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
874 MVT VT = (MVT::SimpleValueType)i;
875 // Do not attempt to custom lower non-power-of-2 vectors
876 if (!isPowerOf2_32(VT.getVectorNumElements()))
878 // Do not attempt to custom lower non-128-bit vectors
879 if (!VT.is128BitVector())
881 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
882 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
886 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
887 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
888 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
889 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
893 if (Subtarget->is64Bit()) {
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
898 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to promote non-128-bit vectors
903 if (!VT.is128BitVector())
906 setOperationAction(ISD::AND, VT, Promote);
907 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
908 setOperationAction(ISD::OR, VT, Promote);
909 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
910 setOperationAction(ISD::XOR, VT, Promote);
911 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
912 setOperationAction(ISD::LOAD, VT, Promote);
913 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
914 setOperationAction(ISD::SELECT, VT, Promote);
915 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
918 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
920 // Custom lower v2i64 and v2f64 selects.
921 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
922 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
923 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
924 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
926 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
927 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
930 if (Subtarget->hasSSE41()) {
931 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
932 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
933 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
934 setOperationAction(ISD::FRINT, MVT::f32, Legal);
935 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
936 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
937 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
938 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
939 setOperationAction(ISD::FRINT, MVT::f64, Legal);
940 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
942 // FIXME: Do we need to handle scalar-to-vector here?
943 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
945 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
946 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
947 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
948 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
949 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
951 // i8 and i16 vectors are custom , because the source register and source
952 // source memory operand types are not the same width. f32 vectors are
953 // custom since the immediate controlling the insert encodes additional
955 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
956 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
957 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
958 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
960 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
961 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
962 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
963 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
965 // FIXME: these should be Legal but thats only for the case where
966 // the index is constant. For now custom expand to deal with that.
967 if (Subtarget->is64Bit()) {
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
969 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
973 if (Subtarget->hasSSE2()) {
974 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
975 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
977 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
978 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
980 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
981 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
983 if (Subtarget->hasAVX2()) {
984 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
985 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
987 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
988 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
990 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
992 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
993 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
995 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
996 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
998 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1002 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1003 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1004 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1005 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1006 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1007 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1008 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1010 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1011 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1012 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1014 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1015 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1016 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1017 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1018 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1019 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1021 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1022 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1023 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1024 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1025 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1026 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1028 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1029 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1030 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1032 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1035 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1036 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1038 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1039 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1041 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1042 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1043 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1044 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1046 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1047 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1048 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1050 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1051 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1052 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1053 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1055 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1056 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1057 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1058 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1059 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1060 setOperationAction(ISD::FMA, MVT::f32, Custom);
1061 setOperationAction(ISD::FMA, MVT::f64, Custom);
1064 if (Subtarget->hasAVX2()) {
1065 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1066 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1067 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1068 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1070 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1071 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1072 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1073 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1075 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1076 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1077 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1078 // Don't lower v32i8 because there is no 128-bit byte mul
1080 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1082 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1083 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1085 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1086 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1088 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1090 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1091 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1092 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1093 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1095 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1096 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1097 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1098 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1100 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1101 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1102 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1103 // Don't lower v32i8 because there is no 128-bit byte mul
1105 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1106 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1108 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1109 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1111 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1114 // Custom lower several nodes for 256-bit types.
1115 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1116 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1117 MVT VT = (MVT::SimpleValueType)i;
1119 // Extract subvector is special because the value type
1120 // (result) is 128-bit but the source is 256-bit wide.
1121 if (VT.is128BitVector())
1122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1124 // Do not attempt to custom lower other non-256-bit vectors
1125 if (!VT.is256BitVector())
1128 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1129 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1130 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1131 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1132 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1133 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1134 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1137 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1138 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1139 MVT VT = (MVT::SimpleValueType)i;
1141 // Do not attempt to promote non-256-bit vectors
1142 if (!VT.is256BitVector())
1145 setOperationAction(ISD::AND, VT, Promote);
1146 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1147 setOperationAction(ISD::OR, VT, Promote);
1148 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1149 setOperationAction(ISD::XOR, VT, Promote);
1150 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1151 setOperationAction(ISD::LOAD, VT, Promote);
1152 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1153 setOperationAction(ISD::SELECT, VT, Promote);
1154 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1158 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1159 // of this type with custom code.
1160 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1161 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1162 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1166 // We want to custom lower some of our intrinsics.
1167 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1168 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1171 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1172 // handle type legalization for these operations here.
1174 // FIXME: We really should do custom legalization for addition and
1175 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1176 // than generic legalization for 64-bit multiplication-with-overflow, though.
1177 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1178 // Add/Sub/Mul with overflow operations are custom lowered.
1180 setOperationAction(ISD::SADDO, VT, Custom);
1181 setOperationAction(ISD::UADDO, VT, Custom);
1182 setOperationAction(ISD::SSUBO, VT, Custom);
1183 setOperationAction(ISD::USUBO, VT, Custom);
1184 setOperationAction(ISD::SMULO, VT, Custom);
1185 setOperationAction(ISD::UMULO, VT, Custom);
1188 // There are no 8-bit 3-address imul/mul instructions
1189 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1190 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1192 if (!Subtarget->is64Bit()) {
1193 // These libcalls are not available in 32-bit.
1194 setLibcallName(RTLIB::SHL_I128, 0);
1195 setLibcallName(RTLIB::SRL_I128, 0);
1196 setLibcallName(RTLIB::SRA_I128, 0);
1199 // We have target-specific dag combine patterns for the following nodes:
1200 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1201 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1202 setTargetDAGCombine(ISD::VSELECT);
1203 setTargetDAGCombine(ISD::SELECT);
1204 setTargetDAGCombine(ISD::SHL);
1205 setTargetDAGCombine(ISD::SRA);
1206 setTargetDAGCombine(ISD::SRL);
1207 setTargetDAGCombine(ISD::OR);
1208 setTargetDAGCombine(ISD::AND);
1209 setTargetDAGCombine(ISD::ADD);
1210 setTargetDAGCombine(ISD::FADD);
1211 setTargetDAGCombine(ISD::FSUB);
1212 setTargetDAGCombine(ISD::FMA);
1213 setTargetDAGCombine(ISD::SUB);
1214 setTargetDAGCombine(ISD::LOAD);
1215 setTargetDAGCombine(ISD::STORE);
1216 setTargetDAGCombine(ISD::ZERO_EXTEND);
1217 setTargetDAGCombine(ISD::ANY_EXTEND);
1218 setTargetDAGCombine(ISD::SIGN_EXTEND);
1219 setTargetDAGCombine(ISD::TRUNCATE);
1220 setTargetDAGCombine(ISD::UINT_TO_FP);
1221 setTargetDAGCombine(ISD::SINT_TO_FP);
1222 setTargetDAGCombine(ISD::SETCC);
1223 setTargetDAGCombine(ISD::FP_TO_SINT);
1224 if (Subtarget->is64Bit())
1225 setTargetDAGCombine(ISD::MUL);
1226 setTargetDAGCombine(ISD::XOR);
1228 computeRegisterProperties();
1230 // On Darwin, -Os means optimize for size without hurting performance,
1231 // do not reduce the limit.
1232 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1233 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1234 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1235 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1236 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1237 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1238 setPrefLoopAlignment(4); // 2^4 bytes.
1239 benefitFromCodePlacementOpt = true;
1241 // Predictable cmov don't hurt on atom because it's in-order.
1242 predictableSelectIsExpensive = !Subtarget->isAtom();
1244 setPrefFunctionAlignment(4); // 2^4 bytes.
1248 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1249 if (!VT.isVector()) return MVT::i8;
1250 return VT.changeVectorElementTypeToInteger();
1254 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1255 /// the desired ByVal argument alignment.
1256 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1259 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1260 if (VTy->getBitWidth() == 128)
1262 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1263 unsigned EltAlign = 0;
1264 getMaxByValAlign(ATy->getElementType(), EltAlign);
1265 if (EltAlign > MaxAlign)
1266 MaxAlign = EltAlign;
1267 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1268 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1269 unsigned EltAlign = 0;
1270 getMaxByValAlign(STy->getElementType(i), EltAlign);
1271 if (EltAlign > MaxAlign)
1272 MaxAlign = EltAlign;
1279 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1280 /// function arguments in the caller parameter area. For X86, aggregates
1281 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1282 /// are at 4-byte boundaries.
1283 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1284 if (Subtarget->is64Bit()) {
1285 // Max of 8 and alignment of type.
1286 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1293 if (Subtarget->hasSSE1())
1294 getMaxByValAlign(Ty, Align);
1298 /// getOptimalMemOpType - Returns the target specific optimal type for load
1299 /// and store operations as a result of memset, memcpy, and memmove
1300 /// lowering. If DstAlign is zero that means it's safe to destination
1301 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1302 /// means there isn't a need to check it against alignment requirement,
1303 /// probably because the source does not need to be loaded. If
1304 /// 'IsZeroVal' is true, that means it's safe to return a
1305 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1306 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1307 /// constant so it does not need to be loaded.
1308 /// It returns EVT::Other if the type should be determined using generic
1309 /// target-independent logic.
1311 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1312 unsigned DstAlign, unsigned SrcAlign,
1315 MachineFunction &MF) const {
1316 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1317 // linux. This is because the stack realignment code can't handle certain
1318 // cases like PR2962. This should be removed when PR2962 is fixed.
1319 const Function *F = MF.getFunction();
1321 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1323 (Subtarget->isUnalignedMemAccessFast() ||
1324 ((DstAlign == 0 || DstAlign >= 16) &&
1325 (SrcAlign == 0 || SrcAlign >= 16))) &&
1326 Subtarget->getStackAlignment() >= 16) {
1327 if (Subtarget->getStackAlignment() >= 32) {
1328 if (Subtarget->hasAVX2())
1330 if (Subtarget->hasAVX())
1333 if (Subtarget->hasSSE2())
1335 if (Subtarget->hasSSE1())
1337 } else if (!MemcpyStrSrc && Size >= 8 &&
1338 !Subtarget->is64Bit() &&
1339 Subtarget->getStackAlignment() >= 8 &&
1340 Subtarget->hasSSE2()) {
1341 // Do not use f64 to lower memcpy if source is string constant. It's
1342 // better to use i32 to avoid the loads.
1346 if (Subtarget->is64Bit() && Size >= 8)
1351 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1352 /// current function. The returned value is a member of the
1353 /// MachineJumpTableInfo::JTEntryKind enum.
1354 unsigned X86TargetLowering::getJumpTableEncoding() const {
1355 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1357 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1358 Subtarget->isPICStyleGOT())
1359 return MachineJumpTableInfo::EK_Custom32;
1361 // Otherwise, use the normal jump table encoding heuristics.
1362 return TargetLowering::getJumpTableEncoding();
1366 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1367 const MachineBasicBlock *MBB,
1368 unsigned uid,MCContext &Ctx) const{
1369 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1370 Subtarget->isPICStyleGOT());
1371 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1373 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1374 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1377 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1379 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1380 SelectionDAG &DAG) const {
1381 if (!Subtarget->is64Bit())
1382 // This doesn't have DebugLoc associated with it, but is not really the
1383 // same as a Register.
1384 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1388 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1389 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1391 const MCExpr *X86TargetLowering::
1392 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1393 MCContext &Ctx) const {
1394 // X86-64 uses RIP relative addressing based on the jump table label.
1395 if (Subtarget->isPICStyleRIPRel())
1396 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1398 // Otherwise, the reference is relative to the PIC base.
1399 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1402 // FIXME: Why this routine is here? Move to RegInfo!
1403 std::pair<const TargetRegisterClass*, uint8_t>
1404 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1405 const TargetRegisterClass *RRC = 0;
1407 switch (VT.getSimpleVT().SimpleTy) {
1409 return TargetLowering::findRepresentativeClass(VT);
1410 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1411 RRC = Subtarget->is64Bit() ?
1412 (const TargetRegisterClass*)&X86::GR64RegClass :
1413 (const TargetRegisterClass*)&X86::GR32RegClass;
1416 RRC = &X86::VR64RegClass;
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::VR128RegClass;
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 // Promote values to the appropriate types
1503 if (VA.getLocInfo() == CCValAssign::SExt)
1504 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1505 else if (VA.getLocInfo() == CCValAssign::ZExt)
1506 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1507 else if (VA.getLocInfo() == CCValAssign::AExt)
1508 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1509 else if (VA.getLocInfo() == CCValAssign::BCvt)
1510 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1512 // If this is x86-64, and we disabled SSE, we can't return FP values,
1513 // or SSE or MMX vectors.
1514 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1515 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1516 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1517 report_fatal_error("SSE register return with SSE disabled");
1519 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1520 // llvm-gcc has never done it right and no one has noticed, so this
1521 // should be OK for now.
1522 if (ValVT == MVT::f64 &&
1523 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1524 report_fatal_error("SSE2 register return with SSE2 disabled");
1526 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1527 // the RET instruction and handled by the FP Stackifier.
1528 if (VA.getLocReg() == X86::ST0 ||
1529 VA.getLocReg() == X86::ST1) {
1530 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1531 // change the value to the FP stack register class.
1532 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1533 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1534 RetOps.push_back(ValToCopy);
1535 // Don't emit a copytoreg.
1539 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1540 // which is returned in RAX / RDX.
1541 if (Subtarget->is64Bit()) {
1542 if (ValVT == MVT::x86mmx) {
1543 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1544 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1545 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1547 // If we don't have SSE2 available, convert to v4f32 so the generated
1548 // register is legal.
1549 if (!Subtarget->hasSSE2())
1550 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1555 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1556 Flag = Chain.getValue(1);
1559 // The x86-64 ABI for returning structs by value requires that we copy
1560 // the sret argument into %rax for the return. We saved the argument into
1561 // a virtual register in the entry block, so now we copy the value out
1563 if (Subtarget->is64Bit() &&
1564 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1565 MachineFunction &MF = DAG.getMachineFunction();
1566 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1567 unsigned Reg = FuncInfo->getSRetReturnReg();
1569 "SRetReturnReg should have been set in LowerFormalArguments().");
1570 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1572 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1573 Flag = Chain.getValue(1);
1575 // RAX now acts like a return value.
1576 MRI.addLiveOut(X86::RAX);
1579 RetOps[0] = Chain; // Update chain.
1581 // Add the flag if we have it.
1583 RetOps.push_back(Flag);
1585 return DAG.getNode(X86ISD::RET_FLAG, dl,
1586 MVT::Other, &RetOps[0], RetOps.size());
1589 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1590 if (N->getNumValues() != 1)
1592 if (!N->hasNUsesOfValue(1, 0))
1595 SDValue TCChain = Chain;
1596 SDNode *Copy = *N->use_begin();
1597 if (Copy->getOpcode() == ISD::CopyToReg) {
1598 // If the copy has a glue operand, we conservatively assume it isn't safe to
1599 // perform a tail call.
1600 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1602 TCChain = Copy->getOperand(0);
1603 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1606 bool HasRet = false;
1607 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1609 if (UI->getOpcode() != X86ISD::RET_FLAG)
1622 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1623 ISD::NodeType ExtendKind) const {
1625 // TODO: Is this also valid on 32-bit?
1626 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1627 ReturnMVT = MVT::i8;
1629 ReturnMVT = MVT::i32;
1631 EVT MinVT = getRegisterType(Context, ReturnMVT);
1632 return VT.bitsLT(MinVT) ? MinVT : VT;
1635 /// LowerCallResult - Lower the result values of a call into the
1636 /// appropriate copies out of appropriate physical registers.
1639 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1640 CallingConv::ID CallConv, bool isVarArg,
1641 const SmallVectorImpl<ISD::InputArg> &Ins,
1642 DebugLoc dl, SelectionDAG &DAG,
1643 SmallVectorImpl<SDValue> &InVals) const {
1645 // Assign locations to each value returned by this call.
1646 SmallVector<CCValAssign, 16> RVLocs;
1647 bool Is64Bit = Subtarget->is64Bit();
1648 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1649 getTargetMachine(), RVLocs, *DAG.getContext());
1650 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1652 // Copy all of the result registers out of their specified physreg.
1653 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1654 CCValAssign &VA = RVLocs[i];
1655 EVT CopyVT = VA.getValVT();
1657 // If this is x86-64, and we disabled SSE, we can't return FP values
1658 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1659 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1660 report_fatal_error("SSE register return with SSE disabled");
1665 // If this is a call to a function that returns an fp value on the floating
1666 // point stack, we must guarantee the value is popped from the stack, so
1667 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1668 // if the return value is not used. We use the FpPOP_RETVAL instruction
1670 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1671 // If we prefer to use the value in xmm registers, copy it out as f80 and
1672 // use a truncate to move it from fp stack reg to xmm reg.
1673 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1674 SDValue Ops[] = { Chain, InFlag };
1675 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1676 MVT::Other, MVT::Glue, Ops, 2), 1);
1677 Val = Chain.getValue(0);
1679 // Round the f80 to the right size, which also moves it to the appropriate
1681 if (CopyVT != VA.getValVT())
1682 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1683 // This truncation won't change the value.
1684 DAG.getIntPtrConstant(1));
1686 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1687 CopyVT, InFlag).getValue(1);
1688 Val = Chain.getValue(0);
1690 InFlag = Chain.getValue(2);
1691 InVals.push_back(Val);
1698 //===----------------------------------------------------------------------===//
1699 // C & StdCall & Fast Calling Convention implementation
1700 //===----------------------------------------------------------------------===//
1701 // StdCall calling convention seems to be standard for many Windows' API
1702 // routines and around. It differs from C calling convention just a little:
1703 // callee should clean up the stack, not caller. Symbols should be also
1704 // decorated in some fancy way :) It doesn't support any vector arguments.
1705 // For info on fast calling convention see Fast Calling Convention (tail call)
1706 // implementation LowerX86_32FastCCCallTo.
1708 /// CallIsStructReturn - Determines whether a call uses struct return
1710 enum StructReturnType {
1715 static StructReturnType
1716 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1718 return NotStructReturn;
1720 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1721 if (!Flags.isSRet())
1722 return NotStructReturn;
1723 if (Flags.isInReg())
1724 return RegStructReturn;
1725 return StackStructReturn;
1728 /// ArgsAreStructReturn - Determines whether a function uses struct
1729 /// return semantics.
1730 static StructReturnType
1731 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1733 return NotStructReturn;
1735 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1736 if (!Flags.isSRet())
1737 return NotStructReturn;
1738 if (Flags.isInReg())
1739 return RegStructReturn;
1740 return StackStructReturn;
1743 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1744 /// by "Src" to address "Dst" with size and alignment information specified by
1745 /// the specific parameter attribute. The copy will be passed as a byval
1746 /// function parameter.
1748 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1749 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1751 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1753 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1754 /*isVolatile*/false, /*AlwaysInline=*/true,
1755 MachinePointerInfo(), MachinePointerInfo());
1758 /// IsTailCallConvention - Return true if the calling convention is one that
1759 /// supports tail call optimization.
1760 static bool IsTailCallConvention(CallingConv::ID CC) {
1761 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1764 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1765 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1769 CallingConv::ID CalleeCC = CS.getCallingConv();
1770 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1776 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1777 /// a tailcall target by changing its ABI.
1778 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1779 bool GuaranteedTailCallOpt) {
1780 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1784 X86TargetLowering::LowerMemArgument(SDValue Chain,
1785 CallingConv::ID CallConv,
1786 const SmallVectorImpl<ISD::InputArg> &Ins,
1787 DebugLoc dl, SelectionDAG &DAG,
1788 const CCValAssign &VA,
1789 MachineFrameInfo *MFI,
1791 // Create the nodes corresponding to a load from this parameter slot.
1792 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1793 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1794 getTargetMachine().Options.GuaranteedTailCallOpt);
1795 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1798 // If value is passed by pointer we have address passed instead of the value
1800 if (VA.getLocInfo() == CCValAssign::Indirect)
1801 ValVT = VA.getLocVT();
1803 ValVT = VA.getValVT();
1805 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1806 // changed with more analysis.
1807 // In case of tail call optimization mark all arguments mutable. Since they
1808 // could be overwritten by lowering of arguments in case of a tail call.
1809 if (Flags.isByVal()) {
1810 unsigned Bytes = Flags.getByValSize();
1811 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1812 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1813 return DAG.getFrameIndex(FI, getPointerTy());
1815 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1816 VA.getLocMemOffset(), isImmutable);
1817 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1818 return DAG.getLoad(ValVT, dl, Chain, FIN,
1819 MachinePointerInfo::getFixedStack(FI),
1820 false, false, false, 0);
1825 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1826 CallingConv::ID CallConv,
1828 const SmallVectorImpl<ISD::InputArg> &Ins,
1831 SmallVectorImpl<SDValue> &InVals)
1833 MachineFunction &MF = DAG.getMachineFunction();
1834 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1836 const Function* Fn = MF.getFunction();
1837 if (Fn->hasExternalLinkage() &&
1838 Subtarget->isTargetCygMing() &&
1839 Fn->getName() == "main")
1840 FuncInfo->setForceFramePointer(true);
1842 MachineFrameInfo *MFI = MF.getFrameInfo();
1843 bool Is64Bit = Subtarget->is64Bit();
1844 bool IsWindows = Subtarget->isTargetWindows();
1845 bool IsWin64 = Subtarget->isTargetWin64();
1847 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1848 "Var args not supported with calling convention fastcc or ghc");
1850 // Assign locations to all of the incoming arguments.
1851 SmallVector<CCValAssign, 16> ArgLocs;
1852 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1853 ArgLocs, *DAG.getContext());
1855 // Allocate shadow area for Win64
1857 CCInfo.AllocateStack(32, 8);
1860 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1862 unsigned LastVal = ~0U;
1864 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1865 CCValAssign &VA = ArgLocs[i];
1866 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1868 assert(VA.getValNo() != LastVal &&
1869 "Don't support value assigned to multiple locs yet");
1871 LastVal = VA.getValNo();
1873 if (VA.isRegLoc()) {
1874 EVT RegVT = VA.getLocVT();
1875 const TargetRegisterClass *RC;
1876 if (RegVT == MVT::i32)
1877 RC = &X86::GR32RegClass;
1878 else if (Is64Bit && RegVT == MVT::i64)
1879 RC = &X86::GR64RegClass;
1880 else if (RegVT == MVT::f32)
1881 RC = &X86::FR32RegClass;
1882 else if (RegVT == MVT::f64)
1883 RC = &X86::FR64RegClass;
1884 else if (RegVT.is256BitVector())
1885 RC = &X86::VR256RegClass;
1886 else if (RegVT.is128BitVector())
1887 RC = &X86::VR128RegClass;
1888 else if (RegVT == MVT::x86mmx)
1889 RC = &X86::VR64RegClass;
1891 llvm_unreachable("Unknown argument type!");
1893 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1894 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1896 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1897 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1899 if (VA.getLocInfo() == CCValAssign::SExt)
1900 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1901 DAG.getValueType(VA.getValVT()));
1902 else if (VA.getLocInfo() == CCValAssign::ZExt)
1903 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1904 DAG.getValueType(VA.getValVT()));
1905 else if (VA.getLocInfo() == CCValAssign::BCvt)
1906 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1908 if (VA.isExtInLoc()) {
1909 // Handle MMX values passed in XMM regs.
1910 if (RegVT.isVector()) {
1911 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1914 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1917 assert(VA.isMemLoc());
1918 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1921 // If value is passed via pointer - do a load.
1922 if (VA.getLocInfo() == CCValAssign::Indirect)
1923 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1924 MachinePointerInfo(), false, false, false, 0);
1926 InVals.push_back(ArgValue);
1929 // The x86-64 ABI for returning structs by value requires that we copy
1930 // the sret argument into %rax for the return. Save the argument into
1931 // a virtual register so that we can access it from the return points.
1932 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1933 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1934 unsigned Reg = FuncInfo->getSRetReturnReg();
1936 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1937 FuncInfo->setSRetReturnReg(Reg);
1939 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1940 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1943 unsigned StackSize = CCInfo.getNextStackOffset();
1944 // Align stack specially for tail calls.
1945 if (FuncIsMadeTailCallSafe(CallConv,
1946 MF.getTarget().Options.GuaranteedTailCallOpt))
1947 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1949 // If the function takes variable number of arguments, make a frame index for
1950 // the start of the first vararg value... for expansion of llvm.va_start.
1952 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1953 CallConv != CallingConv::X86_ThisCall)) {
1954 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1957 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1959 // FIXME: We should really autogenerate these arrays
1960 static const uint16_t GPR64ArgRegsWin64[] = {
1961 X86::RCX, X86::RDX, X86::R8, X86::R9
1963 static const uint16_t GPR64ArgRegs64Bit[] = {
1964 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1966 static const uint16_t XMMArgRegs64Bit[] = {
1967 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1968 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1970 const uint16_t *GPR64ArgRegs;
1971 unsigned NumXMMRegs = 0;
1974 // The XMM registers which might contain var arg parameters are shadowed
1975 // in their paired GPR. So we only need to save the GPR to their home
1977 TotalNumIntRegs = 4;
1978 GPR64ArgRegs = GPR64ArgRegsWin64;
1980 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1981 GPR64ArgRegs = GPR64ArgRegs64Bit;
1983 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1986 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1989 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1990 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1991 "SSE register cannot be used when SSE is disabled!");
1992 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1993 NoImplicitFloatOps) &&
1994 "SSE register cannot be used when SSE is disabled!");
1995 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1996 !Subtarget->hasSSE1())
1997 // Kernel mode asks for SSE to be disabled, so don't push them
1999 TotalNumXMMRegs = 0;
2002 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2003 // Get to the caller-allocated home save location. Add 8 to account
2004 // for the return address.
2005 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2006 FuncInfo->setRegSaveFrameIndex(
2007 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2008 // Fixup to set vararg frame on shadow area (4 x i64).
2010 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2012 // For X86-64, if there are vararg parameters that are passed via
2013 // registers, then we must store them to their spots on the stack so
2014 // they may be loaded by deferencing the result of va_next.
2015 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2016 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2017 FuncInfo->setRegSaveFrameIndex(
2018 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2022 // Store the integer parameter registers.
2023 SmallVector<SDValue, 8> MemOps;
2024 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2026 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2027 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2028 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2029 DAG.getIntPtrConstant(Offset));
2030 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2031 &X86::GR64RegClass);
2032 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2034 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2035 MachinePointerInfo::getFixedStack(
2036 FuncInfo->getRegSaveFrameIndex(), Offset),
2038 MemOps.push_back(Store);
2042 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2043 // Now store the XMM (fp + vector) parameter registers.
2044 SmallVector<SDValue, 11> SaveXMMOps;
2045 SaveXMMOps.push_back(Chain);
2047 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2048 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2049 SaveXMMOps.push_back(ALVal);
2051 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2052 FuncInfo->getRegSaveFrameIndex()));
2053 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2054 FuncInfo->getVarArgsFPOffset()));
2056 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2057 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2058 &X86::VR128RegClass);
2059 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2060 SaveXMMOps.push_back(Val);
2062 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2064 &SaveXMMOps[0], SaveXMMOps.size()));
2067 if (!MemOps.empty())
2068 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2069 &MemOps[0], MemOps.size());
2073 // Some CCs need callee pop.
2074 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2075 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2076 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2078 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2079 // If this is an sret function, the return should pop the hidden pointer.
2080 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2081 argsAreStructReturn(Ins) == StackStructReturn)
2082 FuncInfo->setBytesToPopOnReturn(4);
2086 // RegSaveFrameIndex is X86-64 only.
2087 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2088 if (CallConv == CallingConv::X86_FastCall ||
2089 CallConv == CallingConv::X86_ThisCall)
2090 // fastcc functions can't have varargs.
2091 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2094 FuncInfo->setArgumentStackSize(StackSize);
2100 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2101 SDValue StackPtr, SDValue Arg,
2102 DebugLoc dl, SelectionDAG &DAG,
2103 const CCValAssign &VA,
2104 ISD::ArgFlagsTy Flags) const {
2105 unsigned LocMemOffset = VA.getLocMemOffset();
2106 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2107 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2108 if (Flags.isByVal())
2109 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2111 return DAG.getStore(Chain, dl, Arg, PtrOff,
2112 MachinePointerInfo::getStack(LocMemOffset),
2116 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2117 /// optimization is performed and it is required.
2119 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2120 SDValue &OutRetAddr, SDValue Chain,
2121 bool IsTailCall, bool Is64Bit,
2122 int FPDiff, DebugLoc dl) const {
2123 // Adjust the Return address stack slot.
2124 EVT VT = getPointerTy();
2125 OutRetAddr = getReturnAddressFrameIndex(DAG);
2127 // Load the "old" Return address.
2128 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2129 false, false, false, 0);
2130 return SDValue(OutRetAddr.getNode(), 1);
2133 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2134 /// optimization is performed and it is required (FPDiff!=0).
2136 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2137 SDValue Chain, SDValue RetAddrFrIdx,
2138 bool Is64Bit, int FPDiff, DebugLoc dl) {
2139 // Store the return address to the appropriate stack slot.
2140 if (!FPDiff) return Chain;
2141 // Calculate the new stack slot for the return address.
2142 int SlotSize = Is64Bit ? 8 : 4;
2143 int NewReturnAddrFI =
2144 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2145 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2146 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2147 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2148 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2154 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2155 SmallVectorImpl<SDValue> &InVals) const {
2156 SelectionDAG &DAG = CLI.DAG;
2157 DebugLoc &dl = CLI.DL;
2158 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2159 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2160 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2161 SDValue Chain = CLI.Chain;
2162 SDValue Callee = CLI.Callee;
2163 CallingConv::ID CallConv = CLI.CallConv;
2164 bool &isTailCall = CLI.IsTailCall;
2165 bool isVarArg = CLI.IsVarArg;
2167 MachineFunction &MF = DAG.getMachineFunction();
2168 bool Is64Bit = Subtarget->is64Bit();
2169 bool IsWin64 = Subtarget->isTargetWin64();
2170 bool IsWindows = Subtarget->isTargetWindows();
2171 StructReturnType SR = callIsStructReturn(Outs);
2172 bool IsSibcall = false;
2174 if (MF.getTarget().Options.DisableTailCalls)
2178 // Check if it's really possible to do a tail call.
2179 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2180 isVarArg, SR != NotStructReturn,
2181 MF.getFunction()->hasStructRetAttr(),
2182 Outs, OutVals, Ins, DAG);
2184 // Sibcalls are automatically detected tailcalls which do not require
2186 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2193 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2194 "Var args not supported with calling convention fastcc or ghc");
2196 // Analyze operands of the call, assigning locations to each operand.
2197 SmallVector<CCValAssign, 16> ArgLocs;
2198 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2199 ArgLocs, *DAG.getContext());
2201 // Allocate shadow area for Win64
2203 CCInfo.AllocateStack(32, 8);
2206 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2208 // Get a count of how many bytes are to be pushed on the stack.
2209 unsigned NumBytes = CCInfo.getNextStackOffset();
2211 // This is a sibcall. The memory operands are available in caller's
2212 // own caller's stack.
2214 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2215 IsTailCallConvention(CallConv))
2216 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2219 if (isTailCall && !IsSibcall) {
2220 // Lower arguments at fp - stackoffset + fpdiff.
2221 unsigned NumBytesCallerPushed =
2222 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2223 FPDiff = NumBytesCallerPushed - NumBytes;
2225 // Set the delta of movement of the returnaddr stackslot.
2226 // But only set if delta is greater than previous delta.
2227 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2228 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2232 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2234 SDValue RetAddrFrIdx;
2235 // Load return address for tail calls.
2236 if (isTailCall && FPDiff)
2237 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2238 Is64Bit, FPDiff, dl);
2240 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2241 SmallVector<SDValue, 8> MemOpChains;
2244 // Walk the register/memloc assignments, inserting copies/loads. In the case
2245 // of tail call optimization arguments are handle later.
2246 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2247 CCValAssign &VA = ArgLocs[i];
2248 EVT RegVT = VA.getLocVT();
2249 SDValue Arg = OutVals[i];
2250 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2251 bool isByVal = Flags.isByVal();
2253 // Promote the value if needed.
2254 switch (VA.getLocInfo()) {
2255 default: llvm_unreachable("Unknown loc info!");
2256 case CCValAssign::Full: break;
2257 case CCValAssign::SExt:
2258 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2260 case CCValAssign::ZExt:
2261 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2263 case CCValAssign::AExt:
2264 if (RegVT.is128BitVector()) {
2265 // Special case: passing MMX values in XMM registers.
2266 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2267 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2268 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2270 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2272 case CCValAssign::BCvt:
2273 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2275 case CCValAssign::Indirect: {
2276 // Store the argument.
2277 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2278 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2279 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2280 MachinePointerInfo::getFixedStack(FI),
2287 if (VA.isRegLoc()) {
2288 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2289 if (isVarArg && IsWin64) {
2290 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2291 // shadow reg if callee is a varargs function.
2292 unsigned ShadowReg = 0;
2293 switch (VA.getLocReg()) {
2294 case X86::XMM0: ShadowReg = X86::RCX; break;
2295 case X86::XMM1: ShadowReg = X86::RDX; break;
2296 case X86::XMM2: ShadowReg = X86::R8; break;
2297 case X86::XMM3: ShadowReg = X86::R9; break;
2300 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2302 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2303 assert(VA.isMemLoc());
2304 if (StackPtr.getNode() == 0)
2305 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2306 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2307 dl, DAG, VA, Flags));
2311 if (!MemOpChains.empty())
2312 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2313 &MemOpChains[0], MemOpChains.size());
2315 if (Subtarget->isPICStyleGOT()) {
2316 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2319 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2320 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2322 // If we are tail calling and generating PIC/GOT style code load the
2323 // address of the callee into ECX. The value in ecx is used as target of
2324 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2325 // for tail calls on PIC/GOT architectures. Normally we would just put the
2326 // address of GOT into ebx and then call target@PLT. But for tail calls
2327 // ebx would be restored (since ebx is callee saved) before jumping to the
2330 // Note: The actual moving to ECX is done further down.
2331 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2332 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2333 !G->getGlobal()->hasProtectedVisibility())
2334 Callee = LowerGlobalAddress(Callee, DAG);
2335 else if (isa<ExternalSymbolSDNode>(Callee))
2336 Callee = LowerExternalSymbol(Callee, DAG);
2340 if (Is64Bit && isVarArg && !IsWin64) {
2341 // From AMD64 ABI document:
2342 // For calls that may call functions that use varargs or stdargs
2343 // (prototype-less calls or calls to functions containing ellipsis (...) in
2344 // the declaration) %al is used as hidden argument to specify the number
2345 // of SSE registers used. The contents of %al do not need to match exactly
2346 // the number of registers, but must be an ubound on the number of SSE
2347 // registers used and is in the range 0 - 8 inclusive.
2349 // Count the number of XMM registers allocated.
2350 static const uint16_t XMMArgRegs[] = {
2351 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2352 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2354 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2355 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2356 && "SSE registers cannot be used when SSE is disabled");
2358 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2359 DAG.getConstant(NumXMMRegs, MVT::i8)));
2362 // For tail calls lower the arguments to the 'real' stack slot.
2364 // Force all the incoming stack arguments to be loaded from the stack
2365 // before any new outgoing arguments are stored to the stack, because the
2366 // outgoing stack slots may alias the incoming argument stack slots, and
2367 // the alias isn't otherwise explicit. This is slightly more conservative
2368 // than necessary, because it means that each store effectively depends
2369 // on every argument instead of just those arguments it would clobber.
2370 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2372 SmallVector<SDValue, 8> MemOpChains2;
2375 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2376 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2377 CCValAssign &VA = ArgLocs[i];
2380 assert(VA.isMemLoc());
2381 SDValue Arg = OutVals[i];
2382 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2383 // Create frame index.
2384 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2385 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2386 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2387 FIN = DAG.getFrameIndex(FI, getPointerTy());
2389 if (Flags.isByVal()) {
2390 // Copy relative to framepointer.
2391 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2392 if (StackPtr.getNode() == 0)
2393 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2395 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2397 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2401 // Store relative to framepointer.
2402 MemOpChains2.push_back(
2403 DAG.getStore(ArgChain, dl, Arg, FIN,
2404 MachinePointerInfo::getFixedStack(FI),
2410 if (!MemOpChains2.empty())
2411 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2412 &MemOpChains2[0], MemOpChains2.size());
2414 // Store the return address to the appropriate stack slot.
2415 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2419 // Build a sequence of copy-to-reg nodes chained together with token chain
2420 // and flag operands which copy the outgoing args into registers.
2422 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2423 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2424 RegsToPass[i].second, InFlag);
2425 InFlag = Chain.getValue(1);
2428 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2429 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2430 // In the 64-bit large code model, we have to make all calls
2431 // through a register, since the call instruction's 32-bit
2432 // pc-relative offset may not be large enough to hold the whole
2434 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2435 // If the callee is a GlobalAddress node (quite common, every direct call
2436 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2439 // We should use extra load for direct calls to dllimported functions in
2441 const GlobalValue *GV = G->getGlobal();
2442 if (!GV->hasDLLImportLinkage()) {
2443 unsigned char OpFlags = 0;
2444 bool ExtraLoad = false;
2445 unsigned WrapperKind = ISD::DELETED_NODE;
2447 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2448 // external symbols most go through the PLT in PIC mode. If the symbol
2449 // has hidden or protected visibility, or if it is static or local, then
2450 // we don't need to use the PLT - we can directly call it.
2451 if (Subtarget->isTargetELF() &&
2452 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2453 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2454 OpFlags = X86II::MO_PLT;
2455 } else if (Subtarget->isPICStyleStubAny() &&
2456 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2457 (!Subtarget->getTargetTriple().isMacOSX() ||
2458 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2459 // PC-relative references to external symbols should go through $stub,
2460 // unless we're building with the leopard linker or later, which
2461 // automatically synthesizes these stubs.
2462 OpFlags = X86II::MO_DARWIN_STUB;
2463 } else if (Subtarget->isPICStyleRIPRel() &&
2464 isa<Function>(GV) &&
2465 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2466 // If the function is marked as non-lazy, generate an indirect call
2467 // which loads from the GOT directly. This avoids runtime overhead
2468 // at the cost of eager binding (and one extra byte of encoding).
2469 OpFlags = X86II::MO_GOTPCREL;
2470 WrapperKind = X86ISD::WrapperRIP;
2474 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2475 G->getOffset(), OpFlags);
2477 // Add a wrapper if needed.
2478 if (WrapperKind != ISD::DELETED_NODE)
2479 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2480 // Add extra indirection if needed.
2482 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2483 MachinePointerInfo::getGOT(),
2484 false, false, false, 0);
2486 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2487 unsigned char OpFlags = 0;
2489 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2490 // external symbols should go through the PLT.
2491 if (Subtarget->isTargetELF() &&
2492 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2493 OpFlags = X86II::MO_PLT;
2494 } else if (Subtarget->isPICStyleStubAny() &&
2495 (!Subtarget->getTargetTriple().isMacOSX() ||
2496 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2497 // PC-relative references to external symbols should go through $stub,
2498 // unless we're building with the leopard linker or later, which
2499 // automatically synthesizes these stubs.
2500 OpFlags = X86II::MO_DARWIN_STUB;
2503 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2507 // Returns a chain & a flag for retval copy to use.
2508 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2509 SmallVector<SDValue, 8> Ops;
2511 if (!IsSibcall && isTailCall) {
2512 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2513 DAG.getIntPtrConstant(0, true), InFlag);
2514 InFlag = Chain.getValue(1);
2517 Ops.push_back(Chain);
2518 Ops.push_back(Callee);
2521 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2523 // Add argument registers to the end of the list so that they are known live
2525 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2526 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2527 RegsToPass[i].second.getValueType()));
2529 // Add a register mask operand representing the call-preserved registers.
2530 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2531 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2532 assert(Mask && "Missing call preserved mask for calling convention");
2533 Ops.push_back(DAG.getRegisterMask(Mask));
2535 if (InFlag.getNode())
2536 Ops.push_back(InFlag);
2540 //// If this is the first return lowered for this function, add the regs
2541 //// to the liveout set for the function.
2542 // This isn't right, although it's probably harmless on x86; liveouts
2543 // should be computed from returns not tail calls. Consider a void
2544 // function making a tail call to a function returning int.
2545 return DAG.getNode(X86ISD::TC_RETURN, dl,
2546 NodeTys, &Ops[0], Ops.size());
2549 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2550 InFlag = Chain.getValue(1);
2552 // Create the CALLSEQ_END node.
2553 unsigned NumBytesForCalleeToPush;
2554 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2555 getTargetMachine().Options.GuaranteedTailCallOpt))
2556 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2557 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2558 SR == StackStructReturn)
2559 // If this is a call to a struct-return function, the callee
2560 // pops the hidden struct pointer, so we have to push it back.
2561 // This is common for Darwin/X86, Linux & Mingw32 targets.
2562 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2563 NumBytesForCalleeToPush = 4;
2565 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2567 // Returns a flag for retval copy to use.
2569 Chain = DAG.getCALLSEQ_END(Chain,
2570 DAG.getIntPtrConstant(NumBytes, true),
2571 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2574 InFlag = Chain.getValue(1);
2577 // Handle result values, copying them out of physregs into vregs that we
2579 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2580 Ins, dl, DAG, InVals);
2584 //===----------------------------------------------------------------------===//
2585 // Fast Calling Convention (tail call) implementation
2586 //===----------------------------------------------------------------------===//
2588 // Like std call, callee cleans arguments, convention except that ECX is
2589 // reserved for storing the tail called function address. Only 2 registers are
2590 // free for argument passing (inreg). Tail call optimization is performed
2592 // * tailcallopt is enabled
2593 // * caller/callee are fastcc
2594 // On X86_64 architecture with GOT-style position independent code only local
2595 // (within module) calls are supported at the moment.
2596 // To keep the stack aligned according to platform abi the function
2597 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2598 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2599 // If a tail called function callee has more arguments than the caller the
2600 // caller needs to make sure that there is room to move the RETADDR to. This is
2601 // achieved by reserving an area the size of the argument delta right after the
2602 // original REtADDR, but before the saved framepointer or the spilled registers
2603 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2615 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2616 /// for a 16 byte align requirement.
2618 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2619 SelectionDAG& DAG) const {
2620 MachineFunction &MF = DAG.getMachineFunction();
2621 const TargetMachine &TM = MF.getTarget();
2622 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2623 unsigned StackAlignment = TFI.getStackAlignment();
2624 uint64_t AlignMask = StackAlignment - 1;
2625 int64_t Offset = StackSize;
2626 uint64_t SlotSize = TD->getPointerSize();
2627 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2628 // Number smaller than 12 so just add the difference.
2629 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2631 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2632 Offset = ((~AlignMask) & Offset) + StackAlignment +
2633 (StackAlignment-SlotSize);
2638 /// MatchingStackOffset - Return true if the given stack call argument is
2639 /// already available in the same position (relatively) of the caller's
2640 /// incoming argument stack.
2642 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2643 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2644 const X86InstrInfo *TII) {
2645 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2647 if (Arg.getOpcode() == ISD::CopyFromReg) {
2648 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2649 if (!TargetRegisterInfo::isVirtualRegister(VR))
2651 MachineInstr *Def = MRI->getVRegDef(VR);
2654 if (!Flags.isByVal()) {
2655 if (!TII->isLoadFromStackSlot(Def, FI))
2658 unsigned Opcode = Def->getOpcode();
2659 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2660 Def->getOperand(1).isFI()) {
2661 FI = Def->getOperand(1).getIndex();
2662 Bytes = Flags.getByValSize();
2666 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2667 if (Flags.isByVal())
2668 // ByVal argument is passed in as a pointer but it's now being
2669 // dereferenced. e.g.
2670 // define @foo(%struct.X* %A) {
2671 // tail call @bar(%struct.X* byval %A)
2674 SDValue Ptr = Ld->getBasePtr();
2675 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2678 FI = FINode->getIndex();
2679 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2680 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2681 FI = FINode->getIndex();
2682 Bytes = Flags.getByValSize();
2686 assert(FI != INT_MAX);
2687 if (!MFI->isFixedObjectIndex(FI))
2689 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2692 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2693 /// for tail call optimization. Targets which want to do tail call
2694 /// optimization should implement this function.
2696 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2697 CallingConv::ID CalleeCC,
2699 bool isCalleeStructRet,
2700 bool isCallerStructRet,
2701 const SmallVectorImpl<ISD::OutputArg> &Outs,
2702 const SmallVectorImpl<SDValue> &OutVals,
2703 const SmallVectorImpl<ISD::InputArg> &Ins,
2704 SelectionDAG& DAG) const {
2705 if (!IsTailCallConvention(CalleeCC) &&
2706 CalleeCC != CallingConv::C)
2709 // If -tailcallopt is specified, make fastcc functions tail-callable.
2710 const MachineFunction &MF = DAG.getMachineFunction();
2711 const Function *CallerF = DAG.getMachineFunction().getFunction();
2712 CallingConv::ID CallerCC = CallerF->getCallingConv();
2713 bool CCMatch = CallerCC == CalleeCC;
2715 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2716 if (IsTailCallConvention(CalleeCC) && CCMatch)
2721 // Look for obvious safe cases to perform tail call optimization that do not
2722 // require ABI changes. This is what gcc calls sibcall.
2724 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2725 // emit a special epilogue.
2726 if (RegInfo->needsStackRealignment(MF))
2729 // Also avoid sibcall optimization if either caller or callee uses struct
2730 // return semantics.
2731 if (isCalleeStructRet || isCallerStructRet)
2734 // An stdcall caller is expected to clean up its arguments; the callee
2735 // isn't going to do that.
2736 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2739 // Do not sibcall optimize vararg calls unless all arguments are passed via
2741 if (isVarArg && !Outs.empty()) {
2743 // Optimizing for varargs on Win64 is unlikely to be safe without
2744 // additional testing.
2745 if (Subtarget->isTargetWin64())
2748 SmallVector<CCValAssign, 16> ArgLocs;
2749 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2750 getTargetMachine(), ArgLocs, *DAG.getContext());
2752 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2753 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2754 if (!ArgLocs[i].isRegLoc())
2758 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2759 // stack. Therefore, if it's not used by the call it is not safe to optimize
2760 // this into a sibcall.
2761 bool Unused = false;
2762 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2769 SmallVector<CCValAssign, 16> RVLocs;
2770 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2771 getTargetMachine(), RVLocs, *DAG.getContext());
2772 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2773 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2774 CCValAssign &VA = RVLocs[i];
2775 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2780 // If the calling conventions do not match, then we'd better make sure the
2781 // results are returned in the same way as what the caller expects.
2783 SmallVector<CCValAssign, 16> RVLocs1;
2784 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2785 getTargetMachine(), RVLocs1, *DAG.getContext());
2786 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2788 SmallVector<CCValAssign, 16> RVLocs2;
2789 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2790 getTargetMachine(), RVLocs2, *DAG.getContext());
2791 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2793 if (RVLocs1.size() != RVLocs2.size())
2795 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2796 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2798 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2800 if (RVLocs1[i].isRegLoc()) {
2801 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2804 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2810 // If the callee takes no arguments then go on to check the results of the
2812 if (!Outs.empty()) {
2813 // Check if stack adjustment is needed. For now, do not do this if any
2814 // argument is passed on the stack.
2815 SmallVector<CCValAssign, 16> ArgLocs;
2816 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2817 getTargetMachine(), ArgLocs, *DAG.getContext());
2819 // Allocate shadow area for Win64
2820 if (Subtarget->isTargetWin64()) {
2821 CCInfo.AllocateStack(32, 8);
2824 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2825 if (CCInfo.getNextStackOffset()) {
2826 MachineFunction &MF = DAG.getMachineFunction();
2827 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2830 // Check if the arguments are already laid out in the right way as
2831 // the caller's fixed stack objects.
2832 MachineFrameInfo *MFI = MF.getFrameInfo();
2833 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2834 const X86InstrInfo *TII =
2835 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2836 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2837 CCValAssign &VA = ArgLocs[i];
2838 SDValue Arg = OutVals[i];
2839 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2840 if (VA.getLocInfo() == CCValAssign::Indirect)
2842 if (!VA.isRegLoc()) {
2843 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2850 // If the tailcall address may be in a register, then make sure it's
2851 // possible to register allocate for it. In 32-bit, the call address can
2852 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2853 // callee-saved registers are restored. These happen to be the same
2854 // registers used to pass 'inreg' arguments so watch out for those.
2855 if (!Subtarget->is64Bit() &&
2856 !isa<GlobalAddressSDNode>(Callee) &&
2857 !isa<ExternalSymbolSDNode>(Callee)) {
2858 unsigned NumInRegs = 0;
2859 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2860 CCValAssign &VA = ArgLocs[i];
2863 unsigned Reg = VA.getLocReg();
2866 case X86::EAX: case X86::EDX: case X86::ECX:
2867 if (++NumInRegs == 3)
2879 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2880 const TargetLibraryInfo *libInfo) const {
2881 return X86::createFastISel(funcInfo, libInfo);
2885 //===----------------------------------------------------------------------===//
2886 // Other Lowering Hooks
2887 //===----------------------------------------------------------------------===//
2889 static bool MayFoldLoad(SDValue Op) {
2890 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2893 static bool MayFoldIntoStore(SDValue Op) {
2894 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2897 static bool isTargetShuffle(unsigned Opcode) {
2899 default: return false;
2900 case X86ISD::PSHUFD:
2901 case X86ISD::PSHUFHW:
2902 case X86ISD::PSHUFLW:
2904 case X86ISD::PALIGN:
2905 case X86ISD::MOVLHPS:
2906 case X86ISD::MOVLHPD:
2907 case X86ISD::MOVHLPS:
2908 case X86ISD::MOVLPS:
2909 case X86ISD::MOVLPD:
2910 case X86ISD::MOVSHDUP:
2911 case X86ISD::MOVSLDUP:
2912 case X86ISD::MOVDDUP:
2915 case X86ISD::UNPCKL:
2916 case X86ISD::UNPCKH:
2917 case X86ISD::VPERMILP:
2918 case X86ISD::VPERM2X128:
2919 case X86ISD::VPERMI:
2924 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2925 SDValue V1, SelectionDAG &DAG) {
2927 default: llvm_unreachable("Unknown x86 shuffle node");
2928 case X86ISD::MOVSHDUP:
2929 case X86ISD::MOVSLDUP:
2930 case X86ISD::MOVDDUP:
2931 return DAG.getNode(Opc, dl, VT, V1);
2935 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2936 SDValue V1, unsigned TargetMask,
2937 SelectionDAG &DAG) {
2939 default: llvm_unreachable("Unknown x86 shuffle node");
2940 case X86ISD::PSHUFD:
2941 case X86ISD::PSHUFHW:
2942 case X86ISD::PSHUFLW:
2943 case X86ISD::VPERMILP:
2944 case X86ISD::VPERMI:
2945 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2949 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2950 SDValue V1, SDValue V2, unsigned TargetMask,
2951 SelectionDAG &DAG) {
2953 default: llvm_unreachable("Unknown x86 shuffle node");
2954 case X86ISD::PALIGN:
2956 case X86ISD::VPERM2X128:
2957 return DAG.getNode(Opc, dl, VT, V1, V2,
2958 DAG.getConstant(TargetMask, MVT::i8));
2962 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2963 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2965 default: llvm_unreachable("Unknown x86 shuffle node");
2966 case X86ISD::MOVLHPS:
2967 case X86ISD::MOVLHPD:
2968 case X86ISD::MOVHLPS:
2969 case X86ISD::MOVLPS:
2970 case X86ISD::MOVLPD:
2973 case X86ISD::UNPCKL:
2974 case X86ISD::UNPCKH:
2975 return DAG.getNode(Opc, dl, VT, V1, V2);
2979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2980 MachineFunction &MF = DAG.getMachineFunction();
2981 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2982 int ReturnAddrIndex = FuncInfo->getRAIndex();
2984 if (ReturnAddrIndex == 0) {
2985 // Set up a frame object for the return address.
2986 uint64_t SlotSize = TD->getPointerSize();
2987 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2989 FuncInfo->setRAIndex(ReturnAddrIndex);
2992 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2996 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2997 bool hasSymbolicDisplacement) {
2998 // Offset should fit into 32 bit immediate field.
2999 if (!isInt<32>(Offset))
3002 // If we don't have a symbolic displacement - we don't have any extra
3004 if (!hasSymbolicDisplacement)
3007 // FIXME: Some tweaks might be needed for medium code model.
3008 if (M != CodeModel::Small && M != CodeModel::Kernel)
3011 // For small code model we assume that latest object is 16MB before end of 31
3012 // bits boundary. We may also accept pretty large negative constants knowing
3013 // that all objects are in the positive half of address space.
3014 if (M == CodeModel::Small && Offset < 16*1024*1024)
3017 // For kernel code model we know that all object resist in the negative half
3018 // of 32bits address space. We may not accept negative offsets, since they may
3019 // be just off and we may accept pretty large positive ones.
3020 if (M == CodeModel::Kernel && Offset > 0)
3026 /// isCalleePop - Determines whether the callee is required to pop its
3027 /// own arguments. Callee pop is necessary to support tail calls.
3028 bool X86::isCalleePop(CallingConv::ID CallingConv,
3029 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3033 switch (CallingConv) {
3036 case CallingConv::X86_StdCall:
3038 case CallingConv::X86_FastCall:
3040 case CallingConv::X86_ThisCall:
3042 case CallingConv::Fast:
3044 case CallingConv::GHC:
3049 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3050 /// specific condition code, returning the condition code and the LHS/RHS of the
3051 /// comparison to make.
3052 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3053 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3055 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3056 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3057 // X > -1 -> X == 0, jump !sign.
3058 RHS = DAG.getConstant(0, RHS.getValueType());
3059 return X86::COND_NS;
3061 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3062 // X < 0 -> X == 0, jump on sign.
3065 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3067 RHS = DAG.getConstant(0, RHS.getValueType());
3068 return X86::COND_LE;
3072 switch (SetCCOpcode) {
3073 default: llvm_unreachable("Invalid integer condition!");
3074 case ISD::SETEQ: return X86::COND_E;
3075 case ISD::SETGT: return X86::COND_G;
3076 case ISD::SETGE: return X86::COND_GE;
3077 case ISD::SETLT: return X86::COND_L;
3078 case ISD::SETLE: return X86::COND_LE;
3079 case ISD::SETNE: return X86::COND_NE;
3080 case ISD::SETULT: return X86::COND_B;
3081 case ISD::SETUGT: return X86::COND_A;
3082 case ISD::SETULE: return X86::COND_BE;
3083 case ISD::SETUGE: return X86::COND_AE;
3087 // First determine if it is required or is profitable to flip the operands.
3089 // If LHS is a foldable load, but RHS is not, flip the condition.
3090 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3091 !ISD::isNON_EXTLoad(RHS.getNode())) {
3092 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3093 std::swap(LHS, RHS);
3096 switch (SetCCOpcode) {
3102 std::swap(LHS, RHS);
3106 // On a floating point condition, the flags are set as follows:
3108 // 0 | 0 | 0 | X > Y
3109 // 0 | 0 | 1 | X < Y
3110 // 1 | 0 | 0 | X == Y
3111 // 1 | 1 | 1 | unordered
3112 switch (SetCCOpcode) {
3113 default: llvm_unreachable("Condcode should be pre-legalized away");
3115 case ISD::SETEQ: return X86::COND_E;
3116 case ISD::SETOLT: // flipped
3118 case ISD::SETGT: return X86::COND_A;
3119 case ISD::SETOLE: // flipped
3121 case ISD::SETGE: return X86::COND_AE;
3122 case ISD::SETUGT: // flipped
3124 case ISD::SETLT: return X86::COND_B;
3125 case ISD::SETUGE: // flipped
3127 case ISD::SETLE: return X86::COND_BE;
3129 case ISD::SETNE: return X86::COND_NE;
3130 case ISD::SETUO: return X86::COND_P;
3131 case ISD::SETO: return X86::COND_NP;
3133 case ISD::SETUNE: return X86::COND_INVALID;
3137 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3138 /// code. Current x86 isa includes the following FP cmov instructions:
3139 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3140 static bool hasFPCMov(unsigned X86CC) {
3156 /// isFPImmLegal - Returns true if the target can instruction select the
3157 /// specified FP immediate natively. If false, the legalizer will
3158 /// materialize the FP immediate as a load from a constant pool.
3159 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3160 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3161 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3167 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3168 /// the specified range (L, H].
3169 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3170 return (Val < 0) || (Val >= Low && Val < Hi);
3173 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3174 /// specified value.
3175 static bool isUndefOrEqual(int Val, int CmpVal) {
3176 if (Val < 0 || Val == CmpVal)
3181 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3182 /// from position Pos and ending in Pos+Size, falls within the specified
3183 /// sequential range (L, L+Pos]. or is undef.
3184 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3185 unsigned Pos, unsigned Size, int Low) {
3186 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3187 if (!isUndefOrEqual(Mask[i], Low))
3192 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3193 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3194 /// the second operand.
3195 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3196 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3197 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3198 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3199 return (Mask[0] < 2 && Mask[1] < 2);
3203 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3204 /// is suitable for input to PSHUFHW.
3205 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3206 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3209 // Lower quadword copied in order or undef.
3210 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3213 // Upper quadword shuffled.
3214 for (unsigned i = 4; i != 8; ++i)
3215 if (!isUndefOrInRange(Mask[i], 4, 8))
3218 if (VT == MVT::v16i16) {
3219 // Lower quadword copied in order or undef.
3220 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3223 // Upper quadword shuffled.
3224 for (unsigned i = 12; i != 16; ++i)
3225 if (!isUndefOrInRange(Mask[i], 12, 16))
3232 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3233 /// is suitable for input to PSHUFLW.
3234 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3235 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3238 // Upper quadword copied in order.
3239 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3242 // Lower quadword shuffled.
3243 for (unsigned i = 0; i != 4; ++i)
3244 if (!isUndefOrInRange(Mask[i], 0, 4))
3247 if (VT == MVT::v16i16) {
3248 // Upper quadword copied in order.
3249 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3252 // Lower quadword shuffled.
3253 for (unsigned i = 8; i != 12; ++i)
3254 if (!isUndefOrInRange(Mask[i], 8, 12))
3261 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3262 /// is suitable for input to PALIGNR.
3263 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3264 const X86Subtarget *Subtarget) {
3265 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3266 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3269 unsigned NumElts = VT.getVectorNumElements();
3270 unsigned NumLanes = VT.getSizeInBits()/128;
3271 unsigned NumLaneElts = NumElts/NumLanes;
3273 // Do not handle 64-bit element shuffles with palignr.
3274 if (NumLaneElts == 2)
3277 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3279 for (i = 0; i != NumLaneElts; ++i) {
3284 // Lane is all undef, go to next lane
3285 if (i == NumLaneElts)
3288 int Start = Mask[i+l];
3290 // Make sure its in this lane in one of the sources
3291 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3292 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3295 // If not lane 0, then we must match lane 0
3296 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3299 // Correct second source to be contiguous with first source
3300 if (Start >= (int)NumElts)
3301 Start -= NumElts - NumLaneElts;
3303 // Make sure we're shifting in the right direction.
3304 if (Start <= (int)(i+l))
3309 // Check the rest of the elements to see if they are consecutive.
3310 for (++i; i != NumLaneElts; ++i) {
3311 int Idx = Mask[i+l];
3313 // Make sure its in this lane
3314 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3315 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3318 // If not lane 0, then we must match lane 0
3319 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3322 if (Idx >= (int)NumElts)
3323 Idx -= NumElts - NumLaneElts;
3325 if (!isUndefOrEqual(Idx, Start+i))
3334 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3335 /// the two vector operands have swapped position.
3336 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3337 unsigned NumElems) {
3338 for (unsigned i = 0; i != NumElems; ++i) {
3342 else if (idx < (int)NumElems)
3343 Mask[i] = idx + NumElems;
3345 Mask[i] = idx - NumElems;
3349 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3350 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3351 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3352 /// reverse of what x86 shuffles want.
3353 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3354 bool Commuted = false) {
3355 if (!HasAVX && VT.getSizeInBits() == 256)
3358 unsigned NumElems = VT.getVectorNumElements();
3359 unsigned NumLanes = VT.getSizeInBits()/128;
3360 unsigned NumLaneElems = NumElems/NumLanes;
3362 if (NumLaneElems != 2 && NumLaneElems != 4)
3365 // VSHUFPSY divides the resulting vector into 4 chunks.
3366 // The sources are also splitted into 4 chunks, and each destination
3367 // chunk must come from a different source chunk.
3369 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3370 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3372 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3373 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3375 // VSHUFPDY divides the resulting vector into 4 chunks.
3376 // The sources are also splitted into 4 chunks, and each destination
3377 // chunk must come from a different source chunk.
3379 // SRC1 => X3 X2 X1 X0
3380 // SRC2 => Y3 Y2 Y1 Y0
3382 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3384 unsigned HalfLaneElems = NumLaneElems/2;
3385 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3386 for (unsigned i = 0; i != NumLaneElems; ++i) {
3387 int Idx = Mask[i+l];
3388 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3389 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3391 // For VSHUFPSY, the mask of the second half must be the same as the
3392 // first but with the appropriate offsets. This works in the same way as
3393 // VPERMILPS works with masks.
3394 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3396 if (!isUndefOrEqual(Idx, Mask[i]+l))
3404 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3405 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3406 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3407 if (!VT.is128BitVector())
3410 unsigned NumElems = VT.getVectorNumElements();
3415 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3416 return isUndefOrEqual(Mask[0], 6) &&
3417 isUndefOrEqual(Mask[1], 7) &&
3418 isUndefOrEqual(Mask[2], 2) &&
3419 isUndefOrEqual(Mask[3], 3);
3422 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3423 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3425 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3426 if (!VT.is128BitVector())
3429 unsigned NumElems = VT.getVectorNumElements();
3434 return isUndefOrEqual(Mask[0], 2) &&
3435 isUndefOrEqual(Mask[1], 3) &&
3436 isUndefOrEqual(Mask[2], 2) &&
3437 isUndefOrEqual(Mask[3], 3);
3440 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3442 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3443 if (!VT.is128BitVector())
3446 unsigned NumElems = VT.getVectorNumElements();
3448 if (NumElems != 2 && NumElems != 4)
3451 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3452 if (!isUndefOrEqual(Mask[i], i + NumElems))
3455 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3456 if (!isUndefOrEqual(Mask[i], i))
3462 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3463 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3464 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3465 if (!VT.is128BitVector())
3468 unsigned NumElems = VT.getVectorNumElements();
3470 if (NumElems != 2 && NumElems != 4)
3473 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3474 if (!isUndefOrEqual(Mask[i], i))
3477 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3478 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3485 // Some special combinations that can be optimized.
3488 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3489 SelectionDAG &DAG) {
3490 EVT VT = SVOp->getValueType(0);
3491 DebugLoc dl = SVOp->getDebugLoc();
3493 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3496 ArrayRef<int> Mask = SVOp->getMask();
3498 // These are the special masks that may be optimized.
3499 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3500 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3501 bool MatchEvenMask = true;
3502 bool MatchOddMask = true;
3503 for (int i=0; i<8; ++i) {
3504 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3505 MatchEvenMask = false;
3506 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3507 MatchOddMask = false;
3509 static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3510 static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3512 const int *CompactionMask;
3514 CompactionMask = CompactionMaskEven;
3515 else if (MatchOddMask)
3516 CompactionMask = CompactionMaskOdd;
3520 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3522 SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3523 UndefNode, CompactionMask);
3524 SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3525 UndefNode, CompactionMask);
3526 static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3527 return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3530 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3531 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3532 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3533 bool HasAVX2, bool V2IsSplat = false) {
3534 unsigned NumElts = VT.getVectorNumElements();
3536 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3537 "Unsupported vector type for unpckh");
3539 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3540 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3543 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3544 // independently on 128-bit lanes.
3545 unsigned NumLanes = VT.getSizeInBits()/128;
3546 unsigned NumLaneElts = NumElts/NumLanes;
3548 for (unsigned l = 0; l != NumLanes; ++l) {
3549 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3550 i != (l+1)*NumLaneElts;
3553 int BitI1 = Mask[i+1];
3554 if (!isUndefOrEqual(BitI, j))
3557 if (!isUndefOrEqual(BitI1, NumElts))
3560 if (!isUndefOrEqual(BitI1, j + NumElts))
3569 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3570 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3571 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3572 bool HasAVX2, bool V2IsSplat = false) {
3573 unsigned NumElts = VT.getVectorNumElements();
3575 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3576 "Unsupported vector type for unpckh");
3578 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3579 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3582 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3583 // independently on 128-bit lanes.
3584 unsigned NumLanes = VT.getSizeInBits()/128;
3585 unsigned NumLaneElts = NumElts/NumLanes;
3587 for (unsigned l = 0; l != NumLanes; ++l) {
3588 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3589 i != (l+1)*NumLaneElts; i += 2, ++j) {
3591 int BitI1 = Mask[i+1];
3592 if (!isUndefOrEqual(BitI, j))
3595 if (isUndefOrEqual(BitI1, NumElts))
3598 if (!isUndefOrEqual(BitI1, j+NumElts))
3606 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3607 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3609 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3611 unsigned NumElts = VT.getVectorNumElements();
3613 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3614 "Unsupported vector type for unpckh");
3616 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3617 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3620 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3621 // FIXME: Need a better way to get rid of this, there's no latency difference
3622 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3623 // the former later. We should also remove the "_undef" special mask.
3624 if (NumElts == 4 && VT.getSizeInBits() == 256)
3627 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3628 // independently on 128-bit lanes.
3629 unsigned NumLanes = VT.getSizeInBits()/128;
3630 unsigned NumLaneElts = NumElts/NumLanes;
3632 for (unsigned l = 0; l != NumLanes; ++l) {
3633 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3634 i != (l+1)*NumLaneElts;
3637 int BitI1 = Mask[i+1];
3639 if (!isUndefOrEqual(BitI, j))
3641 if (!isUndefOrEqual(BitI1, j))
3649 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3650 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3652 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3653 unsigned NumElts = VT.getVectorNumElements();
3655 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3656 "Unsupported vector type for unpckh");
3658 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3659 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3662 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3663 // independently on 128-bit lanes.
3664 unsigned NumLanes = VT.getSizeInBits()/128;
3665 unsigned NumLaneElts = NumElts/NumLanes;
3667 for (unsigned l = 0; l != NumLanes; ++l) {
3668 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3669 i != (l+1)*NumLaneElts; i += 2, ++j) {
3671 int BitI1 = Mask[i+1];
3672 if (!isUndefOrEqual(BitI, j))
3674 if (!isUndefOrEqual(BitI1, j))
3681 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3682 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3683 /// MOVSD, and MOVD, i.e. setting the lowest element.
3684 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3685 if (VT.getVectorElementType().getSizeInBits() < 32)
3687 if (!VT.is128BitVector())
3690 unsigned NumElts = VT.getVectorNumElements();
3692 if (!isUndefOrEqual(Mask[0], NumElts))
3695 for (unsigned i = 1; i != NumElts; ++i)
3696 if (!isUndefOrEqual(Mask[i], i))
3702 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3703 /// as permutations between 128-bit chunks or halves. As an example: this
3705 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3706 /// The first half comes from the second half of V1 and the second half from the
3707 /// the second half of V2.
3708 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3709 if (!HasAVX || !VT.is256BitVector())
3712 // The shuffle result is divided into half A and half B. In total the two
3713 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3714 // B must come from C, D, E or F.
3715 unsigned HalfSize = VT.getVectorNumElements()/2;
3716 bool MatchA = false, MatchB = false;
3718 // Check if A comes from one of C, D, E, F.
3719 for (unsigned Half = 0; Half != 4; ++Half) {
3720 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3726 // Check if B comes from one of C, D, E, F.
3727 for (unsigned Half = 0; Half != 4; ++Half) {
3728 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3734 return MatchA && MatchB;
3737 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3738 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3739 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3740 EVT VT = SVOp->getValueType(0);
3742 unsigned HalfSize = VT.getVectorNumElements()/2;
3744 unsigned FstHalf = 0, SndHalf = 0;
3745 for (unsigned i = 0; i < HalfSize; ++i) {
3746 if (SVOp->getMaskElt(i) > 0) {
3747 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3751 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3752 if (SVOp->getMaskElt(i) > 0) {
3753 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3758 return (FstHalf | (SndHalf << 4));
3761 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3762 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3763 /// Note that VPERMIL mask matching is different depending whether theunderlying
3764 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3765 /// to the same elements of the low, but to the higher half of the source.
3766 /// In VPERMILPD the two lanes could be shuffled independently of each other
3767 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3768 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3772 unsigned NumElts = VT.getVectorNumElements();
3773 // Only match 256-bit with 32/64-bit types
3774 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3777 unsigned NumLanes = VT.getSizeInBits()/128;
3778 unsigned LaneSize = NumElts/NumLanes;
3779 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3780 for (unsigned i = 0; i != LaneSize; ++i) {
3781 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3783 if (NumElts != 8 || l == 0)
3785 // VPERMILPS handling
3788 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3796 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3797 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3798 /// element of vector 2 and the other elements to come from vector 1 in order.
3799 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3800 bool V2IsSplat = false, bool V2IsUndef = false) {
3801 if (!VT.is128BitVector())
3804 unsigned NumOps = VT.getVectorNumElements();
3805 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3808 if (!isUndefOrEqual(Mask[0], 0))
3811 for (unsigned i = 1; i != NumOps; ++i)
3812 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3813 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3814 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3820 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3821 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3822 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3823 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3824 const X86Subtarget *Subtarget) {
3825 if (!Subtarget->hasSSE3())
3828 unsigned NumElems = VT.getVectorNumElements();
3830 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3831 (VT.getSizeInBits() == 256 && NumElems != 8))
3834 // "i+1" is the value the indexed mask element must have
3835 for (unsigned i = 0; i != NumElems; i += 2)
3836 if (!isUndefOrEqual(Mask[i], i+1) ||
3837 !isUndefOrEqual(Mask[i+1], i+1))
3843 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3844 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3845 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3846 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3847 const X86Subtarget *Subtarget) {
3848 if (!Subtarget->hasSSE3())
3851 unsigned NumElems = VT.getVectorNumElements();
3853 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3854 (VT.getSizeInBits() == 256 && NumElems != 8))
3857 // "i" is the value the indexed mask element must have
3858 for (unsigned i = 0; i != NumElems; i += 2)
3859 if (!isUndefOrEqual(Mask[i], i) ||
3860 !isUndefOrEqual(Mask[i+1], i))
3866 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to 256-bit
3868 /// version of MOVDDUP.
3869 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3870 if (!HasAVX || !VT.is256BitVector())
3873 unsigned NumElts = VT.getVectorNumElements();
3877 for (unsigned i = 0; i != NumElts/2; ++i)
3878 if (!isUndefOrEqual(Mask[i], 0))
3880 for (unsigned i = NumElts/2; i != NumElts; ++i)
3881 if (!isUndefOrEqual(Mask[i], NumElts/2))
3886 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3887 /// specifies a shuffle of elements that is suitable for input to 128-bit
3888 /// version of MOVDDUP.
3889 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3890 if (!VT.is128BitVector())
3893 unsigned e = VT.getVectorNumElements() / 2;
3894 for (unsigned i = 0; i != e; ++i)
3895 if (!isUndefOrEqual(Mask[i], i))
3897 for (unsigned i = 0; i != e; ++i)
3898 if (!isUndefOrEqual(Mask[e+i], i))
3903 /// isVEXTRACTF128Index - Return true if the specified
3904 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3905 /// suitable for input to VEXTRACTF128.
3906 bool X86::isVEXTRACTF128Index(SDNode *N) {
3907 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3910 // The index should be aligned on a 128-bit boundary.
3912 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3914 unsigned VL = N->getValueType(0).getVectorNumElements();
3915 unsigned VBits = N->getValueType(0).getSizeInBits();
3916 unsigned ElSize = VBits / VL;
3917 bool Result = (Index * ElSize) % 128 == 0;
3922 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3923 /// operand specifies a subvector insert that is suitable for input to
3925 bool X86::isVINSERTF128Index(SDNode *N) {
3926 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3929 // The index should be aligned on a 128-bit boundary.
3931 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3933 unsigned VL = N->getValueType(0).getVectorNumElements();
3934 unsigned VBits = N->getValueType(0).getSizeInBits();
3935 unsigned ElSize = VBits / VL;
3936 bool Result = (Index * ElSize) % 128 == 0;
3941 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3942 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3943 /// Handles 128-bit and 256-bit.
3944 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3945 EVT VT = N->getValueType(0);
3947 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3948 "Unsupported vector type for PSHUF/SHUFP");
3950 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3951 // independently on 128-bit lanes.
3952 unsigned NumElts = VT.getVectorNumElements();
3953 unsigned NumLanes = VT.getSizeInBits()/128;
3954 unsigned NumLaneElts = NumElts/NumLanes;
3956 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3957 "Only supports 2 or 4 elements per lane");
3959 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3961 for (unsigned i = 0; i != NumElts; ++i) {
3962 int Elt = N->getMaskElt(i);
3963 if (Elt < 0) continue;
3964 Elt &= NumLaneElts - 1;
3965 unsigned ShAmt = (i << Shift) % 8;
3966 Mask |= Elt << ShAmt;
3972 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3973 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3974 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3975 EVT VT = N->getValueType(0);
3977 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3978 "Unsupported vector type for PSHUFHW");
3980 unsigned NumElts = VT.getVectorNumElements();
3983 for (unsigned l = 0; l != NumElts; l += 8) {
3984 // 8 nodes per lane, but we only care about the last 4.
3985 for (unsigned i = 0; i < 4; ++i) {
3986 int Elt = N->getMaskElt(l+i+4);
3987 if (Elt < 0) continue;
3988 Elt &= 0x3; // only 2-bits.
3989 Mask |= Elt << (i * 2);
3996 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3997 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3998 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3999 EVT VT = N->getValueType(0);
4001 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4002 "Unsupported vector type for PSHUFHW");
4004 unsigned NumElts = VT.getVectorNumElements();
4007 for (unsigned l = 0; l != NumElts; l += 8) {
4008 // 8 nodes per lane, but we only care about the first 4.
4009 for (unsigned i = 0; i < 4; ++i) {
4010 int Elt = N->getMaskElt(l+i);
4011 if (Elt < 0) continue;
4012 Elt &= 0x3; // only 2-bits
4013 Mask |= Elt << (i * 2);
4020 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4021 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4022 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4023 EVT VT = SVOp->getValueType(0);
4024 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4026 unsigned NumElts = VT.getVectorNumElements();
4027 unsigned NumLanes = VT.getSizeInBits()/128;
4028 unsigned NumLaneElts = NumElts/NumLanes;
4032 for (i = 0; i != NumElts; ++i) {
4033 Val = SVOp->getMaskElt(i);
4037 if (Val >= (int)NumElts)
4038 Val -= NumElts - NumLaneElts;
4040 assert(Val - i > 0 && "PALIGNR imm should be positive");
4041 return (Val - i) * EltSize;
4044 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4045 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4047 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4048 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4049 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4052 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4054 EVT VecVT = N->getOperand(0).getValueType();
4055 EVT ElVT = VecVT.getVectorElementType();
4057 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4058 return Index / NumElemsPerChunk;
4061 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4062 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4064 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4065 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4066 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4069 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4071 EVT VecVT = N->getValueType(0);
4072 EVT ElVT = VecVT.getVectorElementType();
4074 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4075 return Index / NumElemsPerChunk;
4078 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4079 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4080 /// Handles 256-bit.
4081 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4082 EVT VT = N->getValueType(0);
4084 unsigned NumElts = VT.getVectorNumElements();
4086 assert((VT.is256BitVector() && NumElts == 4) &&
4087 "Unsupported vector type for VPERMQ/VPERMPD");
4090 for (unsigned i = 0; i != NumElts; ++i) {
4091 int Elt = N->getMaskElt(i);
4094 Mask |= Elt << (i*2);
4099 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4101 bool X86::isZeroNode(SDValue Elt) {
4102 return ((isa<ConstantSDNode>(Elt) &&
4103 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4104 (isa<ConstantFPSDNode>(Elt) &&
4105 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4108 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4109 /// their permute mask.
4110 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4111 SelectionDAG &DAG) {
4112 EVT VT = SVOp->getValueType(0);
4113 unsigned NumElems = VT.getVectorNumElements();
4114 SmallVector<int, 8> MaskVec;
4116 for (unsigned i = 0; i != NumElems; ++i) {
4117 int Idx = SVOp->getMaskElt(i);
4119 if (Idx < (int)NumElems)
4124 MaskVec.push_back(Idx);
4126 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4127 SVOp->getOperand(0), &MaskVec[0]);
4130 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4131 /// match movhlps. The lower half elements should come from upper half of
4132 /// V1 (and in order), and the upper half elements should come from the upper
4133 /// half of V2 (and in order).
4134 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4135 if (!VT.is128BitVector())
4137 if (VT.getVectorNumElements() != 4)
4139 for (unsigned i = 0, e = 2; i != e; ++i)
4140 if (!isUndefOrEqual(Mask[i], i+2))
4142 for (unsigned i = 2; i != 4; ++i)
4143 if (!isUndefOrEqual(Mask[i], i+4))
4148 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4149 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4151 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4152 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4154 N = N->getOperand(0).getNode();
4155 if (!ISD::isNON_EXTLoad(N))
4158 *LD = cast<LoadSDNode>(N);
4162 // Test whether the given value is a vector value which will be legalized
4164 static bool WillBeConstantPoolLoad(SDNode *N) {
4165 if (N->getOpcode() != ISD::BUILD_VECTOR)
4168 // Check for any non-constant elements.
4169 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4170 switch (N->getOperand(i).getNode()->getOpcode()) {
4172 case ISD::ConstantFP:
4179 // Vectors of all-zeros and all-ones are materialized with special
4180 // instructions rather than being loaded.
4181 return !ISD::isBuildVectorAllZeros(N) &&
4182 !ISD::isBuildVectorAllOnes(N);
4185 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4186 /// match movlp{s|d}. The lower half elements should come from lower half of
4187 /// V1 (and in order), and the upper half elements should come from the upper
4188 /// half of V2 (and in order). And since V1 will become the source of the
4189 /// MOVLP, it must be either a vector load or a scalar load to vector.
4190 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4191 ArrayRef<int> Mask, EVT VT) {
4192 if (!VT.is128BitVector())
4195 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4197 // Is V2 is a vector load, don't do this transformation. We will try to use
4198 // load folding shufps op.
4199 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4202 unsigned NumElems = VT.getVectorNumElements();
4204 if (NumElems != 2 && NumElems != 4)
4206 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4207 if (!isUndefOrEqual(Mask[i], i))
4209 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4210 if (!isUndefOrEqual(Mask[i], i+NumElems))
4215 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4217 static bool isSplatVector(SDNode *N) {
4218 if (N->getOpcode() != ISD::BUILD_VECTOR)
4221 SDValue SplatValue = N->getOperand(0);
4222 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4223 if (N->getOperand(i) != SplatValue)
4228 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4229 /// to an zero vector.
4230 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4231 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4232 SDValue V1 = N->getOperand(0);
4233 SDValue V2 = N->getOperand(1);
4234 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4235 for (unsigned i = 0; i != NumElems; ++i) {
4236 int Idx = N->getMaskElt(i);
4237 if (Idx >= (int)NumElems) {
4238 unsigned Opc = V2.getOpcode();
4239 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4241 if (Opc != ISD::BUILD_VECTOR ||
4242 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4244 } else if (Idx >= 0) {
4245 unsigned Opc = V1.getOpcode();
4246 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4248 if (Opc != ISD::BUILD_VECTOR ||
4249 !X86::isZeroNode(V1.getOperand(Idx)))
4256 /// getZeroVector - Returns a vector of specified type with all zero elements.
4258 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4259 SelectionDAG &DAG, DebugLoc dl) {
4260 assert(VT.isVector() && "Expected a vector type");
4261 unsigned Size = VT.getSizeInBits();
4263 // Always build SSE zero vectors as <4 x i32> bitcasted
4264 // to their dest type. This ensures they get CSE'd.
4266 if (Size == 128) { // SSE
4267 if (Subtarget->hasSSE2()) { // SSE2
4268 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4269 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4271 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4272 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4274 } else if (Size == 256) { // AVX
4275 if (Subtarget->hasAVX2()) { // AVX2
4276 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4277 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4278 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4280 // 256-bit logic and arithmetic instructions in AVX are all
4281 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4282 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4283 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4284 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4287 llvm_unreachable("Unexpected vector type");
4289 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4292 /// getOnesVector - Returns a vector of specified type with all bits set.
4293 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4294 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4295 /// Then bitcast to their original type, ensuring they get CSE'd.
4296 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4298 assert(VT.isVector() && "Expected a vector type");
4299 unsigned Size = VT.getSizeInBits();
4301 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4304 if (HasAVX2) { // AVX2
4305 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4306 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4308 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4309 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4311 } else if (Size == 128) {
4312 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4314 llvm_unreachable("Unexpected vector type");
4316 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4319 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4320 /// that point to V2 points to its first element.
4321 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4322 for (unsigned i = 0; i != NumElems; ++i) {
4323 if (Mask[i] > (int)NumElems) {
4329 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4330 /// operation of specified width.
4331 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4333 unsigned NumElems = VT.getVectorNumElements();
4334 SmallVector<int, 8> Mask;
4335 Mask.push_back(NumElems);
4336 for (unsigned i = 1; i != NumElems; ++i)
4338 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4341 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4342 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4344 unsigned NumElems = VT.getVectorNumElements();
4345 SmallVector<int, 8> Mask;
4346 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4348 Mask.push_back(i + NumElems);
4350 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4353 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4354 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4356 unsigned NumElems = VT.getVectorNumElements();
4357 SmallVector<int, 8> Mask;
4358 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4359 Mask.push_back(i + Half);
4360 Mask.push_back(i + NumElems + Half);
4362 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4365 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4366 // a generic shuffle instruction because the target has no such instructions.
4367 // Generate shuffles which repeat i16 and i8 several times until they can be
4368 // represented by v4f32 and then be manipulated by target suported shuffles.
4369 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4370 EVT VT = V.getValueType();
4371 int NumElems = VT.getVectorNumElements();
4372 DebugLoc dl = V.getDebugLoc();
4374 while (NumElems > 4) {
4375 if (EltNo < NumElems/2) {
4376 V = getUnpackl(DAG, dl, VT, V, V);
4378 V = getUnpackh(DAG, dl, VT, V, V);
4379 EltNo -= NumElems/2;
4386 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4387 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4388 EVT VT = V.getValueType();
4389 DebugLoc dl = V.getDebugLoc();
4390 unsigned Size = VT.getSizeInBits();
4393 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4394 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4395 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4397 } else if (Size == 256) {
4398 // To use VPERMILPS to splat scalars, the second half of indicies must
4399 // refer to the higher part, which is a duplication of the lower one,
4400 // because VPERMILPS can only handle in-lane permutations.
4401 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4402 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4404 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4405 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4408 llvm_unreachable("Vector size not supported");
4410 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4413 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4414 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4415 EVT SrcVT = SV->getValueType(0);
4416 SDValue V1 = SV->getOperand(0);
4417 DebugLoc dl = SV->getDebugLoc();
4419 int EltNo = SV->getSplatIndex();
4420 int NumElems = SrcVT.getVectorNumElements();
4421 unsigned Size = SrcVT.getSizeInBits();
4423 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4424 "Unknown how to promote splat for type");
4426 // Extract the 128-bit part containing the splat element and update
4427 // the splat element index when it refers to the higher register.
4429 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4430 if (EltNo >= NumElems/2)
4431 EltNo -= NumElems/2;
4434 // All i16 and i8 vector types can't be used directly by a generic shuffle
4435 // instruction because the target has no such instruction. Generate shuffles
4436 // which repeat i16 and i8 several times until they fit in i32, and then can
4437 // be manipulated by target suported shuffles.
4438 EVT EltVT = SrcVT.getVectorElementType();
4439 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4440 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4442 // Recreate the 256-bit vector and place the same 128-bit vector
4443 // into the low and high part. This is necessary because we want
4444 // to use VPERM* to shuffle the vectors
4446 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4449 return getLegalSplat(DAG, V1, EltNo);
4452 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4453 /// vector of zero or undef vector. This produces a shuffle where the low
4454 /// element of V2 is swizzled into the zero/undef vector, landing at element
4455 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4456 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4458 const X86Subtarget *Subtarget,
4459 SelectionDAG &DAG) {
4460 EVT VT = V2.getValueType();
4462 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4463 unsigned NumElems = VT.getVectorNumElements();
4464 SmallVector<int, 16> MaskVec;
4465 for (unsigned i = 0; i != NumElems; ++i)
4466 // If this is the insertion idx, put the low elt of V2 here.
4467 MaskVec.push_back(i == Idx ? NumElems : i);
4468 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4471 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4472 /// target specific opcode. Returns true if the Mask could be calculated.
4473 /// Sets IsUnary to true if only uses one source.
4474 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4475 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4476 unsigned NumElems = VT.getVectorNumElements();
4480 switch(N->getOpcode()) {
4482 ImmN = N->getOperand(N->getNumOperands()-1);
4483 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4485 case X86ISD::UNPCKH:
4486 DecodeUNPCKHMask(VT, Mask);
4488 case X86ISD::UNPCKL:
4489 DecodeUNPCKLMask(VT, Mask);
4491 case X86ISD::MOVHLPS:
4492 DecodeMOVHLPSMask(NumElems, Mask);
4494 case X86ISD::MOVLHPS:
4495 DecodeMOVLHPSMask(NumElems, Mask);
4497 case X86ISD::PSHUFD:
4498 case X86ISD::VPERMILP:
4499 ImmN = N->getOperand(N->getNumOperands()-1);
4500 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4503 case X86ISD::PSHUFHW:
4504 ImmN = N->getOperand(N->getNumOperands()-1);
4505 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4508 case X86ISD::PSHUFLW:
4509 ImmN = N->getOperand(N->getNumOperands()-1);
4510 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4513 case X86ISD::VPERMI:
4514 ImmN = N->getOperand(N->getNumOperands()-1);
4515 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519 case X86ISD::MOVSD: {
4520 // The index 0 always comes from the first element of the second source,
4521 // this is why MOVSS and MOVSD are used in the first place. The other
4522 // elements come from the other positions of the first source vector
4523 Mask.push_back(NumElems);
4524 for (unsigned i = 1; i != NumElems; ++i) {
4529 case X86ISD::VPERM2X128:
4530 ImmN = N->getOperand(N->getNumOperands()-1);
4531 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4532 if (Mask.empty()) return false;
4534 case X86ISD::MOVDDUP:
4535 case X86ISD::MOVLHPD:
4536 case X86ISD::MOVLPD:
4537 case X86ISD::MOVLPS:
4538 case X86ISD::MOVSHDUP:
4539 case X86ISD::MOVSLDUP:
4540 case X86ISD::PALIGN:
4541 // Not yet implemented
4543 default: llvm_unreachable("unknown target shuffle node");
4549 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4550 /// element of the result of the vector shuffle.
4551 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4554 return SDValue(); // Limit search depth.
4556 SDValue V = SDValue(N, 0);
4557 EVT VT = V.getValueType();
4558 unsigned Opcode = V.getOpcode();
4560 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4561 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4562 int Elt = SV->getMaskElt(Index);
4565 return DAG.getUNDEF(VT.getVectorElementType());
4567 unsigned NumElems = VT.getVectorNumElements();
4568 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4569 : SV->getOperand(1);
4570 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4573 // Recurse into target specific vector shuffles to find scalars.
4574 if (isTargetShuffle(Opcode)) {
4575 MVT ShufVT = V.getValueType().getSimpleVT();
4576 unsigned NumElems = ShufVT.getVectorNumElements();
4577 SmallVector<int, 16> ShuffleMask;
4581 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4584 int Elt = ShuffleMask[Index];
4586 return DAG.getUNDEF(ShufVT.getVectorElementType());
4588 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4590 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4594 // Actual nodes that may contain scalar elements
4595 if (Opcode == ISD::BITCAST) {
4596 V = V.getOperand(0);
4597 EVT SrcVT = V.getValueType();
4598 unsigned NumElems = VT.getVectorNumElements();
4600 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4604 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4605 return (Index == 0) ? V.getOperand(0)
4606 : DAG.getUNDEF(VT.getVectorElementType());
4608 if (V.getOpcode() == ISD::BUILD_VECTOR)
4609 return V.getOperand(Index);
4614 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4615 /// shuffle operation which come from a consecutively from a zero. The
4616 /// search can start in two different directions, from left or right.
4618 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4619 bool ZerosFromLeft, SelectionDAG &DAG) {
4621 for (i = 0; i != NumElems; ++i) {
4622 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4623 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4624 if (!(Elt.getNode() &&
4625 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4632 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4633 /// correspond consecutively to elements from one of the vector operands,
4634 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4636 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4637 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4638 unsigned NumElems, unsigned &OpNum) {
4639 bool SeenV1 = false;
4640 bool SeenV2 = false;
4642 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4643 int Idx = SVOp->getMaskElt(i);
4644 // Ignore undef indicies
4648 if (Idx < (int)NumElems)
4653 // Only accept consecutive elements from the same vector
4654 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4658 OpNum = SeenV1 ? 0 : 1;
4662 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4663 /// logical left shift of a vector.
4664 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4665 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4666 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4667 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4668 false /* check zeros from right */, DAG);
4674 // Considering the elements in the mask that are not consecutive zeros,
4675 // check if they consecutively come from only one of the source vectors.
4677 // V1 = {X, A, B, C} 0
4679 // vector_shuffle V1, V2 <1, 2, 3, X>
4681 if (!isShuffleMaskConsecutive(SVOp,
4682 0, // Mask Start Index
4683 NumElems-NumZeros, // Mask End Index(exclusive)
4684 NumZeros, // Where to start looking in the src vector
4685 NumElems, // Number of elements in vector
4686 OpSrc)) // Which source operand ?
4691 ShVal = SVOp->getOperand(OpSrc);
4695 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4696 /// logical left shift of a vector.
4697 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4698 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4699 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4700 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4701 true /* check zeros from left */, DAG);
4707 // Considering the elements in the mask that are not consecutive zeros,
4708 // check if they consecutively come from only one of the source vectors.
4710 // 0 { A, B, X, X } = V2
4712 // vector_shuffle V1, V2 <X, X, 4, 5>
4714 if (!isShuffleMaskConsecutive(SVOp,
4715 NumZeros, // Mask Start Index
4716 NumElems, // Mask End Index(exclusive)
4717 0, // Where to start looking in the src vector
4718 NumElems, // Number of elements in vector
4719 OpSrc)) // Which source operand ?
4724 ShVal = SVOp->getOperand(OpSrc);
4728 /// isVectorShift - Returns true if the shuffle can be implemented as a
4729 /// logical left or right shift of a vector.
4730 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4731 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4732 // Although the logic below support any bitwidth size, there are no
4733 // shift instructions which handle more than 128-bit vectors.
4734 if (!SVOp->getValueType(0).is128BitVector())
4737 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4738 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4744 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4746 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4747 unsigned NumNonZero, unsigned NumZero,
4749 const X86Subtarget* Subtarget,
4750 const TargetLowering &TLI) {
4754 DebugLoc dl = Op.getDebugLoc();
4757 for (unsigned i = 0; i < 16; ++i) {
4758 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4759 if (ThisIsNonZero && First) {
4761 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4763 V = DAG.getUNDEF(MVT::v8i16);
4768 SDValue ThisElt(0, 0), LastElt(0, 0);
4769 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4770 if (LastIsNonZero) {
4771 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4772 MVT::i16, Op.getOperand(i-1));
4774 if (ThisIsNonZero) {
4775 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4776 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4777 ThisElt, DAG.getConstant(8, MVT::i8));
4779 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4783 if (ThisElt.getNode())
4784 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4785 DAG.getIntPtrConstant(i/2));
4789 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4792 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4794 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4795 unsigned NumNonZero, unsigned NumZero,
4797 const X86Subtarget* Subtarget,
4798 const TargetLowering &TLI) {
4802 DebugLoc dl = Op.getDebugLoc();
4805 for (unsigned i = 0; i < 8; ++i) {
4806 bool isNonZero = (NonZeros & (1 << i)) != 0;
4810 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4812 V = DAG.getUNDEF(MVT::v8i16);
4815 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4816 MVT::v8i16, V, Op.getOperand(i),
4817 DAG.getIntPtrConstant(i));
4824 /// getVShift - Return a vector logical shift node.
4826 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4827 unsigned NumBits, SelectionDAG &DAG,
4828 const TargetLowering &TLI, DebugLoc dl) {
4829 assert(VT.is128BitVector() && "Unknown type for VShift");
4830 EVT ShVT = MVT::v2i64;
4831 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4832 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4833 return DAG.getNode(ISD::BITCAST, dl, VT,
4834 DAG.getNode(Opc, dl, ShVT, SrcOp,
4835 DAG.getConstant(NumBits,
4836 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4840 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4841 SelectionDAG &DAG) const {
4843 // Check if the scalar load can be widened into a vector load. And if
4844 // the address is "base + cst" see if the cst can be "absorbed" into
4845 // the shuffle mask.
4846 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4847 SDValue Ptr = LD->getBasePtr();
4848 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4850 EVT PVT = LD->getValueType(0);
4851 if (PVT != MVT::i32 && PVT != MVT::f32)
4856 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4857 FI = FINode->getIndex();
4859 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4860 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4861 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4862 Offset = Ptr.getConstantOperandVal(1);
4863 Ptr = Ptr.getOperand(0);
4868 // FIXME: 256-bit vector instructions don't require a strict alignment,
4869 // improve this code to support it better.
4870 unsigned RequiredAlign = VT.getSizeInBits()/8;
4871 SDValue Chain = LD->getChain();
4872 // Make sure the stack object alignment is at least 16 or 32.
4873 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4874 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4875 if (MFI->isFixedObjectIndex(FI)) {
4876 // Can't change the alignment. FIXME: It's possible to compute
4877 // the exact stack offset and reference FI + adjust offset instead.
4878 // If someone *really* cares about this. That's the way to implement it.
4881 MFI->setObjectAlignment(FI, RequiredAlign);
4885 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4886 // Ptr + (Offset & ~15).
4889 if ((Offset % RequiredAlign) & 3)
4891 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4893 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4894 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4896 int EltNo = (Offset - StartOffset) >> 2;
4897 unsigned NumElems = VT.getVectorNumElements();
4899 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4900 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4901 LD->getPointerInfo().getWithOffset(StartOffset),
4902 false, false, false, 0);
4904 SmallVector<int, 8> Mask;
4905 for (unsigned i = 0; i != NumElems; ++i)
4906 Mask.push_back(EltNo);
4908 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4914 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4915 /// vector of type 'VT', see if the elements can be replaced by a single large
4916 /// load which has the same value as a build_vector whose operands are 'elts'.
4918 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4920 /// FIXME: we'd also like to handle the case where the last elements are zero
4921 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4922 /// There's even a handy isZeroNode for that purpose.
4923 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4924 DebugLoc &DL, SelectionDAG &DAG) {
4925 EVT EltVT = VT.getVectorElementType();
4926 unsigned NumElems = Elts.size();
4928 LoadSDNode *LDBase = NULL;
4929 unsigned LastLoadedElt = -1U;
4931 // For each element in the initializer, see if we've found a load or an undef.
4932 // If we don't find an initial load element, or later load elements are
4933 // non-consecutive, bail out.
4934 for (unsigned i = 0; i < NumElems; ++i) {
4935 SDValue Elt = Elts[i];
4937 if (!Elt.getNode() ||
4938 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4941 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4943 LDBase = cast<LoadSDNode>(Elt.getNode());
4947 if (Elt.getOpcode() == ISD::UNDEF)
4950 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4951 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4956 // If we have found an entire vector of loads and undefs, then return a large
4957 // load of the entire vector width starting at the base pointer. If we found
4958 // consecutive loads for the low half, generate a vzext_load node.
4959 if (LastLoadedElt == NumElems - 1) {
4960 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4961 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4962 LDBase->getPointerInfo(),
4963 LDBase->isVolatile(), LDBase->isNonTemporal(),
4964 LDBase->isInvariant(), 0);
4965 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4966 LDBase->getPointerInfo(),
4967 LDBase->isVolatile(), LDBase->isNonTemporal(),
4968 LDBase->isInvariant(), LDBase->getAlignment());
4970 if (NumElems == 4 && LastLoadedElt == 1 &&
4971 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4972 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4973 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4975 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4976 LDBase->getPointerInfo(),
4977 LDBase->getAlignment(),
4978 false/*isVolatile*/, true/*ReadMem*/,
4980 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4985 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4986 /// to generate a splat value for the following cases:
4987 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4988 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4989 /// a scalar load, or a constant.
4990 /// The VBROADCAST node is returned when a pattern is found,
4991 /// or SDValue() otherwise.
4993 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4994 if (!Subtarget->hasAVX())
4997 EVT VT = Op.getValueType();
4998 DebugLoc dl = Op.getDebugLoc();
5000 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5001 "Unsupported vector type for broadcast.");
5006 switch (Op.getOpcode()) {
5008 // Unknown pattern found.
5011 case ISD::BUILD_VECTOR: {
5012 // The BUILD_VECTOR node must be a splat.
5013 if (!isSplatVector(Op.getNode()))
5016 Ld = Op.getOperand(0);
5017 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5018 Ld.getOpcode() == ISD::ConstantFP);
5020 // The suspected load node has several users. Make sure that all
5021 // of its users are from the BUILD_VECTOR node.
5022 // Constants may have multiple users.
5023 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5028 case ISD::VECTOR_SHUFFLE: {
5029 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5031 // Shuffles must have a splat mask where the first element is
5033 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5036 SDValue Sc = Op.getOperand(0);
5037 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5038 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5040 if (!Subtarget->hasAVX2())
5043 // Use the register form of the broadcast instruction available on AVX2.
5044 if (VT.is256BitVector())
5045 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5046 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5049 Ld = Sc.getOperand(0);
5050 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5051 Ld.getOpcode() == ISD::ConstantFP);
5053 // The scalar_to_vector node and the suspected
5054 // load node must have exactly one user.
5055 // Constants may have multiple users.
5056 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5062 bool Is256 = VT.is256BitVector();
5064 // Handle the broadcasting a single constant scalar from the constant pool
5065 // into a vector. On Sandybridge it is still better to load a constant vector
5066 // from the constant pool and not to broadcast it from a scalar.
5067 if (ConstSplatVal && Subtarget->hasAVX2()) {
5068 EVT CVT = Ld.getValueType();
5069 assert(!CVT.isVector() && "Must not broadcast a vector type");
5070 unsigned ScalarSize = CVT.getSizeInBits();
5072 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5073 const Constant *C = 0;
5074 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5075 C = CI->getConstantIntValue();
5076 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5077 C = CF->getConstantFPValue();
5079 assert(C && "Invalid constant type");
5081 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5082 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5083 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5084 MachinePointerInfo::getConstantPool(),
5085 false, false, false, Alignment);
5087 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5091 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5092 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5094 // Handle AVX2 in-register broadcasts.
5095 if (!IsLoad && Subtarget->hasAVX2() &&
5096 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5097 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5099 // The scalar source must be a normal load.
5103 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5104 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5106 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5107 // double since there is no vbroadcastsd xmm
5108 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5109 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5110 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5113 // Unsupported broadcast.
5117 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5118 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5119 // constraint of matching input/output vector elements.
5121 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5122 DebugLoc DL = Op.getDebugLoc();
5123 SDNode *N = Op.getNode();
5124 EVT VT = Op.getValueType();
5125 unsigned NumElts = Op.getNumOperands();
5127 // Check supported types and sub-targets.
5129 // Only v2f32 -> v2f64 needs special handling.
5130 if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5135 SmallVector<int, 8> Mask;
5136 EVT SrcVT = MVT::Other;
5138 // Check the patterns could be translated into X86vfpext.
5139 for (unsigned i = 0; i < NumElts; ++i) {
5140 SDValue In = N->getOperand(i);
5141 unsigned Opcode = In.getOpcode();
5143 // Skip if the element is undefined.
5144 if (Opcode == ISD::UNDEF) {
5149 // Quit if one of the elements is not defined from 'fpext'.
5150 if (Opcode != ISD::FP_EXTEND)
5153 // Check how the source of 'fpext' is defined.
5154 SDValue L2In = In.getOperand(0);
5155 EVT L2InVT = L2In.getValueType();
5157 // Check the original type
5158 if (SrcVT == MVT::Other)
5160 else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5163 // Check whether the value being 'fpext'ed is extracted from the same
5165 Opcode = L2In.getOpcode();
5167 // Quit if it's not extracted with a constant index.
5168 if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5169 !isa<ConstantSDNode>(L2In.getOperand(1)))
5172 SDValue ExtractedFromVec = L2In.getOperand(0);
5174 if (VecIn.getNode() == 0) {
5175 VecIn = ExtractedFromVec;
5176 VecInVT = ExtractedFromVec.getValueType();
5177 } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5180 Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5183 // Quit if all operands of BUILD_VECTOR are undefined.
5184 if (!VecIn.getNode())
5187 // Fill the remaining mask as undef.
5188 for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5191 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5192 DAG.getVectorShuffle(VecInVT, DL,
5193 VecIn, DAG.getUNDEF(VecInVT),
5198 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5199 DebugLoc dl = Op.getDebugLoc();
5201 EVT VT = Op.getValueType();
5202 EVT ExtVT = VT.getVectorElementType();
5203 unsigned NumElems = Op.getNumOperands();
5205 // Vectors containing all zeros can be matched by pxor and xorps later
5206 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5207 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5208 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5209 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5212 return getZeroVector(VT, Subtarget, DAG, dl);
5215 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5216 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5217 // vpcmpeqd on 256-bit vectors.
5218 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5219 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5222 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5225 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5226 if (Broadcast.getNode())
5229 SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5230 if (FpExt.getNode())
5233 unsigned EVTBits = ExtVT.getSizeInBits();
5235 unsigned NumZero = 0;
5236 unsigned NumNonZero = 0;
5237 unsigned NonZeros = 0;
5238 bool IsAllConstants = true;
5239 SmallSet<SDValue, 8> Values;
5240 for (unsigned i = 0; i < NumElems; ++i) {
5241 SDValue Elt = Op.getOperand(i);
5242 if (Elt.getOpcode() == ISD::UNDEF)
5245 if (Elt.getOpcode() != ISD::Constant &&
5246 Elt.getOpcode() != ISD::ConstantFP)
5247 IsAllConstants = false;
5248 if (X86::isZeroNode(Elt))
5251 NonZeros |= (1 << i);
5256 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5257 if (NumNonZero == 0)
5258 return DAG.getUNDEF(VT);
5260 // Special case for single non-zero, non-undef, element.
5261 if (NumNonZero == 1) {
5262 unsigned Idx = CountTrailingZeros_32(NonZeros);
5263 SDValue Item = Op.getOperand(Idx);
5265 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5266 // the value are obviously zero, truncate the value to i32 and do the
5267 // insertion that way. Only do this if the value is non-constant or if the
5268 // value is a constant being inserted into element 0. It is cheaper to do
5269 // a constant pool load than it is to do a movd + shuffle.
5270 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5271 (!IsAllConstants || Idx == 0)) {
5272 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5274 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5275 EVT VecVT = MVT::v4i32;
5276 unsigned VecElts = 4;
5278 // Truncate the value (which may itself be a constant) to i32, and
5279 // convert it to a vector with movd (S2V+shuffle to zero extend).
5280 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5281 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5282 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5284 // Now we have our 32-bit value zero extended in the low element of
5285 // a vector. If Idx != 0, swizzle it into place.
5287 SmallVector<int, 4> Mask;
5288 Mask.push_back(Idx);
5289 for (unsigned i = 1; i != VecElts; ++i)
5291 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5294 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5298 // If we have a constant or non-constant insertion into the low element of
5299 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5300 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5301 // depending on what the source datatype is.
5304 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5306 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5307 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5308 if (VT.is256BitVector()) {
5309 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5310 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5311 Item, DAG.getIntPtrConstant(0));
5313 assert(VT.is128BitVector() && "Expected an SSE value type!");
5314 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5315 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5316 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5319 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5320 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5321 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5322 if (VT.is256BitVector()) {
5323 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5324 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5326 assert(VT.is128BitVector() && "Expected an SSE value type!");
5327 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5329 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5333 // Is it a vector logical left shift?
5334 if (NumElems == 2 && Idx == 1 &&
5335 X86::isZeroNode(Op.getOperand(0)) &&
5336 !X86::isZeroNode(Op.getOperand(1))) {
5337 unsigned NumBits = VT.getSizeInBits();
5338 return getVShift(true, VT,
5339 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5340 VT, Op.getOperand(1)),
5341 NumBits/2, DAG, *this, dl);
5344 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5347 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5348 // is a non-constant being inserted into an element other than the low one,
5349 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5350 // movd/movss) to move this into the low element, then shuffle it into
5352 if (EVTBits == 32) {
5353 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5355 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5356 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5357 SmallVector<int, 8> MaskVec;
5358 for (unsigned i = 0; i != NumElems; ++i)
5359 MaskVec.push_back(i == Idx ? 0 : 1);
5360 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5364 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5365 if (Values.size() == 1) {
5366 if (EVTBits == 32) {
5367 // Instead of a shuffle like this:
5368 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5369 // Check if it's possible to issue this instead.
5370 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5371 unsigned Idx = CountTrailingZeros_32(NonZeros);
5372 SDValue Item = Op.getOperand(Idx);
5373 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5374 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5379 // A vector full of immediates; various special cases are already
5380 // handled, so this is best done with a single constant-pool load.
5384 // For AVX-length vectors, build the individual 128-bit pieces and use
5385 // shuffles to put them in place.
5386 if (VT.is256BitVector()) {
5387 SmallVector<SDValue, 32> V;
5388 for (unsigned i = 0; i != NumElems; ++i)
5389 V.push_back(Op.getOperand(i));
5391 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5393 // Build both the lower and upper subvector.
5394 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5395 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5398 // Recreate the wider vector with the lower and upper part.
5399 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5402 // Let legalizer expand 2-wide build_vectors.
5403 if (EVTBits == 64) {
5404 if (NumNonZero == 1) {
5405 // One half is zero or undef.
5406 unsigned Idx = CountTrailingZeros_32(NonZeros);
5407 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5408 Op.getOperand(Idx));
5409 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5414 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5415 if (EVTBits == 8 && NumElems == 16) {
5416 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5418 if (V.getNode()) return V;
5421 if (EVTBits == 16 && NumElems == 8) {
5422 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5424 if (V.getNode()) return V;
5427 // If element VT is == 32 bits, turn it into a number of shuffles.
5428 SmallVector<SDValue, 8> V(NumElems);
5429 if (NumElems == 4 && NumZero > 0) {
5430 for (unsigned i = 0; i < 4; ++i) {
5431 bool isZero = !(NonZeros & (1 << i));
5433 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5435 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5438 for (unsigned i = 0; i < 2; ++i) {
5439 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5442 V[i] = V[i*2]; // Must be a zero vector.
5445 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5448 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5451 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5456 bool Reverse1 = (NonZeros & 0x3) == 2;
5457 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5461 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5462 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5464 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5467 if (Values.size() > 1 && VT.is128BitVector()) {
5468 // Check for a build vector of consecutive loads.
5469 for (unsigned i = 0; i < NumElems; ++i)
5470 V[i] = Op.getOperand(i);
5472 // Check for elements which are consecutive loads.
5473 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5477 // For SSE 4.1, use insertps to put the high elements into the low element.
5478 if (getSubtarget()->hasSSE41()) {
5480 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5481 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5483 Result = DAG.getUNDEF(VT);
5485 for (unsigned i = 1; i < NumElems; ++i) {
5486 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5487 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5488 Op.getOperand(i), DAG.getIntPtrConstant(i));
5493 // Otherwise, expand into a number of unpckl*, start by extending each of
5494 // our (non-undef) elements to the full vector width with the element in the
5495 // bottom slot of the vector (which generates no code for SSE).
5496 for (unsigned i = 0; i < NumElems; ++i) {
5497 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5498 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5500 V[i] = DAG.getUNDEF(VT);
5503 // Next, we iteratively mix elements, e.g. for v4f32:
5504 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5505 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5506 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5507 unsigned EltStride = NumElems >> 1;
5508 while (EltStride != 0) {
5509 for (unsigned i = 0; i < EltStride; ++i) {
5510 // If V[i+EltStride] is undef and this is the first round of mixing,
5511 // then it is safe to just drop this shuffle: V[i] is already in the
5512 // right place, the one element (since it's the first round) being
5513 // inserted as undef can be dropped. This isn't safe for successive
5514 // rounds because they will permute elements within both vectors.
5515 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5516 EltStride == NumElems/2)
5519 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5528 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5529 // to create 256-bit vectors from two other 128-bit ones.
5530 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5531 DebugLoc dl = Op.getDebugLoc();
5532 EVT ResVT = Op.getValueType();
5534 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5536 SDValue V1 = Op.getOperand(0);
5537 SDValue V2 = Op.getOperand(1);
5538 unsigned NumElems = ResVT.getVectorNumElements();
5540 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5544 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5545 assert(Op.getNumOperands() == 2);
5547 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5548 // from two other 128-bit ones.
5549 return LowerAVXCONCAT_VECTORS(Op, DAG);
5552 // Try to lower a shuffle node into a simple blend instruction.
5553 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5554 const X86Subtarget *Subtarget,
5555 SelectionDAG &DAG) {
5556 SDValue V1 = SVOp->getOperand(0);
5557 SDValue V2 = SVOp->getOperand(1);
5558 DebugLoc dl = SVOp->getDebugLoc();
5559 MVT VT = SVOp->getValueType(0).getSimpleVT();
5560 unsigned NumElems = VT.getVectorNumElements();
5562 if (!Subtarget->hasSSE41())
5568 switch (VT.SimpleTy) {
5569 default: return SDValue();
5571 ISDNo = X86ISD::BLENDPW;
5576 ISDNo = X86ISD::BLENDPS;
5581 ISDNo = X86ISD::BLENDPD;
5586 if (!Subtarget->hasAVX())
5588 ISDNo = X86ISD::BLENDPS;
5593 if (!Subtarget->hasAVX())
5595 ISDNo = X86ISD::BLENDPD;
5599 assert(ISDNo && "Invalid Op Number");
5601 unsigned MaskVals = 0;
5603 for (unsigned i = 0; i != NumElems; ++i) {
5604 int EltIdx = SVOp->getMaskElt(i);
5605 if (EltIdx == (int)i || EltIdx < 0)
5607 else if (EltIdx == (int)(i + NumElems))
5608 continue; // Bit is set to zero;
5613 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5614 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5615 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5616 DAG.getConstant(MaskVals, MVT::i32));
5617 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5620 // v8i16 shuffles - Prefer shuffles in the following order:
5621 // 1. [all] pshuflw, pshufhw, optional move
5622 // 2. [ssse3] 1 x pshufb
5623 // 3. [ssse3] 2 x pshufb + 1 x por
5624 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5626 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5627 SelectionDAG &DAG) const {
5628 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5629 SDValue V1 = SVOp->getOperand(0);
5630 SDValue V2 = SVOp->getOperand(1);
5631 DebugLoc dl = SVOp->getDebugLoc();
5632 SmallVector<int, 8> MaskVals;
5634 // Determine if more than 1 of the words in each of the low and high quadwords
5635 // of the result come from the same quadword of one of the two inputs. Undef
5636 // mask values count as coming from any quadword, for better codegen.
5637 unsigned LoQuad[] = { 0, 0, 0, 0 };
5638 unsigned HiQuad[] = { 0, 0, 0, 0 };
5639 std::bitset<4> InputQuads;
5640 for (unsigned i = 0; i < 8; ++i) {
5641 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5642 int EltIdx = SVOp->getMaskElt(i);
5643 MaskVals.push_back(EltIdx);
5652 InputQuads.set(EltIdx / 4);
5655 int BestLoQuad = -1;
5656 unsigned MaxQuad = 1;
5657 for (unsigned i = 0; i < 4; ++i) {
5658 if (LoQuad[i] > MaxQuad) {
5660 MaxQuad = LoQuad[i];
5664 int BestHiQuad = -1;
5666 for (unsigned i = 0; i < 4; ++i) {
5667 if (HiQuad[i] > MaxQuad) {
5669 MaxQuad = HiQuad[i];
5673 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5674 // of the two input vectors, shuffle them into one input vector so only a
5675 // single pshufb instruction is necessary. If There are more than 2 input
5676 // quads, disable the next transformation since it does not help SSSE3.
5677 bool V1Used = InputQuads[0] || InputQuads[1];
5678 bool V2Used = InputQuads[2] || InputQuads[3];
5679 if (Subtarget->hasSSSE3()) {
5680 if (InputQuads.count() == 2 && V1Used && V2Used) {
5681 BestLoQuad = InputQuads[0] ? 0 : 1;
5682 BestHiQuad = InputQuads[2] ? 2 : 3;
5684 if (InputQuads.count() > 2) {
5690 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5691 // the shuffle mask. If a quad is scored as -1, that means that it contains
5692 // words from all 4 input quadwords.
5694 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5696 BestLoQuad < 0 ? 0 : BestLoQuad,
5697 BestHiQuad < 0 ? 1 : BestHiQuad
5699 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5700 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5701 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5702 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5704 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5705 // source words for the shuffle, to aid later transformations.
5706 bool AllWordsInNewV = true;
5707 bool InOrder[2] = { true, true };
5708 for (unsigned i = 0; i != 8; ++i) {
5709 int idx = MaskVals[i];
5711 InOrder[i/4] = false;
5712 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5714 AllWordsInNewV = false;
5718 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5719 if (AllWordsInNewV) {
5720 for (int i = 0; i != 8; ++i) {
5721 int idx = MaskVals[i];
5724 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5725 if ((idx != i) && idx < 4)
5727 if ((idx != i) && idx > 3)
5736 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5737 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5738 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5739 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5740 unsigned TargetMask = 0;
5741 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5742 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5743 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5744 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5745 getShufflePSHUFLWImmediate(SVOp);
5746 V1 = NewV.getOperand(0);
5747 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5751 // If we have SSSE3, and all words of the result are from 1 input vector,
5752 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5753 // is present, fall back to case 4.
5754 if (Subtarget->hasSSSE3()) {
5755 SmallVector<SDValue,16> pshufbMask;
5757 // If we have elements from both input vectors, set the high bit of the
5758 // shuffle mask element to zero out elements that come from V2 in the V1
5759 // mask, and elements that come from V1 in the V2 mask, so that the two
5760 // results can be OR'd together.
5761 bool TwoInputs = V1Used && V2Used;
5762 for (unsigned i = 0; i != 8; ++i) {
5763 int EltIdx = MaskVals[i] * 2;
5764 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5765 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5766 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5767 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5769 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5770 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5771 DAG.getNode(ISD::BUILD_VECTOR, dl,
5772 MVT::v16i8, &pshufbMask[0], 16));
5774 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5776 // Calculate the shuffle mask for the second input, shuffle it, and
5777 // OR it with the first shuffled input.
5779 for (unsigned i = 0; i != 8; ++i) {
5780 int EltIdx = MaskVals[i] * 2;
5781 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5782 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5783 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5784 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5786 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5787 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5788 DAG.getNode(ISD::BUILD_VECTOR, dl,
5789 MVT::v16i8, &pshufbMask[0], 16));
5790 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5791 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5794 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5795 // and update MaskVals with new element order.
5796 std::bitset<8> InOrder;
5797 if (BestLoQuad >= 0) {
5798 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5799 for (int i = 0; i != 4; ++i) {
5800 int idx = MaskVals[i];
5803 } else if ((idx / 4) == BestLoQuad) {
5808 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5811 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5812 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5813 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5815 getShufflePSHUFLWImmediate(SVOp), DAG);
5819 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5820 // and update MaskVals with the new element order.
5821 if (BestHiQuad >= 0) {
5822 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5823 for (unsigned i = 4; i != 8; ++i) {
5824 int idx = MaskVals[i];
5827 } else if ((idx / 4) == BestHiQuad) {
5828 MaskV[i] = (idx & 3) + 4;
5832 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5835 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5836 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5837 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5839 getShufflePSHUFHWImmediate(SVOp), DAG);
5843 // In case BestHi & BestLo were both -1, which means each quadword has a word
5844 // from each of the four input quadwords, calculate the InOrder bitvector now
5845 // before falling through to the insert/extract cleanup.
5846 if (BestLoQuad == -1 && BestHiQuad == -1) {
5848 for (int i = 0; i != 8; ++i)
5849 if (MaskVals[i] < 0 || MaskVals[i] == i)
5853 // The other elements are put in the right place using pextrw and pinsrw.
5854 for (unsigned i = 0; i != 8; ++i) {
5857 int EltIdx = MaskVals[i];
5860 SDValue ExtOp = (EltIdx < 8) ?
5861 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5862 DAG.getIntPtrConstant(EltIdx)) :
5863 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5864 DAG.getIntPtrConstant(EltIdx - 8));
5865 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5866 DAG.getIntPtrConstant(i));
5871 // v16i8 shuffles - Prefer shuffles in the following order:
5872 // 1. [ssse3] 1 x pshufb
5873 // 2. [ssse3] 2 x pshufb + 1 x por
5874 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5876 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5878 const X86TargetLowering &TLI) {
5879 SDValue V1 = SVOp->getOperand(0);
5880 SDValue V2 = SVOp->getOperand(1);
5881 DebugLoc dl = SVOp->getDebugLoc();
5882 ArrayRef<int> MaskVals = SVOp->getMask();
5884 // If we have SSSE3, case 1 is generated when all result bytes come from
5885 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5886 // present, fall back to case 3.
5888 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5889 if (TLI.getSubtarget()->hasSSSE3()) {
5890 SmallVector<SDValue,16> pshufbMask;
5892 // If all result elements are from one input vector, then only translate
5893 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5895 // Otherwise, we have elements from both input vectors, and must zero out
5896 // elements that come from V2 in the first mask, and V1 in the second mask
5897 // so that we can OR them together.
5898 for (unsigned i = 0; i != 16; ++i) {
5899 int EltIdx = MaskVals[i];
5900 if (EltIdx < 0 || EltIdx >= 16)
5902 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5904 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5905 DAG.getNode(ISD::BUILD_VECTOR, dl,
5906 MVT::v16i8, &pshufbMask[0], 16));
5908 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5909 // the 2nd operand if it's undefined or zero.
5910 if (V2.getOpcode() == ISD::UNDEF ||
5911 ISD::isBuildVectorAllZeros(V2.getNode()))
5914 // Calculate the shuffle mask for the second input, shuffle it, and
5915 // OR it with the first shuffled input.
5917 for (unsigned i = 0; i != 16; ++i) {
5918 int EltIdx = MaskVals[i];
5919 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5920 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5922 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5923 DAG.getNode(ISD::BUILD_VECTOR, dl,
5924 MVT::v16i8, &pshufbMask[0], 16));
5925 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5928 // No SSSE3 - Calculate in place words and then fix all out of place words
5929 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5930 // the 16 different words that comprise the two doublequadword input vectors.
5931 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5932 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5934 for (int i = 0; i != 8; ++i) {
5935 int Elt0 = MaskVals[i*2];
5936 int Elt1 = MaskVals[i*2+1];
5938 // This word of the result is all undef, skip it.
5939 if (Elt0 < 0 && Elt1 < 0)
5942 // This word of the result is already in the correct place, skip it.
5943 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5946 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5947 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5950 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5951 // using a single extract together, load it and store it.
5952 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5953 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5954 DAG.getIntPtrConstant(Elt1 / 2));
5955 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5956 DAG.getIntPtrConstant(i));
5960 // If Elt1 is defined, extract it from the appropriate source. If the
5961 // source byte is not also odd, shift the extracted word left 8 bits
5962 // otherwise clear the bottom 8 bits if we need to do an or.
5964 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5965 DAG.getIntPtrConstant(Elt1 / 2));
5966 if ((Elt1 & 1) == 0)
5967 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5969 TLI.getShiftAmountTy(InsElt.getValueType())));
5971 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5972 DAG.getConstant(0xFF00, MVT::i16));
5974 // If Elt0 is defined, extract it from the appropriate source. If the
5975 // source byte is not also even, shift the extracted word right 8 bits. If
5976 // Elt1 was also defined, OR the extracted values together before
5977 // inserting them in the result.
5979 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5980 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5981 if ((Elt0 & 1) != 0)
5982 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5984 TLI.getShiftAmountTy(InsElt0.getValueType())));
5986 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5987 DAG.getConstant(0x00FF, MVT::i16));
5988 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5991 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5992 DAG.getIntPtrConstant(i));
5994 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5997 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5998 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5999 /// done when every pair / quad of shuffle mask elements point to elements in
6000 /// the right sequence. e.g.
6001 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6003 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6004 SelectionDAG &DAG, DebugLoc dl) {
6005 MVT VT = SVOp->getValueType(0).getSimpleVT();
6006 unsigned NumElems = VT.getVectorNumElements();
6009 switch (VT.SimpleTy) {
6010 default: llvm_unreachable("Unexpected!");
6011 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6012 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6013 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6014 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6015 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6016 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6019 SmallVector<int, 8> MaskVec;
6020 for (unsigned i = 0; i != NumElems; i += Scale) {
6022 for (unsigned j = 0; j != Scale; ++j) {
6023 int EltIdx = SVOp->getMaskElt(i+j);
6027 StartIdx = (EltIdx / Scale);
6028 if (EltIdx != (int)(StartIdx*Scale + j))
6031 MaskVec.push_back(StartIdx);
6034 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6035 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6036 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6039 /// getVZextMovL - Return a zero-extending vector move low node.
6041 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6042 SDValue SrcOp, SelectionDAG &DAG,
6043 const X86Subtarget *Subtarget, DebugLoc dl) {
6044 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6045 LoadSDNode *LD = NULL;
6046 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6047 LD = dyn_cast<LoadSDNode>(SrcOp);
6049 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6051 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6052 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6053 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6054 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6055 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6057 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6058 return DAG.getNode(ISD::BITCAST, dl, VT,
6059 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6060 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6068 return DAG.getNode(ISD::BITCAST, dl, VT,
6069 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6070 DAG.getNode(ISD::BITCAST, dl,
6074 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6075 /// which could not be matched by any known target speficic shuffle
6077 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6079 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6080 if (NewOp.getNode())
6083 EVT VT = SVOp->getValueType(0);
6085 unsigned NumElems = VT.getVectorNumElements();
6086 unsigned NumLaneElems = NumElems / 2;
6088 DebugLoc dl = SVOp->getDebugLoc();
6089 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6090 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6093 SmallVector<int, 16> Mask;
6094 for (unsigned l = 0; l < 2; ++l) {
6095 // Build a shuffle mask for the output, discovering on the fly which
6096 // input vectors to use as shuffle operands (recorded in InputUsed).
6097 // If building a suitable shuffle vector proves too hard, then bail
6098 // out with UseBuildVector set.
6099 bool UseBuildVector = false;
6100 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6101 unsigned LaneStart = l * NumLaneElems;
6102 for (unsigned i = 0; i != NumLaneElems; ++i) {
6103 // The mask element. This indexes into the input.
6104 int Idx = SVOp->getMaskElt(i+LaneStart);
6106 // the mask element does not index into any input vector.
6111 // The input vector this mask element indexes into.
6112 int Input = Idx / NumLaneElems;
6114 // Turn the index into an offset from the start of the input vector.
6115 Idx -= Input * NumLaneElems;
6117 // Find or create a shuffle vector operand to hold this input.
6119 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6120 if (InputUsed[OpNo] == Input)
6121 // This input vector is already an operand.
6123 if (InputUsed[OpNo] < 0) {
6124 // Create a new operand for this input vector.
6125 InputUsed[OpNo] = Input;
6130 if (OpNo >= array_lengthof(InputUsed)) {
6131 // More than two input vectors used! Give up on trying to create a
6132 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6133 UseBuildVector = true;
6137 // Add the mask index for the new shuffle vector.
6138 Mask.push_back(Idx + OpNo * NumLaneElems);
6141 if (UseBuildVector) {
6142 SmallVector<SDValue, 16> SVOps;
6143 for (unsigned i = 0; i != NumLaneElems; ++i) {
6144 // The mask element. This indexes into the input.
6145 int Idx = SVOp->getMaskElt(i+LaneStart);
6147 SVOps.push_back(DAG.getUNDEF(EltVT));
6151 // The input vector this mask element indexes into.
6152 int Input = Idx / NumElems;
6154 // Turn the index into an offset from the start of the input vector.
6155 Idx -= Input * NumElems;
6157 // Extract the vector element by hand.
6158 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6159 SVOp->getOperand(Input),
6160 DAG.getIntPtrConstant(Idx)));
6163 // Construct the output using a BUILD_VECTOR.
6164 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6166 } else if (InputUsed[0] < 0) {
6167 // No input vectors were used! The result is undefined.
6168 Output[l] = DAG.getUNDEF(NVT);
6170 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6171 (InputUsed[0] % 2) * NumLaneElems,
6173 // If only one input was used, use an undefined vector for the other.
6174 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6175 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6176 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6177 // At least one input vector was used. Create a new shuffle vector.
6178 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6184 // Concatenate the result back
6185 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6188 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6189 /// 4 elements, and match them with several different shuffle types.
6191 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6192 SDValue V1 = SVOp->getOperand(0);
6193 SDValue V2 = SVOp->getOperand(1);
6194 DebugLoc dl = SVOp->getDebugLoc();
6195 EVT VT = SVOp->getValueType(0);
6197 assert(VT.is128BitVector() && "Unsupported vector size");
6199 std::pair<int, int> Locs[4];
6200 int Mask1[] = { -1, -1, -1, -1 };
6201 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6205 for (unsigned i = 0; i != 4; ++i) {
6206 int Idx = PermMask[i];
6208 Locs[i] = std::make_pair(-1, -1);
6210 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6212 Locs[i] = std::make_pair(0, NumLo);
6216 Locs[i] = std::make_pair(1, NumHi);
6218 Mask1[2+NumHi] = Idx;
6224 if (NumLo <= 2 && NumHi <= 2) {
6225 // If no more than two elements come from either vector. This can be
6226 // implemented with two shuffles. First shuffle gather the elements.
6227 // The second shuffle, which takes the first shuffle as both of its
6228 // vector operands, put the elements into the right order.
6229 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6231 int Mask2[] = { -1, -1, -1, -1 };
6233 for (unsigned i = 0; i != 4; ++i)
6234 if (Locs[i].first != -1) {
6235 unsigned Idx = (i < 2) ? 0 : 4;
6236 Idx += Locs[i].first * 2 + Locs[i].second;
6240 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6243 if (NumLo == 3 || NumHi == 3) {
6244 // Otherwise, we must have three elements from one vector, call it X, and
6245 // one element from the other, call it Y. First, use a shufps to build an
6246 // intermediate vector with the one element from Y and the element from X
6247 // that will be in the same half in the final destination (the indexes don't
6248 // matter). Then, use a shufps to build the final vector, taking the half
6249 // containing the element from Y from the intermediate, and the other half
6252 // Normalize it so the 3 elements come from V1.
6253 CommuteVectorShuffleMask(PermMask, 4);
6257 // Find the element from V2.
6259 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6260 int Val = PermMask[HiIndex];
6267 Mask1[0] = PermMask[HiIndex];
6269 Mask1[2] = PermMask[HiIndex^1];
6271 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6274 Mask1[0] = PermMask[0];
6275 Mask1[1] = PermMask[1];
6276 Mask1[2] = HiIndex & 1 ? 6 : 4;
6277 Mask1[3] = HiIndex & 1 ? 4 : 6;
6278 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6281 Mask1[0] = HiIndex & 1 ? 2 : 0;
6282 Mask1[1] = HiIndex & 1 ? 0 : 2;
6283 Mask1[2] = PermMask[2];
6284 Mask1[3] = PermMask[3];
6289 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6292 // Break it into (shuffle shuffle_hi, shuffle_lo).
6293 int LoMask[] = { -1, -1, -1, -1 };
6294 int HiMask[] = { -1, -1, -1, -1 };
6296 int *MaskPtr = LoMask;
6297 unsigned MaskIdx = 0;
6300 for (unsigned i = 0; i != 4; ++i) {
6307 int Idx = PermMask[i];
6309 Locs[i] = std::make_pair(-1, -1);
6310 } else if (Idx < 4) {
6311 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6312 MaskPtr[LoIdx] = Idx;
6315 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6316 MaskPtr[HiIdx] = Idx;
6321 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6322 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6323 int MaskOps[] = { -1, -1, -1, -1 };
6324 for (unsigned i = 0; i != 4; ++i)
6325 if (Locs[i].first != -1)
6326 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6327 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6330 static bool MayFoldVectorLoad(SDValue V) {
6331 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6332 V = V.getOperand(0);
6333 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6334 V = V.getOperand(0);
6335 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6336 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6337 // BUILD_VECTOR (load), undef
6338 V = V.getOperand(0);
6344 // FIXME: the version above should always be used. Since there's
6345 // a bug where several vector shuffles can't be folded because the
6346 // DAG is not updated during lowering and a node claims to have two
6347 // uses while it only has one, use this version, and let isel match
6348 // another instruction if the load really happens to have more than
6349 // one use. Remove this version after this bug get fixed.
6350 // rdar://8434668, PR8156
6351 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6352 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6353 V = V.getOperand(0);
6354 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6355 V = V.getOperand(0);
6356 if (ISD::isNormalLoad(V.getNode()))
6362 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6363 EVT VT = Op.getValueType();
6365 // Canonizalize to v2f64.
6366 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6367 return DAG.getNode(ISD::BITCAST, dl, VT,
6368 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6373 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6375 SDValue V1 = Op.getOperand(0);
6376 SDValue V2 = Op.getOperand(1);
6377 EVT VT = Op.getValueType();
6379 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6381 if (HasSSE2 && VT == MVT::v2f64)
6382 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6384 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6385 return DAG.getNode(ISD::BITCAST, dl, VT,
6386 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6387 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6388 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6392 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6393 SDValue V1 = Op.getOperand(0);
6394 SDValue V2 = Op.getOperand(1);
6395 EVT VT = Op.getValueType();
6397 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6398 "unsupported shuffle type");
6400 if (V2.getOpcode() == ISD::UNDEF)
6404 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6408 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6409 SDValue V1 = Op.getOperand(0);
6410 SDValue V2 = Op.getOperand(1);
6411 EVT VT = Op.getValueType();
6412 unsigned NumElems = VT.getVectorNumElements();
6414 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6415 // operand of these instructions is only memory, so check if there's a
6416 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6418 bool CanFoldLoad = false;
6420 // Trivial case, when V2 comes from a load.
6421 if (MayFoldVectorLoad(V2))
6424 // When V1 is a load, it can be folded later into a store in isel, example:
6425 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6427 // (MOVLPSmr addr:$src1, VR128:$src2)
6428 // So, recognize this potential and also use MOVLPS or MOVLPD
6429 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6432 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6434 if (HasSSE2 && NumElems == 2)
6435 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6438 // If we don't care about the second element, proceed to use movss.
6439 if (SVOp->getMaskElt(1) != -1)
6440 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6443 // movl and movlp will both match v2i64, but v2i64 is never matched by
6444 // movl earlier because we make it strict to avoid messing with the movlp load
6445 // folding logic (see the code above getMOVLP call). Match it here then,
6446 // this is horrible, but will stay like this until we move all shuffle
6447 // matching to x86 specific nodes. Note that for the 1st condition all
6448 // types are matched with movsd.
6450 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6451 // as to remove this logic from here, as much as possible
6452 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6453 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6454 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6457 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6459 // Invert the operand order and use SHUFPS to match it.
6460 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6461 getShuffleSHUFImmediate(SVOp), DAG);
6465 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6466 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6467 EVT VT = Op.getValueType();
6468 DebugLoc dl = Op.getDebugLoc();
6469 SDValue V1 = Op.getOperand(0);
6470 SDValue V2 = Op.getOperand(1);
6472 if (isZeroShuffle(SVOp))
6473 return getZeroVector(VT, Subtarget, DAG, dl);
6475 // Handle splat operations
6476 if (SVOp->isSplat()) {
6477 unsigned NumElem = VT.getVectorNumElements();
6478 int Size = VT.getSizeInBits();
6480 // Use vbroadcast whenever the splat comes from a foldable load
6481 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6482 if (Broadcast.getNode())
6485 // Handle splats by matching through known shuffle masks
6486 if ((Size == 128 && NumElem <= 4) ||
6487 (Size == 256 && NumElem < 8))
6490 // All remaning splats are promoted to target supported vector shuffles.
6491 return PromoteSplat(SVOp, DAG);
6494 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6496 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6497 VT == MVT::v16i16 || VT == MVT::v32i8) {
6498 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6499 if (NewOp.getNode())
6500 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6501 } else if ((VT == MVT::v4i32 ||
6502 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6503 // FIXME: Figure out a cleaner way to do this.
6504 // Try to make use of movq to zero out the top part.
6505 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6506 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6507 if (NewOp.getNode()) {
6508 EVT NewVT = NewOp.getValueType();
6509 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6510 NewVT, true, false))
6511 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6512 DAG, Subtarget, dl);
6514 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6515 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6516 if (NewOp.getNode()) {
6517 EVT NewVT = NewOp.getValueType();
6518 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6519 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6520 DAG, Subtarget, dl);
6528 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6529 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6530 SDValue V1 = Op.getOperand(0);
6531 SDValue V2 = Op.getOperand(1);
6532 EVT VT = Op.getValueType();
6533 DebugLoc dl = Op.getDebugLoc();
6534 unsigned NumElems = VT.getVectorNumElements();
6535 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6536 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6537 bool V1IsSplat = false;
6538 bool V2IsSplat = false;
6539 bool HasSSE2 = Subtarget->hasSSE2();
6540 bool HasAVX = Subtarget->hasAVX();
6541 bool HasAVX2 = Subtarget->hasAVX2();
6542 MachineFunction &MF = DAG.getMachineFunction();
6543 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6545 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6547 if (V1IsUndef && V2IsUndef)
6548 return DAG.getUNDEF(VT);
6550 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6552 // Vector shuffle lowering takes 3 steps:
6554 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6555 // narrowing and commutation of operands should be handled.
6556 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6558 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6559 // so the shuffle can be broken into other shuffles and the legalizer can
6560 // try the lowering again.
6562 // The general idea is that no vector_shuffle operation should be left to
6563 // be matched during isel, all of them must be converted to a target specific
6566 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6567 // narrowing and commutation of operands should be handled. The actual code
6568 // doesn't include all of those, work in progress...
6569 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6570 if (NewOp.getNode())
6573 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6575 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6576 // unpckh_undef). Only use pshufd if speed is more important than size.
6577 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6578 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6579 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6580 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6582 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6583 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6584 return getMOVDDup(Op, dl, V1, DAG);
6586 if (isMOVHLPS_v_undef_Mask(M, VT))
6587 return getMOVHighToLow(Op, dl, DAG);
6589 // Use to match splats
6590 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6591 (VT == MVT::v2f64 || VT == MVT::v2i64))
6592 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6594 if (isPSHUFDMask(M, VT)) {
6595 // The actual implementation will match the mask in the if above and then
6596 // during isel it can match several different instructions, not only pshufd
6597 // as its name says, sad but true, emulate the behavior for now...
6598 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6599 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6601 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6603 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6604 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6606 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6607 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6609 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6613 // Check if this can be converted into a logical shift.
6614 bool isLeft = false;
6617 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6618 if (isShift && ShVal.hasOneUse()) {
6619 // If the shifted value has multiple uses, it may be cheaper to use
6620 // v_set0 + movlhps or movhlps, etc.
6621 EVT EltVT = VT.getVectorElementType();
6622 ShAmt *= EltVT.getSizeInBits();
6623 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6626 if (isMOVLMask(M, VT)) {
6627 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6628 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6629 if (!isMOVLPMask(M, VT)) {
6630 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6631 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6633 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6634 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6638 // FIXME: fold these into legal mask.
6639 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6640 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6642 if (isMOVHLPSMask(M, VT))
6643 return getMOVHighToLow(Op, dl, DAG);
6645 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6646 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6648 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6649 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6651 if (isMOVLPMask(M, VT))
6652 return getMOVLP(Op, dl, DAG, HasSSE2);
6654 if (ShouldXformToMOVHLPS(M, VT) ||
6655 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6656 return CommuteVectorShuffle(SVOp, DAG);
6659 // No better options. Use a vshldq / vsrldq.
6660 EVT EltVT = VT.getVectorElementType();
6661 ShAmt *= EltVT.getSizeInBits();
6662 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6665 bool Commuted = false;
6666 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6667 // 1,1,1,1 -> v8i16 though.
6668 V1IsSplat = isSplatVector(V1.getNode());
6669 V2IsSplat = isSplatVector(V2.getNode());
6671 // Canonicalize the splat or undef, if present, to be on the RHS.
6672 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6673 CommuteVectorShuffleMask(M, NumElems);
6675 std::swap(V1IsSplat, V2IsSplat);
6679 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6680 // Shuffling low element of v1 into undef, just return v1.
6683 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6684 // the instruction selector will not match, so get a canonical MOVL with
6685 // swapped operands to undo the commute.
6686 return getMOVL(DAG, dl, VT, V2, V1);
6689 if (isUNPCKLMask(M, VT, HasAVX2))
6690 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6692 if (isUNPCKHMask(M, VT, HasAVX2))
6693 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6696 // Normalize mask so all entries that point to V2 points to its first
6697 // element then try to match unpck{h|l} again. If match, return a
6698 // new vector_shuffle with the corrected mask.p
6699 SmallVector<int, 8> NewMask(M.begin(), M.end());
6700 NormalizeMask(NewMask, NumElems);
6701 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6702 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6703 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6704 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6708 // Commute is back and try unpck* again.
6709 // FIXME: this seems wrong.
6710 CommuteVectorShuffleMask(M, NumElems);
6712 std::swap(V1IsSplat, V2IsSplat);
6715 if (isUNPCKLMask(M, VT, HasAVX2))
6716 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6718 if (isUNPCKHMask(M, VT, HasAVX2))
6719 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6722 // Normalize the node to match x86 shuffle ops if needed
6723 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6724 return CommuteVectorShuffle(SVOp, DAG);
6726 // The checks below are all present in isShuffleMaskLegal, but they are
6727 // inlined here right now to enable us to directly emit target specific
6728 // nodes, and remove one by one until they don't return Op anymore.
6730 if (isPALIGNRMask(M, VT, Subtarget))
6731 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6732 getShufflePALIGNRImmediate(SVOp),
6735 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6736 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6737 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6738 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6741 if (isPSHUFHWMask(M, VT, HasAVX2))
6742 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6743 getShufflePSHUFHWImmediate(SVOp),
6746 if (isPSHUFLWMask(M, VT, HasAVX2))
6747 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6748 getShufflePSHUFLWImmediate(SVOp),
6751 if (isSHUFPMask(M, VT, HasAVX))
6752 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6753 getShuffleSHUFImmediate(SVOp), DAG);
6755 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6756 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6757 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6758 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6760 //===--------------------------------------------------------------------===//
6761 // Generate target specific nodes for 128 or 256-bit shuffles only
6762 // supported in the AVX instruction set.
6765 // Handle VMOVDDUPY permutations
6766 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6767 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6769 // Handle VPERMILPS/D* permutations
6770 if (isVPERMILPMask(M, VT, HasAVX)) {
6771 if (HasAVX2 && VT == MVT::v8i32)
6772 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6773 getShuffleSHUFImmediate(SVOp), DAG);
6774 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6775 getShuffleSHUFImmediate(SVOp), DAG);
6778 // Handle VPERM2F128/VPERM2I128 permutations
6779 if (isVPERM2X128Mask(M, VT, HasAVX))
6780 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6781 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6783 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6784 if (BlendOp.getNode())
6787 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6788 SmallVector<SDValue, 8> permclMask;
6789 for (unsigned i = 0; i != 8; ++i) {
6790 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6792 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6794 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6795 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6796 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6799 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6800 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6801 getShuffleCLImmediate(SVOp), DAG);
6804 //===--------------------------------------------------------------------===//
6805 // Since no target specific shuffle was selected for this generic one,
6806 // lower it into other known shuffles. FIXME: this isn't true yet, but
6807 // this is the plan.
6810 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6811 if (VT == MVT::v8i16) {
6812 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6813 if (NewOp.getNode())
6817 if (VT == MVT::v16i8) {
6818 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6819 if (NewOp.getNode())
6823 // Handle all 128-bit wide vectors with 4 elements, and match them with
6824 // several different shuffle types.
6825 if (NumElems == 4 && VT.is128BitVector())
6826 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6828 // Handle general 256-bit shuffles
6829 if (VT.is256BitVector())
6830 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6836 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6837 SelectionDAG &DAG) const {
6838 EVT VT = Op.getValueType();
6839 DebugLoc dl = Op.getDebugLoc();
6841 if (!Op.getOperand(0).getValueType().is128BitVector())
6844 if (VT.getSizeInBits() == 8) {
6845 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6846 Op.getOperand(0), Op.getOperand(1));
6847 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6848 DAG.getValueType(VT));
6849 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6852 if (VT.getSizeInBits() == 16) {
6853 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6854 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6856 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6857 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6858 DAG.getNode(ISD::BITCAST, dl,
6862 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6863 Op.getOperand(0), Op.getOperand(1));
6864 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6865 DAG.getValueType(VT));
6866 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6869 if (VT == MVT::f32) {
6870 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6871 // the result back to FR32 register. It's only worth matching if the
6872 // result has a single use which is a store or a bitcast to i32. And in
6873 // the case of a store, it's not worth it if the index is a constant 0,
6874 // because a MOVSSmr can be used instead, which is smaller and faster.
6875 if (!Op.hasOneUse())
6877 SDNode *User = *Op.getNode()->use_begin();
6878 if ((User->getOpcode() != ISD::STORE ||
6879 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6880 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6881 (User->getOpcode() != ISD::BITCAST ||
6882 User->getValueType(0) != MVT::i32))
6884 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6885 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6888 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6891 if (VT == MVT::i32 || VT == MVT::i64) {
6892 // ExtractPS/pextrq works with constant index.
6893 if (isa<ConstantSDNode>(Op.getOperand(1)))
6901 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6902 SelectionDAG &DAG) const {
6903 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6906 SDValue Vec = Op.getOperand(0);
6907 EVT VecVT = Vec.getValueType();
6909 // If this is a 256-bit vector result, first extract the 128-bit vector and
6910 // then extract the element from the 128-bit vector.
6911 if (VecVT.is256BitVector()) {
6912 DebugLoc dl = Op.getNode()->getDebugLoc();
6913 unsigned NumElems = VecVT.getVectorNumElements();
6914 SDValue Idx = Op.getOperand(1);
6915 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6917 // Get the 128-bit vector.
6918 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6920 if (IdxVal >= NumElems/2)
6921 IdxVal -= NumElems/2;
6922 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6923 DAG.getConstant(IdxVal, MVT::i32));
6926 assert(VecVT.is128BitVector() && "Unexpected vector length");
6928 if (Subtarget->hasSSE41()) {
6929 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6934 EVT VT = Op.getValueType();
6935 DebugLoc dl = Op.getDebugLoc();
6936 // TODO: handle v16i8.
6937 if (VT.getSizeInBits() == 16) {
6938 SDValue Vec = Op.getOperand(0);
6939 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6941 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6942 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6943 DAG.getNode(ISD::BITCAST, dl,
6946 // Transform it so it match pextrw which produces a 32-bit result.
6947 EVT EltVT = MVT::i32;
6948 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6949 Op.getOperand(0), Op.getOperand(1));
6950 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6951 DAG.getValueType(VT));
6952 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6955 if (VT.getSizeInBits() == 32) {
6956 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6960 // SHUFPS the element to the lowest double word, then movss.
6961 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6962 EVT VVT = Op.getOperand(0).getValueType();
6963 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6964 DAG.getUNDEF(VVT), Mask);
6965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6966 DAG.getIntPtrConstant(0));
6969 if (VT.getSizeInBits() == 64) {
6970 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6971 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6972 // to match extract_elt for f64.
6973 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6977 // UNPCKHPD the element to the lowest double word, then movsd.
6978 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6979 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6980 int Mask[2] = { 1, -1 };
6981 EVT VVT = Op.getOperand(0).getValueType();
6982 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6983 DAG.getUNDEF(VVT), Mask);
6984 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6985 DAG.getIntPtrConstant(0));
6992 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6993 SelectionDAG &DAG) const {
6994 EVT VT = Op.getValueType();
6995 EVT EltVT = VT.getVectorElementType();
6996 DebugLoc dl = Op.getDebugLoc();
6998 SDValue N0 = Op.getOperand(0);
6999 SDValue N1 = Op.getOperand(1);
7000 SDValue N2 = Op.getOperand(2);
7002 if (!VT.is128BitVector())
7005 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7006 isa<ConstantSDNode>(N2)) {
7008 if (VT == MVT::v8i16)
7009 Opc = X86ISD::PINSRW;
7010 else if (VT == MVT::v16i8)
7011 Opc = X86ISD::PINSRB;
7013 Opc = X86ISD::PINSRB;
7015 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7017 if (N1.getValueType() != MVT::i32)
7018 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7019 if (N2.getValueType() != MVT::i32)
7020 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7021 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7024 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7025 // Bits [7:6] of the constant are the source select. This will always be
7026 // zero here. The DAG Combiner may combine an extract_elt index into these
7027 // bits. For example (insert (extract, 3), 2) could be matched by putting
7028 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7029 // Bits [5:4] of the constant are the destination select. This is the
7030 // value of the incoming immediate.
7031 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7032 // combine either bitwise AND or insert of float 0.0 to set these bits.
7033 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7034 // Create this as a scalar to vector..
7035 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7036 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7039 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7040 // PINSR* works with constant index.
7047 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7048 EVT VT = Op.getValueType();
7049 EVT EltVT = VT.getVectorElementType();
7051 DebugLoc dl = Op.getDebugLoc();
7052 SDValue N0 = Op.getOperand(0);
7053 SDValue N1 = Op.getOperand(1);
7054 SDValue N2 = Op.getOperand(2);
7056 // If this is a 256-bit vector result, first extract the 128-bit vector,
7057 // insert the element into the extracted half and then place it back.
7058 if (VT.is256BitVector()) {
7059 if (!isa<ConstantSDNode>(N2))
7062 // Get the desired 128-bit vector half.
7063 unsigned NumElems = VT.getVectorNumElements();
7064 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7065 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7067 // Insert the element into the desired half.
7068 bool Upper = IdxVal >= NumElems/2;
7069 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7070 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7072 // Insert the changed part back to the 256-bit vector
7073 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7076 if (Subtarget->hasSSE41())
7077 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7079 if (EltVT == MVT::i8)
7082 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7083 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7084 // as its second argument.
7085 if (N1.getValueType() != MVT::i32)
7086 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7087 if (N2.getValueType() != MVT::i32)
7088 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7089 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7095 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7096 LLVMContext *Context = DAG.getContext();
7097 DebugLoc dl = Op.getDebugLoc();
7098 EVT OpVT = Op.getValueType();
7100 // If this is a 256-bit vector result, first insert into a 128-bit
7101 // vector and then insert into the 256-bit vector.
7102 if (!OpVT.is128BitVector()) {
7103 // Insert into a 128-bit vector.
7104 EVT VT128 = EVT::getVectorVT(*Context,
7105 OpVT.getVectorElementType(),
7106 OpVT.getVectorNumElements() / 2);
7108 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7110 // Insert the 128-bit vector.
7111 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7114 if (OpVT == MVT::v1i64 &&
7115 Op.getOperand(0).getValueType() == MVT::i64)
7116 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7118 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7119 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7120 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7121 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7124 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7125 // a simple subregister reference or explicit instructions to grab
7126 // upper bits of a vector.
7128 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7129 if (Subtarget->hasAVX()) {
7130 DebugLoc dl = Op.getNode()->getDebugLoc();
7131 SDValue Vec = Op.getNode()->getOperand(0);
7132 SDValue Idx = Op.getNode()->getOperand(1);
7134 if (Op.getNode()->getValueType(0).is128BitVector() &&
7135 Vec.getNode()->getValueType(0).is256BitVector() &&
7136 isa<ConstantSDNode>(Idx)) {
7137 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7138 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7144 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7145 // simple superregister reference or explicit instructions to insert
7146 // the upper bits of a vector.
7148 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7149 if (Subtarget->hasAVX()) {
7150 DebugLoc dl = Op.getNode()->getDebugLoc();
7151 SDValue Vec = Op.getNode()->getOperand(0);
7152 SDValue SubVec = Op.getNode()->getOperand(1);
7153 SDValue Idx = Op.getNode()->getOperand(2);
7155 if (Op.getNode()->getValueType(0).is256BitVector() &&
7156 SubVec.getNode()->getValueType(0).is128BitVector() &&
7157 isa<ConstantSDNode>(Idx)) {
7158 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7159 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7165 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7166 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7167 // one of the above mentioned nodes. It has to be wrapped because otherwise
7168 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7169 // be used to form addressing mode. These wrapped nodes will be selected
7172 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7173 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7175 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7177 unsigned char OpFlag = 0;
7178 unsigned WrapperKind = X86ISD::Wrapper;
7179 CodeModel::Model M = getTargetMachine().getCodeModel();
7181 if (Subtarget->isPICStyleRIPRel() &&
7182 (M == CodeModel::Small || M == CodeModel::Kernel))
7183 WrapperKind = X86ISD::WrapperRIP;
7184 else if (Subtarget->isPICStyleGOT())
7185 OpFlag = X86II::MO_GOTOFF;
7186 else if (Subtarget->isPICStyleStubPIC())
7187 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7189 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7191 CP->getOffset(), OpFlag);
7192 DebugLoc DL = CP->getDebugLoc();
7193 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7194 // With PIC, the address is actually $g + Offset.
7196 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7197 DAG.getNode(X86ISD::GlobalBaseReg,
7198 DebugLoc(), getPointerTy()),
7205 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7206 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7208 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7210 unsigned char OpFlag = 0;
7211 unsigned WrapperKind = X86ISD::Wrapper;
7212 CodeModel::Model M = getTargetMachine().getCodeModel();
7214 if (Subtarget->isPICStyleRIPRel() &&
7215 (M == CodeModel::Small || M == CodeModel::Kernel))
7216 WrapperKind = X86ISD::WrapperRIP;
7217 else if (Subtarget->isPICStyleGOT())
7218 OpFlag = X86II::MO_GOTOFF;
7219 else if (Subtarget->isPICStyleStubPIC())
7220 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7222 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7224 DebugLoc DL = JT->getDebugLoc();
7225 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7227 // With PIC, the address is actually $g + Offset.
7229 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7230 DAG.getNode(X86ISD::GlobalBaseReg,
7231 DebugLoc(), getPointerTy()),
7238 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7239 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7241 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7243 unsigned char OpFlag = 0;
7244 unsigned WrapperKind = X86ISD::Wrapper;
7245 CodeModel::Model M = getTargetMachine().getCodeModel();
7247 if (Subtarget->isPICStyleRIPRel() &&
7248 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7249 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7250 OpFlag = X86II::MO_GOTPCREL;
7251 WrapperKind = X86ISD::WrapperRIP;
7252 } else if (Subtarget->isPICStyleGOT()) {
7253 OpFlag = X86II::MO_GOT;
7254 } else if (Subtarget->isPICStyleStubPIC()) {
7255 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7256 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7257 OpFlag = X86II::MO_DARWIN_NONLAZY;
7260 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7262 DebugLoc DL = Op.getDebugLoc();
7263 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7266 // With PIC, the address is actually $g + Offset.
7267 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7268 !Subtarget->is64Bit()) {
7269 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7270 DAG.getNode(X86ISD::GlobalBaseReg,
7271 DebugLoc(), getPointerTy()),
7275 // For symbols that require a load from a stub to get the address, emit the
7277 if (isGlobalStubReference(OpFlag))
7278 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7279 MachinePointerInfo::getGOT(), false, false, false, 0);
7285 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7286 // Create the TargetBlockAddressAddress node.
7287 unsigned char OpFlags =
7288 Subtarget->ClassifyBlockAddressReference();
7289 CodeModel::Model M = getTargetMachine().getCodeModel();
7290 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7291 DebugLoc dl = Op.getDebugLoc();
7292 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7293 /*isTarget=*/true, OpFlags);
7295 if (Subtarget->isPICStyleRIPRel() &&
7296 (M == CodeModel::Small || M == CodeModel::Kernel))
7297 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7299 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7301 // With PIC, the address is actually $g + Offset.
7302 if (isGlobalRelativeToPICBase(OpFlags)) {
7303 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7304 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7312 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7314 SelectionDAG &DAG) const {
7315 // Create the TargetGlobalAddress node, folding in the constant
7316 // offset if it is legal.
7317 unsigned char OpFlags =
7318 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7319 CodeModel::Model M = getTargetMachine().getCodeModel();
7321 if (OpFlags == X86II::MO_NO_FLAG &&
7322 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7323 // A direct static reference to a global.
7324 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7327 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7330 if (Subtarget->isPICStyleRIPRel() &&
7331 (M == CodeModel::Small || M == CodeModel::Kernel))
7332 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7334 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7336 // With PIC, the address is actually $g + Offset.
7337 if (isGlobalRelativeToPICBase(OpFlags)) {
7338 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7339 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7343 // For globals that require a load from a stub to get the address, emit the
7345 if (isGlobalStubReference(OpFlags))
7346 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7347 MachinePointerInfo::getGOT(), false, false, false, 0);
7349 // If there was a non-zero offset that we didn't fold, create an explicit
7352 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7353 DAG.getConstant(Offset, getPointerTy()));
7359 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7360 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7361 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7362 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7366 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7367 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7368 unsigned char OperandFlags, bool LocalDynamic = false) {
7369 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7370 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7371 DebugLoc dl = GA->getDebugLoc();
7372 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7373 GA->getValueType(0),
7377 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7381 SDValue Ops[] = { Chain, TGA, *InFlag };
7382 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7384 SDValue Ops[] = { Chain, TGA };
7385 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7388 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7389 MFI->setAdjustsStack(true);
7391 SDValue Flag = Chain.getValue(1);
7392 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7395 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7397 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7400 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7401 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7402 DAG.getNode(X86ISD::GlobalBaseReg,
7403 DebugLoc(), PtrVT), InFlag);
7404 InFlag = Chain.getValue(1);
7406 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7409 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7411 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7413 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7414 X86::RAX, X86II::MO_TLSGD);
7417 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7421 DebugLoc dl = GA->getDebugLoc();
7423 // Get the start address of the TLS block for this module.
7424 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7425 .getInfo<X86MachineFunctionInfo>();
7426 MFI->incNumLocalDynamicTLSAccesses();
7430 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7431 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7434 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7435 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7436 InFlag = Chain.getValue(1);
7437 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7438 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7441 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7445 unsigned char OperandFlags = X86II::MO_DTPOFF;
7446 unsigned WrapperKind = X86ISD::Wrapper;
7447 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7448 GA->getValueType(0),
7449 GA->getOffset(), OperandFlags);
7450 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7452 // Add x@dtpoff with the base.
7453 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7456 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7457 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7458 const EVT PtrVT, TLSModel::Model model,
7459 bool is64Bit, bool isPIC) {
7460 DebugLoc dl = GA->getDebugLoc();
7462 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7463 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7464 is64Bit ? 257 : 256));
7466 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7467 DAG.getIntPtrConstant(0),
7468 MachinePointerInfo(Ptr),
7469 false, false, false, 0);
7471 unsigned char OperandFlags = 0;
7472 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7474 unsigned WrapperKind = X86ISD::Wrapper;
7475 if (model == TLSModel::LocalExec) {
7476 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7477 } else if (model == TLSModel::InitialExec) {
7479 OperandFlags = X86II::MO_GOTTPOFF;
7480 WrapperKind = X86ISD::WrapperRIP;
7482 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7485 llvm_unreachable("Unexpected model");
7488 // emit "addl x@ntpoff,%eax" (local exec)
7489 // or "addl x@indntpoff,%eax" (initial exec)
7490 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7491 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7492 GA->getValueType(0),
7493 GA->getOffset(), OperandFlags);
7494 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7496 if (model == TLSModel::InitialExec) {
7497 if (isPIC && !is64Bit) {
7498 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7499 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7503 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7504 MachinePointerInfo::getGOT(), false, false, false,
7508 // The address of the thread local variable is the add of the thread
7509 // pointer with the offset of the variable.
7510 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7514 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7516 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7517 const GlobalValue *GV = GA->getGlobal();
7519 if (Subtarget->isTargetELF()) {
7520 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7523 case TLSModel::GeneralDynamic:
7524 if (Subtarget->is64Bit())
7525 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7526 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7527 case TLSModel::LocalDynamic:
7528 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7529 Subtarget->is64Bit());
7530 case TLSModel::InitialExec:
7531 case TLSModel::LocalExec:
7532 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7533 Subtarget->is64Bit(),
7534 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7536 llvm_unreachable("Unknown TLS model.");
7539 if (Subtarget->isTargetDarwin()) {
7540 // Darwin only has one model of TLS. Lower to that.
7541 unsigned char OpFlag = 0;
7542 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7543 X86ISD::WrapperRIP : X86ISD::Wrapper;
7545 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7547 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7548 !Subtarget->is64Bit();
7550 OpFlag = X86II::MO_TLVP_PIC_BASE;
7552 OpFlag = X86II::MO_TLVP;
7553 DebugLoc DL = Op.getDebugLoc();
7554 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7555 GA->getValueType(0),
7556 GA->getOffset(), OpFlag);
7557 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7559 // With PIC32, the address is actually $g + Offset.
7561 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7562 DAG.getNode(X86ISD::GlobalBaseReg,
7563 DebugLoc(), getPointerTy()),
7566 // Lowering the machine isd will make sure everything is in the right
7568 SDValue Chain = DAG.getEntryNode();
7569 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7570 SDValue Args[] = { Chain, Offset };
7571 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7573 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7574 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7575 MFI->setAdjustsStack(true);
7577 // And our return value (tls address) is in the standard call return value
7579 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7580 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7584 if (Subtarget->isTargetWindows()) {
7585 // Just use the implicit TLS architecture
7586 // Need to generate someting similar to:
7587 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7589 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7590 // mov rcx, qword [rdx+rcx*8]
7591 // mov eax, .tls$:tlsvar
7592 // [rax+rcx] contains the address
7593 // Windows 64bit: gs:0x58
7594 // Windows 32bit: fs:__tls_array
7596 // If GV is an alias then use the aliasee for determining
7597 // thread-localness.
7598 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7599 GV = GA->resolveAliasedGlobal(false);
7600 DebugLoc dl = GA->getDebugLoc();
7601 SDValue Chain = DAG.getEntryNode();
7603 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7604 // %gs:0x58 (64-bit).
7605 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7606 ? Type::getInt8PtrTy(*DAG.getContext(),
7608 : Type::getInt32PtrTy(*DAG.getContext(),
7611 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7612 Subtarget->is64Bit()
7613 ? DAG.getIntPtrConstant(0x58)
7614 : DAG.getExternalSymbol("_tls_array",
7616 MachinePointerInfo(Ptr),
7617 false, false, false, 0);
7619 // Load the _tls_index variable
7620 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7621 if (Subtarget->is64Bit())
7622 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7623 IDX, MachinePointerInfo(), MVT::i32,
7626 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7627 false, false, false, 0);
7629 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7631 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7633 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7634 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7635 false, false, false, 0);
7637 // Get the offset of start of .tls section
7638 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7639 GA->getValueType(0),
7640 GA->getOffset(), X86II::MO_SECREL);
7641 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7643 // The address of the thread local variable is the add of the thread
7644 // pointer with the offset of the variable.
7645 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7648 llvm_unreachable("TLS not implemented for this target.");
7652 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7653 /// and take a 2 x i32 value to shift plus a shift amount.
7654 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7655 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7656 EVT VT = Op.getValueType();
7657 unsigned VTBits = VT.getSizeInBits();
7658 DebugLoc dl = Op.getDebugLoc();
7659 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7660 SDValue ShOpLo = Op.getOperand(0);
7661 SDValue ShOpHi = Op.getOperand(1);
7662 SDValue ShAmt = Op.getOperand(2);
7663 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7664 DAG.getConstant(VTBits - 1, MVT::i8))
7665 : DAG.getConstant(0, VT);
7668 if (Op.getOpcode() == ISD::SHL_PARTS) {
7669 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7670 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7672 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7673 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7676 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7677 DAG.getConstant(VTBits, MVT::i8));
7678 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7679 AndNode, DAG.getConstant(0, MVT::i8));
7682 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7683 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7684 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7686 if (Op.getOpcode() == ISD::SHL_PARTS) {
7687 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7688 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7690 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7691 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7694 SDValue Ops[2] = { Lo, Hi };
7695 return DAG.getMergeValues(Ops, 2, dl);
7698 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7699 SelectionDAG &DAG) const {
7700 EVT SrcVT = Op.getOperand(0).getValueType();
7702 if (SrcVT.isVector())
7705 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7706 "Unknown SINT_TO_FP to lower!");
7708 // These are really Legal; return the operand so the caller accepts it as
7710 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7712 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7713 Subtarget->is64Bit()) {
7717 DebugLoc dl = Op.getDebugLoc();
7718 unsigned Size = SrcVT.getSizeInBits()/8;
7719 MachineFunction &MF = DAG.getMachineFunction();
7720 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7721 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7722 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7724 MachinePointerInfo::getFixedStack(SSFI),
7726 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7729 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7731 SelectionDAG &DAG) const {
7733 DebugLoc DL = Op.getDebugLoc();
7735 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7737 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7739 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7741 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7743 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7744 MachineMemOperand *MMO;
7746 int SSFI = FI->getIndex();
7748 DAG.getMachineFunction()
7749 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7750 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7752 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7753 StackSlot = StackSlot.getOperand(1);
7755 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7756 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7758 Tys, Ops, array_lengthof(Ops),
7762 Chain = Result.getValue(1);
7763 SDValue InFlag = Result.getValue(2);
7765 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7766 // shouldn't be necessary except that RFP cannot be live across
7767 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7768 MachineFunction &MF = DAG.getMachineFunction();
7769 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7770 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7771 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7772 Tys = DAG.getVTList(MVT::Other);
7774 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7776 MachineMemOperand *MMO =
7777 DAG.getMachineFunction()
7778 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7779 MachineMemOperand::MOStore, SSFISize, SSFISize);
7781 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7782 Ops, array_lengthof(Ops),
7783 Op.getValueType(), MMO);
7784 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7785 MachinePointerInfo::getFixedStack(SSFI),
7786 false, false, false, 0);
7792 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7793 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7794 SelectionDAG &DAG) const {
7795 // This algorithm is not obvious. Here it is what we're trying to output:
7798 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7799 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7803 pshufd $0x4e, %xmm0, %xmm1
7808 DebugLoc dl = Op.getDebugLoc();
7809 LLVMContext *Context = DAG.getContext();
7811 // Build some magic constants.
7812 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7813 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7814 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7816 SmallVector<Constant*,2> CV1;
7818 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7820 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7821 Constant *C1 = ConstantVector::get(CV1);
7822 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7824 // Load the 64-bit value into an XMM register.
7825 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7827 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7828 MachinePointerInfo::getConstantPool(),
7829 false, false, false, 16);
7830 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7831 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7834 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7835 MachinePointerInfo::getConstantPool(),
7836 false, false, false, 16);
7837 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7838 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7841 if (Subtarget->hasSSE3()) {
7842 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7843 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7845 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7846 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7848 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7849 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7854 DAG.getIntPtrConstant(0));
7857 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7858 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7859 SelectionDAG &DAG) const {
7860 DebugLoc dl = Op.getDebugLoc();
7861 // FP constant to bias correct the final result.
7862 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7865 // Load the 32-bit value into an XMM register.
7866 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7869 // Zero out the upper parts of the register.
7870 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7872 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7873 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7874 DAG.getIntPtrConstant(0));
7876 // Or the load with the bias.
7877 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7878 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7879 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7881 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7882 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7883 MVT::v2f64, Bias)));
7884 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7885 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7886 DAG.getIntPtrConstant(0));
7888 // Subtract the bias.
7889 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7891 // Handle final rounding.
7892 EVT DestVT = Op.getValueType();
7894 if (DestVT.bitsLT(MVT::f64))
7895 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7896 DAG.getIntPtrConstant(0));
7897 if (DestVT.bitsGT(MVT::f64))
7898 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7900 // Handle final rounding.
7904 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7905 SelectionDAG &DAG) const {
7906 SDValue N0 = Op.getOperand(0);
7907 DebugLoc dl = Op.getDebugLoc();
7909 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7910 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7911 // the optimization here.
7912 if (DAG.SignBitIsZero(N0))
7913 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7915 EVT SrcVT = N0.getValueType();
7916 EVT DstVT = Op.getValueType();
7917 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7918 return LowerUINT_TO_FP_i64(Op, DAG);
7919 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7920 return LowerUINT_TO_FP_i32(Op, DAG);
7921 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7924 // Make a 64-bit buffer, and use it to build an FILD.
7925 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7926 if (SrcVT == MVT::i32) {
7927 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7928 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7929 getPointerTy(), StackSlot, WordOff);
7930 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7931 StackSlot, MachinePointerInfo(),
7933 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7934 OffsetSlot, MachinePointerInfo(),
7936 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7940 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7941 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7942 StackSlot, MachinePointerInfo(),
7944 // For i64 source, we need to add the appropriate power of 2 if the input
7945 // was negative. This is the same as the optimization in
7946 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7947 // we must be careful to do the computation in x87 extended precision, not
7948 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7949 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7950 MachineMemOperand *MMO =
7951 DAG.getMachineFunction()
7952 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7953 MachineMemOperand::MOLoad, 8, 8);
7955 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7956 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7957 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7960 APInt FF(32, 0x5F800000ULL);
7962 // Check whether the sign bit is set.
7963 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7964 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7967 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7968 SDValue FudgePtr = DAG.getConstantPool(
7969 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7972 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7973 SDValue Zero = DAG.getIntPtrConstant(0);
7974 SDValue Four = DAG.getIntPtrConstant(4);
7975 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7977 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7979 // Load the value out, extending it from f32 to f80.
7980 // FIXME: Avoid the extend by constructing the right constant pool?
7981 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7982 FudgePtr, MachinePointerInfo::getConstantPool(),
7983 MVT::f32, false, false, 4);
7984 // Extend everything to 80 bits to force it to be done on x87.
7985 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7986 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7989 std::pair<SDValue,SDValue> X86TargetLowering::
7990 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7991 DebugLoc DL = Op.getDebugLoc();
7993 EVT DstTy = Op.getValueType();
7995 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7996 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8000 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8001 DstTy.getSimpleVT() >= MVT::i16 &&
8002 "Unknown FP_TO_INT to lower!");
8004 // These are really Legal.
8005 if (DstTy == MVT::i32 &&
8006 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8007 return std::make_pair(SDValue(), SDValue());
8008 if (Subtarget->is64Bit() &&
8009 DstTy == MVT::i64 &&
8010 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8011 return std::make_pair(SDValue(), SDValue());
8013 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8014 // stack slot, or into the FTOL runtime function.
8015 MachineFunction &MF = DAG.getMachineFunction();
8016 unsigned MemSize = DstTy.getSizeInBits()/8;
8017 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8018 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8021 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8022 Opc = X86ISD::WIN_FTOL;
8024 switch (DstTy.getSimpleVT().SimpleTy) {
8025 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8026 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8027 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8028 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8031 SDValue Chain = DAG.getEntryNode();
8032 SDValue Value = Op.getOperand(0);
8033 EVT TheVT = Op.getOperand(0).getValueType();
8034 // FIXME This causes a redundant load/store if the SSE-class value is already
8035 // in memory, such as if it is on the callstack.
8036 if (isScalarFPTypeInSSEReg(TheVT)) {
8037 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8038 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8039 MachinePointerInfo::getFixedStack(SSFI),
8041 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8043 Chain, StackSlot, DAG.getValueType(TheVT)
8046 MachineMemOperand *MMO =
8047 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8048 MachineMemOperand::MOLoad, MemSize, MemSize);
8049 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8051 Chain = Value.getValue(1);
8052 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8053 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8056 MachineMemOperand *MMO =
8057 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8058 MachineMemOperand::MOStore, MemSize, MemSize);
8060 if (Opc != X86ISD::WIN_FTOL) {
8061 // Build the FP_TO_INT*_IN_MEM
8062 SDValue Ops[] = { Chain, Value, StackSlot };
8063 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8064 Ops, 3, DstTy, MMO);
8065 return std::make_pair(FIST, StackSlot);
8067 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8068 DAG.getVTList(MVT::Other, MVT::Glue),
8070 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8071 MVT::i32, ftol.getValue(1));
8072 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8073 MVT::i32, eax.getValue(2));
8074 SDValue Ops[] = { eax, edx };
8075 SDValue pair = IsReplace
8076 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8077 : DAG.getMergeValues(Ops, 2, DL);
8078 return std::make_pair(pair, SDValue());
8082 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8083 SelectionDAG &DAG) const {
8084 if (Op.getValueType().isVector())
8087 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8088 /*IsSigned=*/ true, /*IsReplace=*/ false);
8089 SDValue FIST = Vals.first, StackSlot = Vals.second;
8090 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8091 if (FIST.getNode() == 0) return Op;
8093 if (StackSlot.getNode())
8095 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8096 FIST, StackSlot, MachinePointerInfo(),
8097 false, false, false, 0);
8099 // The node is the result.
8103 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8104 SelectionDAG &DAG) const {
8105 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8106 /*IsSigned=*/ false, /*IsReplace=*/ false);
8107 SDValue FIST = Vals.first, StackSlot = Vals.second;
8108 assert(FIST.getNode() && "Unexpected failure");
8110 if (StackSlot.getNode())
8112 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8113 FIST, StackSlot, MachinePointerInfo(),
8114 false, false, false, 0);
8116 // The node is the result.
8120 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8121 SelectionDAG &DAG) const {
8122 LLVMContext *Context = DAG.getContext();
8123 DebugLoc dl = Op.getDebugLoc();
8124 EVT VT = Op.getValueType();
8127 EltVT = VT.getVectorElementType();
8129 if (EltVT == MVT::f64) {
8130 C = ConstantVector::getSplat(2,
8131 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8133 C = ConstantVector::getSplat(4,
8134 ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8136 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8137 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8138 MachinePointerInfo::getConstantPool(),
8139 false, false, false, 16);
8140 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8143 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8144 LLVMContext *Context = DAG.getContext();
8145 DebugLoc dl = Op.getDebugLoc();
8146 EVT VT = Op.getValueType();
8148 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8149 if (VT.isVector()) {
8150 EltVT = VT.getVectorElementType();
8151 NumElts = VT.getVectorNumElements();
8154 if (EltVT == MVT::f64)
8155 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8157 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8158 C = ConstantVector::getSplat(NumElts, C);
8159 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8160 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8161 MachinePointerInfo::getConstantPool(),
8162 false, false, false, 16);
8163 if (VT.isVector()) {
8164 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8165 return DAG.getNode(ISD::BITCAST, dl, VT,
8166 DAG.getNode(ISD::XOR, dl, XORVT,
8167 DAG.getNode(ISD::BITCAST, dl, XORVT,
8169 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8172 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8175 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8176 LLVMContext *Context = DAG.getContext();
8177 SDValue Op0 = Op.getOperand(0);
8178 SDValue Op1 = Op.getOperand(1);
8179 DebugLoc dl = Op.getDebugLoc();
8180 EVT VT = Op.getValueType();
8181 EVT SrcVT = Op1.getValueType();
8183 // If second operand is smaller, extend it first.
8184 if (SrcVT.bitsLT(VT)) {
8185 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8188 // And if it is bigger, shrink it first.
8189 if (SrcVT.bitsGT(VT)) {
8190 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8194 // At this point the operands and the result should have the same
8195 // type, and that won't be f80 since that is not custom lowered.
8197 // First get the sign bit of second operand.
8198 SmallVector<Constant*,4> CV;
8199 if (SrcVT == MVT::f64) {
8200 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8201 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8203 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8204 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8205 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8206 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8208 Constant *C = ConstantVector::get(CV);
8209 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8210 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8211 MachinePointerInfo::getConstantPool(),
8212 false, false, false, 16);
8213 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8215 // Shift sign bit right or left if the two operands have different types.
8216 if (SrcVT.bitsGT(VT)) {
8217 // Op0 is MVT::f32, Op1 is MVT::f64.
8218 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8219 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8220 DAG.getConstant(32, MVT::i32));
8221 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8222 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8223 DAG.getIntPtrConstant(0));
8226 // Clear first operand sign bit.
8228 if (VT == MVT::f64) {
8229 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8230 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8232 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8233 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8234 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8235 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8237 C = ConstantVector::get(CV);
8238 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8239 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8240 MachinePointerInfo::getConstantPool(),
8241 false, false, false, 16);
8242 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8244 // Or the value with the sign bit.
8245 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8248 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8249 SDValue N0 = Op.getOperand(0);
8250 DebugLoc dl = Op.getDebugLoc();
8251 EVT VT = Op.getValueType();
8253 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8254 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8255 DAG.getConstant(1, VT));
8256 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8259 /// Emit nodes that will be selected as "test Op0,Op0", or something
8261 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8262 SelectionDAG &DAG) const {
8263 DebugLoc dl = Op.getDebugLoc();
8265 // CF and OF aren't always set the way we want. Determine which
8266 // of these we need.
8267 bool NeedCF = false;
8268 bool NeedOF = false;
8271 case X86::COND_A: case X86::COND_AE:
8272 case X86::COND_B: case X86::COND_BE:
8275 case X86::COND_G: case X86::COND_GE:
8276 case X86::COND_L: case X86::COND_LE:
8277 case X86::COND_O: case X86::COND_NO:
8282 // See if we can use the EFLAGS value from the operand instead of
8283 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8284 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8285 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8286 // Emit a CMP with 0, which is the TEST pattern.
8287 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8288 DAG.getConstant(0, Op.getValueType()));
8290 unsigned Opcode = 0;
8291 unsigned NumOperands = 0;
8293 // Truncate operations may prevent the merge of the SETCC instruction
8294 // and the arithmetic intruction before it. Attempt to truncate the operands
8295 // of the arithmetic instruction and use a reduced bit-width instruction.
8296 bool NeedTruncation = false;
8297 SDValue ArithOp = Op;
8298 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8299 SDValue Arith = Op->getOperand(0);
8300 // Both the trunc and the arithmetic op need to have one user each.
8301 if (Arith->hasOneUse())
8302 switch (Arith.getOpcode()) {
8309 NeedTruncation = true;
8315 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8316 // which may be the result of a CAST. We use the variable 'Op', which is the
8317 // non-casted variable when we check for possible users.
8318 switch (ArithOp.getOpcode()) {
8320 // Due to an isel shortcoming, be conservative if this add is likely to be
8321 // selected as part of a load-modify-store instruction. When the root node
8322 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8323 // uses of other nodes in the match, such as the ADD in this case. This
8324 // leads to the ADD being left around and reselected, with the result being
8325 // two adds in the output. Alas, even if none our users are stores, that
8326 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8327 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8328 // climbing the DAG back to the root, and it doesn't seem to be worth the
8330 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8331 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8332 if (UI->getOpcode() != ISD::CopyToReg &&
8333 UI->getOpcode() != ISD::SETCC &&
8334 UI->getOpcode() != ISD::STORE)
8337 if (ConstantSDNode *C =
8338 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8339 // An add of one will be selected as an INC.
8340 if (C->getAPIntValue() == 1) {
8341 Opcode = X86ISD::INC;
8346 // An add of negative one (subtract of one) will be selected as a DEC.
8347 if (C->getAPIntValue().isAllOnesValue()) {
8348 Opcode = X86ISD::DEC;
8354 // Otherwise use a regular EFLAGS-setting add.
8355 Opcode = X86ISD::ADD;
8359 // If the primary and result isn't used, don't bother using X86ISD::AND,
8360 // because a TEST instruction will be better.
8361 bool NonFlagUse = false;
8362 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8363 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8365 unsigned UOpNo = UI.getOperandNo();
8366 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8367 // Look pass truncate.
8368 UOpNo = User->use_begin().getOperandNo();
8369 User = *User->use_begin();
8372 if (User->getOpcode() != ISD::BRCOND &&
8373 User->getOpcode() != ISD::SETCC &&
8374 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8387 // Due to the ISEL shortcoming noted above, be conservative if this op is
8388 // likely to be selected as part of a load-modify-store instruction.
8389 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8390 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8391 if (UI->getOpcode() == ISD::STORE)
8394 // Otherwise use a regular EFLAGS-setting instruction.
8395 switch (ArithOp.getOpcode()) {
8396 default: llvm_unreachable("unexpected operator!");
8397 case ISD::SUB: Opcode = X86ISD::SUB; break;
8398 case ISD::OR: Opcode = X86ISD::OR; break;
8399 case ISD::XOR: Opcode = X86ISD::XOR; break;
8400 case ISD::AND: Opcode = X86ISD::AND; break;
8412 return SDValue(Op.getNode(), 1);
8418 // If we found that truncation is beneficial, perform the truncation and
8420 if (NeedTruncation) {
8421 EVT VT = Op.getValueType();
8422 SDValue WideVal = Op->getOperand(0);
8423 EVT WideVT = WideVal.getValueType();
8424 unsigned ConvertedOp = 0;
8425 // Use a target machine opcode to prevent further DAGCombine
8426 // optimizations that may separate the arithmetic operations
8427 // from the setcc node.
8428 switch (WideVal.getOpcode()) {
8430 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8431 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8432 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8433 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8434 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8438 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8439 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8440 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8441 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8442 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8448 // Emit a CMP with 0, which is the TEST pattern.
8449 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8450 DAG.getConstant(0, Op.getValueType()));
8452 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8453 SmallVector<SDValue, 4> Ops;
8454 for (unsigned i = 0; i != NumOperands; ++i)
8455 Ops.push_back(Op.getOperand(i));
8457 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8458 DAG.ReplaceAllUsesWith(Op, New);
8459 return SDValue(New.getNode(), 1);
8462 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8464 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8465 SelectionDAG &DAG) const {
8466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8467 if (C->getAPIntValue() == 0)
8468 return EmitTest(Op0, X86CC, DAG);
8470 DebugLoc dl = Op0.getDebugLoc();
8471 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8472 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8473 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8474 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8475 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8477 return SDValue(Sub.getNode(), 1);
8479 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8482 /// Convert a comparison if required by the subtarget.
8483 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8484 SelectionDAG &DAG) const {
8485 // If the subtarget does not support the FUCOMI instruction, floating-point
8486 // comparisons have to be converted.
8487 if (Subtarget->hasCMov() ||
8488 Cmp.getOpcode() != X86ISD::CMP ||
8489 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8490 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8493 // The instruction selector will select an FUCOM instruction instead of
8494 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8495 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8496 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8497 DebugLoc dl = Cmp.getDebugLoc();
8498 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8499 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8500 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8501 DAG.getConstant(8, MVT::i8));
8502 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8503 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8506 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8507 /// if it's possible.
8508 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8509 DebugLoc dl, SelectionDAG &DAG) const {
8510 SDValue Op0 = And.getOperand(0);
8511 SDValue Op1 = And.getOperand(1);
8512 if (Op0.getOpcode() == ISD::TRUNCATE)
8513 Op0 = Op0.getOperand(0);
8514 if (Op1.getOpcode() == ISD::TRUNCATE)
8515 Op1 = Op1.getOperand(0);
8518 if (Op1.getOpcode() == ISD::SHL)
8519 std::swap(Op0, Op1);
8520 if (Op0.getOpcode() == ISD::SHL) {
8521 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8522 if (And00C->getZExtValue() == 1) {
8523 // If we looked past a truncate, check that it's only truncating away
8525 unsigned BitWidth = Op0.getValueSizeInBits();
8526 unsigned AndBitWidth = And.getValueSizeInBits();
8527 if (BitWidth > AndBitWidth) {
8529 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8530 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8534 RHS = Op0.getOperand(1);
8536 } else if (Op1.getOpcode() == ISD::Constant) {
8537 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8538 uint64_t AndRHSVal = AndRHS->getZExtValue();
8539 SDValue AndLHS = Op0;
8541 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8542 LHS = AndLHS.getOperand(0);
8543 RHS = AndLHS.getOperand(1);
8546 // Use BT if the immediate can't be encoded in a TEST instruction.
8547 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8549 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8553 if (LHS.getNode()) {
8554 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8555 // instruction. Since the shift amount is in-range-or-undefined, we know
8556 // that doing a bittest on the i32 value is ok. We extend to i32 because
8557 // the encoding for the i16 version is larger than the i32 version.
8558 // Also promote i16 to i32 for performance / code size reason.
8559 if (LHS.getValueType() == MVT::i8 ||
8560 LHS.getValueType() == MVT::i16)
8561 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8563 // If the operand types disagree, extend the shift amount to match. Since
8564 // BT ignores high bits (like shifts) we can use anyextend.
8565 if (LHS.getValueType() != RHS.getValueType())
8566 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8568 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8569 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8570 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8571 DAG.getConstant(Cond, MVT::i8), BT);
8577 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8579 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8581 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8582 SDValue Op0 = Op.getOperand(0);
8583 SDValue Op1 = Op.getOperand(1);
8584 DebugLoc dl = Op.getDebugLoc();
8585 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8587 // Optimize to BT if possible.
8588 // Lower (X & (1 << N)) == 0 to BT(X, N).
8589 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8590 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8591 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8592 Op1.getOpcode() == ISD::Constant &&
8593 cast<ConstantSDNode>(Op1)->isNullValue() &&
8594 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8595 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8596 if (NewSetCC.getNode())
8600 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8602 if (Op1.getOpcode() == ISD::Constant &&
8603 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8604 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8605 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8607 // If the input is a setcc, then reuse the input setcc or use a new one with
8608 // the inverted condition.
8609 if (Op0.getOpcode() == X86ISD::SETCC) {
8610 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8611 bool Invert = (CC == ISD::SETNE) ^
8612 cast<ConstantSDNode>(Op1)->isNullValue();
8613 if (!Invert) return Op0;
8615 CCode = X86::GetOppositeBranchCondition(CCode);
8616 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8617 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8621 bool isFP = Op1.getValueType().isFloatingPoint();
8622 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8623 if (X86CC == X86::COND_INVALID)
8626 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8627 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8628 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8629 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8632 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8633 // ones, and then concatenate the result back.
8634 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8635 EVT VT = Op.getValueType();
8637 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8638 "Unsupported value type for operation");
8640 unsigned NumElems = VT.getVectorNumElements();
8641 DebugLoc dl = Op.getDebugLoc();
8642 SDValue CC = Op.getOperand(2);
8644 // Extract the LHS vectors
8645 SDValue LHS = Op.getOperand(0);
8646 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8647 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8649 // Extract the RHS vectors
8650 SDValue RHS = Op.getOperand(1);
8651 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8652 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8654 // Issue the operation on the smaller types and concatenate the result back
8655 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8656 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8657 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8658 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8659 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8663 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8665 SDValue Op0 = Op.getOperand(0);
8666 SDValue Op1 = Op.getOperand(1);
8667 SDValue CC = Op.getOperand(2);
8668 EVT VT = Op.getValueType();
8669 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8670 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8671 DebugLoc dl = Op.getDebugLoc();
8675 EVT EltVT = Op0.getValueType().getVectorElementType();
8676 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8682 // SSE Condition code mapping:
8691 switch (SetCCOpcode) {
8692 default: llvm_unreachable("Unexpected SETCC condition");
8694 case ISD::SETEQ: SSECC = 0; break;
8696 case ISD::SETGT: Swap = true; // Fallthrough
8698 case ISD::SETOLT: SSECC = 1; break;
8700 case ISD::SETGE: Swap = true; // Fallthrough
8702 case ISD::SETOLE: SSECC = 2; break;
8703 case ISD::SETUO: SSECC = 3; break;
8705 case ISD::SETNE: SSECC = 4; break;
8706 case ISD::SETULE: Swap = true; // Fallthrough
8707 case ISD::SETUGE: SSECC = 5; break;
8708 case ISD::SETULT: Swap = true; // Fallthrough
8709 case ISD::SETUGT: SSECC = 6; break;
8710 case ISD::SETO: SSECC = 7; break;
8712 case ISD::SETONE: SSECC = 8; break;
8715 std::swap(Op0, Op1);
8717 // In the two special cases we can't handle, emit two comparisons.
8720 unsigned CombineOpc;
8721 if (SetCCOpcode == ISD::SETUEQ) {
8722 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8724 assert(SetCCOpcode == ISD::SETONE);
8725 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8728 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8729 DAG.getConstant(CC0, MVT::i8));
8730 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8731 DAG.getConstant(CC1, MVT::i8));
8732 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8734 // Handle all other FP comparisons here.
8735 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8736 DAG.getConstant(SSECC, MVT::i8));
8739 // Break 256-bit integer vector compare into smaller ones.
8740 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8741 return Lower256IntVSETCC(Op, DAG);
8743 // We are handling one of the integer comparisons here. Since SSE only has
8744 // GT and EQ comparisons for integer, swapping operands and multiple
8745 // operations may be required for some comparisons.
8747 bool Swap = false, Invert = false, FlipSigns = false;
8749 switch (SetCCOpcode) {
8750 default: llvm_unreachable("Unexpected SETCC condition");
8751 case ISD::SETNE: Invert = true;
8752 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8753 case ISD::SETLT: Swap = true;
8754 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8755 case ISD::SETGE: Swap = true;
8756 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8757 case ISD::SETULT: Swap = true;
8758 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8759 case ISD::SETUGE: Swap = true;
8760 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8763 std::swap(Op0, Op1);
8765 // Check that the operation in question is available (most are plain SSE2,
8766 // but PCMPGTQ and PCMPEQQ have different requirements).
8767 if (VT == MVT::v2i64) {
8768 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8770 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8774 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8775 // bits of the inputs before performing those operations.
8777 EVT EltVT = VT.getVectorElementType();
8778 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8780 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8781 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8783 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8784 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8787 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8789 // If the logical-not of the result is required, perform that now.
8791 Result = DAG.getNOT(dl, Result, VT);
8796 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8797 static bool isX86LogicalCmp(SDValue Op) {
8798 unsigned Opc = Op.getNode()->getOpcode();
8799 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8800 Opc == X86ISD::SAHF)
8802 if (Op.getResNo() == 1 &&
8803 (Opc == X86ISD::ADD ||
8804 Opc == X86ISD::SUB ||
8805 Opc == X86ISD::ADC ||
8806 Opc == X86ISD::SBB ||
8807 Opc == X86ISD::SMUL ||
8808 Opc == X86ISD::UMUL ||
8809 Opc == X86ISD::INC ||
8810 Opc == X86ISD::DEC ||
8811 Opc == X86ISD::OR ||
8812 Opc == X86ISD::XOR ||
8813 Opc == X86ISD::AND))
8816 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8822 static bool isZero(SDValue V) {
8823 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8824 return C && C->isNullValue();
8827 static bool isAllOnes(SDValue V) {
8828 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8829 return C && C->isAllOnesValue();
8832 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8833 if (V.getOpcode() != ISD::TRUNCATE)
8836 SDValue VOp0 = V.getOperand(0);
8837 unsigned InBits = VOp0.getValueSizeInBits();
8838 unsigned Bits = V.getValueSizeInBits();
8839 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8842 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8843 bool addTest = true;
8844 SDValue Cond = Op.getOperand(0);
8845 SDValue Op1 = Op.getOperand(1);
8846 SDValue Op2 = Op.getOperand(2);
8847 DebugLoc DL = Op.getDebugLoc();
8850 if (Cond.getOpcode() == ISD::SETCC) {
8851 SDValue NewCond = LowerSETCC(Cond, DAG);
8852 if (NewCond.getNode())
8856 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8857 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8858 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8859 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8860 if (Cond.getOpcode() == X86ISD::SETCC &&
8861 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8862 isZero(Cond.getOperand(1).getOperand(1))) {
8863 SDValue Cmp = Cond.getOperand(1);
8865 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8867 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8868 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8869 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8871 SDValue CmpOp0 = Cmp.getOperand(0);
8872 // Apply further optimizations for special cases
8873 // (select (x != 0), -1, 0) -> neg & sbb
8874 // (select (x == 0), 0, -1) -> neg & sbb
8875 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8876 if (YC->isNullValue() &&
8877 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8878 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8879 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8880 DAG.getConstant(0, CmpOp0.getValueType()),
8882 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8883 DAG.getConstant(X86::COND_B, MVT::i8),
8884 SDValue(Neg.getNode(), 1));
8888 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8889 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8890 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8892 SDValue Res = // Res = 0 or -1.
8893 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8894 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8896 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8897 Res = DAG.getNOT(DL, Res, Res.getValueType());
8899 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8900 if (N2C == 0 || !N2C->isNullValue())
8901 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8906 // Look past (and (setcc_carry (cmp ...)), 1).
8907 if (Cond.getOpcode() == ISD::AND &&
8908 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8909 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8910 if (C && C->getAPIntValue() == 1)
8911 Cond = Cond.getOperand(0);
8914 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8915 // setting operand in place of the X86ISD::SETCC.
8916 unsigned CondOpcode = Cond.getOpcode();
8917 if (CondOpcode == X86ISD::SETCC ||
8918 CondOpcode == X86ISD::SETCC_CARRY) {
8919 CC = Cond.getOperand(0);
8921 SDValue Cmp = Cond.getOperand(1);
8922 unsigned Opc = Cmp.getOpcode();
8923 EVT VT = Op.getValueType();
8925 bool IllegalFPCMov = false;
8926 if (VT.isFloatingPoint() && !VT.isVector() &&
8927 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8928 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8930 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8931 Opc == X86ISD::BT) { // FIXME
8935 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8936 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8937 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8938 Cond.getOperand(0).getValueType() != MVT::i8)) {
8939 SDValue LHS = Cond.getOperand(0);
8940 SDValue RHS = Cond.getOperand(1);
8944 switch (CondOpcode) {
8945 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8946 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8947 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8948 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8949 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8950 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8951 default: llvm_unreachable("unexpected overflowing operator");
8953 if (CondOpcode == ISD::UMULO)
8954 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8957 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8959 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8961 if (CondOpcode == ISD::UMULO)
8962 Cond = X86Op.getValue(2);
8964 Cond = X86Op.getValue(1);
8966 CC = DAG.getConstant(X86Cond, MVT::i8);
8971 // Look pass the truncate if the high bits are known zero.
8972 if (isTruncWithZeroHighBitsInput(Cond, DAG))
8973 Cond = Cond.getOperand(0);
8975 // We know the result of AND is compared against zero. Try to match
8977 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8978 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8979 if (NewSetCC.getNode()) {
8980 CC = NewSetCC.getOperand(0);
8981 Cond = NewSetCC.getOperand(1);
8988 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8989 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8992 // a < b ? -1 : 0 -> RES = ~setcc_carry
8993 // a < b ? 0 : -1 -> RES = setcc_carry
8994 // a >= b ? -1 : 0 -> RES = setcc_carry
8995 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8996 if (Cond.getOpcode() == X86ISD::SUB) {
8997 Cond = ConvertCmpIfNecessary(Cond, DAG);
8998 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9000 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9001 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9002 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9003 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9004 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9005 return DAG.getNOT(DL, Res, Res.getValueType());
9010 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9011 // condition is true.
9012 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9013 SDValue Ops[] = { Op2, Op1, CC, Cond };
9014 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9017 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9018 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9019 // from the AND / OR.
9020 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9021 Opc = Op.getOpcode();
9022 if (Opc != ISD::OR && Opc != ISD::AND)
9024 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9025 Op.getOperand(0).hasOneUse() &&
9026 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9027 Op.getOperand(1).hasOneUse());
9030 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9031 // 1 and that the SETCC node has a single use.
9032 static bool isXor1OfSetCC(SDValue Op) {
9033 if (Op.getOpcode() != ISD::XOR)
9035 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9036 if (N1C && N1C->getAPIntValue() == 1) {
9037 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9038 Op.getOperand(0).hasOneUse();
9043 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9044 bool addTest = true;
9045 SDValue Chain = Op.getOperand(0);
9046 SDValue Cond = Op.getOperand(1);
9047 SDValue Dest = Op.getOperand(2);
9048 DebugLoc dl = Op.getDebugLoc();
9050 bool Inverted = false;
9052 if (Cond.getOpcode() == ISD::SETCC) {
9053 // Check for setcc([su]{add,sub,mul}o == 0).
9054 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9055 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9056 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9057 Cond.getOperand(0).getResNo() == 1 &&
9058 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9059 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9060 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9061 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9062 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9063 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9065 Cond = Cond.getOperand(0);
9067 SDValue NewCond = LowerSETCC(Cond, DAG);
9068 if (NewCond.getNode())
9073 // FIXME: LowerXALUO doesn't handle these!!
9074 else if (Cond.getOpcode() == X86ISD::ADD ||
9075 Cond.getOpcode() == X86ISD::SUB ||
9076 Cond.getOpcode() == X86ISD::SMUL ||
9077 Cond.getOpcode() == X86ISD::UMUL)
9078 Cond = LowerXALUO(Cond, DAG);
9081 // Look pass (and (setcc_carry (cmp ...)), 1).
9082 if (Cond.getOpcode() == ISD::AND &&
9083 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9084 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9085 if (C && C->getAPIntValue() == 1)
9086 Cond = Cond.getOperand(0);
9089 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9090 // setting operand in place of the X86ISD::SETCC.
9091 unsigned CondOpcode = Cond.getOpcode();
9092 if (CondOpcode == X86ISD::SETCC ||
9093 CondOpcode == X86ISD::SETCC_CARRY) {
9094 CC = Cond.getOperand(0);
9096 SDValue Cmp = Cond.getOperand(1);
9097 unsigned Opc = Cmp.getOpcode();
9098 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9099 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9103 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9107 // These can only come from an arithmetic instruction with overflow,
9108 // e.g. SADDO, UADDO.
9109 Cond = Cond.getNode()->getOperand(1);
9115 CondOpcode = Cond.getOpcode();
9116 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9117 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9118 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9119 Cond.getOperand(0).getValueType() != MVT::i8)) {
9120 SDValue LHS = Cond.getOperand(0);
9121 SDValue RHS = Cond.getOperand(1);
9125 switch (CondOpcode) {
9126 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9127 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9128 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9129 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9130 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9131 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9132 default: llvm_unreachable("unexpected overflowing operator");
9135 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9136 if (CondOpcode == ISD::UMULO)
9137 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9140 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9142 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9144 if (CondOpcode == ISD::UMULO)
9145 Cond = X86Op.getValue(2);
9147 Cond = X86Op.getValue(1);
9149 CC = DAG.getConstant(X86Cond, MVT::i8);
9153 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9154 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9155 if (CondOpc == ISD::OR) {
9156 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9157 // two branches instead of an explicit OR instruction with a
9159 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9160 isX86LogicalCmp(Cmp)) {
9161 CC = Cond.getOperand(0).getOperand(0);
9162 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9163 Chain, Dest, CC, Cmp);
9164 CC = Cond.getOperand(1).getOperand(0);
9168 } else { // ISD::AND
9169 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9170 // two branches instead of an explicit AND instruction with a
9171 // separate test. However, we only do this if this block doesn't
9172 // have a fall-through edge, because this requires an explicit
9173 // jmp when the condition is false.
9174 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9175 isX86LogicalCmp(Cmp) &&
9176 Op.getNode()->hasOneUse()) {
9177 X86::CondCode CCode =
9178 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9179 CCode = X86::GetOppositeBranchCondition(CCode);
9180 CC = DAG.getConstant(CCode, MVT::i8);
9181 SDNode *User = *Op.getNode()->use_begin();
9182 // Look for an unconditional branch following this conditional branch.
9183 // We need this because we need to reverse the successors in order
9184 // to implement FCMP_OEQ.
9185 if (User->getOpcode() == ISD::BR) {
9186 SDValue FalseBB = User->getOperand(1);
9188 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9189 assert(NewBR == User);
9193 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9194 Chain, Dest, CC, Cmp);
9195 X86::CondCode CCode =
9196 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9197 CCode = X86::GetOppositeBranchCondition(CCode);
9198 CC = DAG.getConstant(CCode, MVT::i8);
9204 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9205 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9206 // It should be transformed during dag combiner except when the condition
9207 // is set by a arithmetics with overflow node.
9208 X86::CondCode CCode =
9209 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9210 CCode = X86::GetOppositeBranchCondition(CCode);
9211 CC = DAG.getConstant(CCode, MVT::i8);
9212 Cond = Cond.getOperand(0).getOperand(1);
9214 } else if (Cond.getOpcode() == ISD::SETCC &&
9215 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9216 // For FCMP_OEQ, we can emit
9217 // two branches instead of an explicit AND instruction with a
9218 // separate test. However, we only do this if this block doesn't
9219 // have a fall-through edge, because this requires an explicit
9220 // jmp when the condition is false.
9221 if (Op.getNode()->hasOneUse()) {
9222 SDNode *User = *Op.getNode()->use_begin();
9223 // Look for an unconditional branch following this conditional branch.
9224 // We need this because we need to reverse the successors in order
9225 // to implement FCMP_OEQ.
9226 if (User->getOpcode() == ISD::BR) {
9227 SDValue FalseBB = User->getOperand(1);
9229 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9230 assert(NewBR == User);
9234 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9235 Cond.getOperand(0), Cond.getOperand(1));
9236 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9237 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9238 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9239 Chain, Dest, CC, Cmp);
9240 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9245 } else if (Cond.getOpcode() == ISD::SETCC &&
9246 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9247 // For FCMP_UNE, we can emit
9248 // two branches instead of an explicit AND instruction with a
9249 // separate test. However, we only do this if this block doesn't
9250 // have a fall-through edge, because this requires an explicit
9251 // jmp when the condition is false.
9252 if (Op.getNode()->hasOneUse()) {
9253 SDNode *User = *Op.getNode()->use_begin();
9254 // Look for an unconditional branch following this conditional branch.
9255 // We need this because we need to reverse the successors in order
9256 // to implement FCMP_UNE.
9257 if (User->getOpcode() == ISD::BR) {
9258 SDValue FalseBB = User->getOperand(1);
9260 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9261 assert(NewBR == User);
9264 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9265 Cond.getOperand(0), Cond.getOperand(1));
9266 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9267 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9268 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9269 Chain, Dest, CC, Cmp);
9270 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9280 // Look pass the truncate if the high bits are known zero.
9281 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9282 Cond = Cond.getOperand(0);
9284 // We know the result of AND is compared against zero. Try to match
9286 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9287 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9288 if (NewSetCC.getNode()) {
9289 CC = NewSetCC.getOperand(0);
9290 Cond = NewSetCC.getOperand(1);
9297 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9298 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9300 Cond = ConvertCmpIfNecessary(Cond, DAG);
9301 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9302 Chain, Dest, CC, Cond);
9306 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9307 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9308 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9309 // that the guard pages used by the OS virtual memory manager are allocated in
9310 // correct sequence.
9312 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9313 SelectionDAG &DAG) const {
9314 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9315 getTargetMachine().Options.EnableSegmentedStacks) &&
9316 "This should be used only on Windows targets or when segmented stacks "
9318 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9319 DebugLoc dl = Op.getDebugLoc();
9322 SDValue Chain = Op.getOperand(0);
9323 SDValue Size = Op.getOperand(1);
9324 // FIXME: Ensure alignment here
9326 bool Is64Bit = Subtarget->is64Bit();
9327 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9329 if (getTargetMachine().Options.EnableSegmentedStacks) {
9330 MachineFunction &MF = DAG.getMachineFunction();
9331 MachineRegisterInfo &MRI = MF.getRegInfo();
9334 // The 64 bit implementation of segmented stacks needs to clobber both r10
9335 // r11. This makes it impossible to use it along with nested parameters.
9336 const Function *F = MF.getFunction();
9338 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9340 if (I->hasNestAttr())
9341 report_fatal_error("Cannot use segmented stacks with functions that "
9342 "have nested arguments.");
9345 const TargetRegisterClass *AddrRegClass =
9346 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9347 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9348 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9349 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9350 DAG.getRegister(Vreg, SPTy));
9351 SDValue Ops1[2] = { Value, Chain };
9352 return DAG.getMergeValues(Ops1, 2, dl);
9355 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9357 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9358 Flag = Chain.getValue(1);
9359 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9361 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9362 Flag = Chain.getValue(1);
9364 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9366 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9367 return DAG.getMergeValues(Ops1, 2, dl);
9371 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9372 MachineFunction &MF = DAG.getMachineFunction();
9373 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9375 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9376 DebugLoc DL = Op.getDebugLoc();
9378 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9379 // vastart just stores the address of the VarArgsFrameIndex slot into the
9380 // memory location argument.
9381 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9383 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9384 MachinePointerInfo(SV), false, false, 0);
9388 // gp_offset (0 - 6 * 8)
9389 // fp_offset (48 - 48 + 8 * 16)
9390 // overflow_arg_area (point to parameters coming in memory).
9392 SmallVector<SDValue, 8> MemOps;
9393 SDValue FIN = Op.getOperand(1);
9395 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9396 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9398 FIN, MachinePointerInfo(SV), false, false, 0);
9399 MemOps.push_back(Store);
9402 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9403 FIN, DAG.getIntPtrConstant(4));
9404 Store = DAG.getStore(Op.getOperand(0), DL,
9405 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9407 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9408 MemOps.push_back(Store);
9410 // Store ptr to overflow_arg_area
9411 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9412 FIN, DAG.getIntPtrConstant(4));
9413 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9415 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9416 MachinePointerInfo(SV, 8),
9418 MemOps.push_back(Store);
9420 // Store ptr to reg_save_area.
9421 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9422 FIN, DAG.getIntPtrConstant(8));
9423 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9425 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9426 MachinePointerInfo(SV, 16), false, false, 0);
9427 MemOps.push_back(Store);
9428 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9429 &MemOps[0], MemOps.size());
9432 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9433 assert(Subtarget->is64Bit() &&
9434 "LowerVAARG only handles 64-bit va_arg!");
9435 assert((Subtarget->isTargetLinux() ||
9436 Subtarget->isTargetDarwin()) &&
9437 "Unhandled target in LowerVAARG");
9438 assert(Op.getNode()->getNumOperands() == 4);
9439 SDValue Chain = Op.getOperand(0);
9440 SDValue SrcPtr = Op.getOperand(1);
9441 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9442 unsigned Align = Op.getConstantOperandVal(3);
9443 DebugLoc dl = Op.getDebugLoc();
9445 EVT ArgVT = Op.getNode()->getValueType(0);
9446 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9447 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9450 // Decide which area this value should be read from.
9451 // TODO: Implement the AMD64 ABI in its entirety. This simple
9452 // selection mechanism works only for the basic types.
9453 if (ArgVT == MVT::f80) {
9454 llvm_unreachable("va_arg for f80 not yet implemented");
9455 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9456 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9457 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9458 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9460 llvm_unreachable("Unhandled argument type in LowerVAARG");
9464 // Sanity Check: Make sure using fp_offset makes sense.
9465 assert(!getTargetMachine().Options.UseSoftFloat &&
9466 !(DAG.getMachineFunction()
9467 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9468 Subtarget->hasSSE1());
9471 // Insert VAARG_64 node into the DAG
9472 // VAARG_64 returns two values: Variable Argument Address, Chain
9473 SmallVector<SDValue, 11> InstOps;
9474 InstOps.push_back(Chain);
9475 InstOps.push_back(SrcPtr);
9476 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9477 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9478 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9479 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9480 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9481 VTs, &InstOps[0], InstOps.size(),
9483 MachinePointerInfo(SV),
9488 Chain = VAARG.getValue(1);
9490 // Load the next argument and return it
9491 return DAG.getLoad(ArgVT, dl,
9494 MachinePointerInfo(),
9495 false, false, false, 0);
9498 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9499 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9500 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9501 SDValue Chain = Op.getOperand(0);
9502 SDValue DstPtr = Op.getOperand(1);
9503 SDValue SrcPtr = Op.getOperand(2);
9504 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9505 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9506 DebugLoc DL = Op.getDebugLoc();
9508 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9509 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9511 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9514 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9515 // may or may not be a constant. Takes immediate version of shift as input.
9516 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9517 SDValue SrcOp, SDValue ShAmt,
9518 SelectionDAG &DAG) {
9519 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9521 if (isa<ConstantSDNode>(ShAmt)) {
9522 // Constant may be a TargetConstant. Use a regular constant.
9523 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9525 default: llvm_unreachable("Unknown target vector shift node");
9529 return DAG.getNode(Opc, dl, VT, SrcOp,
9530 DAG.getConstant(ShiftAmt, MVT::i32));
9534 // Change opcode to non-immediate version
9536 default: llvm_unreachable("Unknown target vector shift node");
9537 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9538 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9539 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9542 // Need to build a vector containing shift amount
9543 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9546 ShOps[1] = DAG.getConstant(0, MVT::i32);
9547 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9548 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9550 // The return type has to be a 128-bit type with the same element
9551 // type as the input type.
9552 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9553 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9555 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9556 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9560 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9561 DebugLoc dl = Op.getDebugLoc();
9562 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9564 default: return SDValue(); // Don't custom lower most intrinsics.
9565 // Comparison intrinsics.
9566 case Intrinsic::x86_sse_comieq_ss:
9567 case Intrinsic::x86_sse_comilt_ss:
9568 case Intrinsic::x86_sse_comile_ss:
9569 case Intrinsic::x86_sse_comigt_ss:
9570 case Intrinsic::x86_sse_comige_ss:
9571 case Intrinsic::x86_sse_comineq_ss:
9572 case Intrinsic::x86_sse_ucomieq_ss:
9573 case Intrinsic::x86_sse_ucomilt_ss:
9574 case Intrinsic::x86_sse_ucomile_ss:
9575 case Intrinsic::x86_sse_ucomigt_ss:
9576 case Intrinsic::x86_sse_ucomige_ss:
9577 case Intrinsic::x86_sse_ucomineq_ss:
9578 case Intrinsic::x86_sse2_comieq_sd:
9579 case Intrinsic::x86_sse2_comilt_sd:
9580 case Intrinsic::x86_sse2_comile_sd:
9581 case Intrinsic::x86_sse2_comigt_sd:
9582 case Intrinsic::x86_sse2_comige_sd:
9583 case Intrinsic::x86_sse2_comineq_sd:
9584 case Intrinsic::x86_sse2_ucomieq_sd:
9585 case Intrinsic::x86_sse2_ucomilt_sd:
9586 case Intrinsic::x86_sse2_ucomile_sd:
9587 case Intrinsic::x86_sse2_ucomigt_sd:
9588 case Intrinsic::x86_sse2_ucomige_sd:
9589 case Intrinsic::x86_sse2_ucomineq_sd: {
9593 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9594 case Intrinsic::x86_sse_comieq_ss:
9595 case Intrinsic::x86_sse2_comieq_sd:
9599 case Intrinsic::x86_sse_comilt_ss:
9600 case Intrinsic::x86_sse2_comilt_sd:
9604 case Intrinsic::x86_sse_comile_ss:
9605 case Intrinsic::x86_sse2_comile_sd:
9609 case Intrinsic::x86_sse_comigt_ss:
9610 case Intrinsic::x86_sse2_comigt_sd:
9614 case Intrinsic::x86_sse_comige_ss:
9615 case Intrinsic::x86_sse2_comige_sd:
9619 case Intrinsic::x86_sse_comineq_ss:
9620 case Intrinsic::x86_sse2_comineq_sd:
9624 case Intrinsic::x86_sse_ucomieq_ss:
9625 case Intrinsic::x86_sse2_ucomieq_sd:
9626 Opc = X86ISD::UCOMI;
9629 case Intrinsic::x86_sse_ucomilt_ss:
9630 case Intrinsic::x86_sse2_ucomilt_sd:
9631 Opc = X86ISD::UCOMI;
9634 case Intrinsic::x86_sse_ucomile_ss:
9635 case Intrinsic::x86_sse2_ucomile_sd:
9636 Opc = X86ISD::UCOMI;
9639 case Intrinsic::x86_sse_ucomigt_ss:
9640 case Intrinsic::x86_sse2_ucomigt_sd:
9641 Opc = X86ISD::UCOMI;
9644 case Intrinsic::x86_sse_ucomige_ss:
9645 case Intrinsic::x86_sse2_ucomige_sd:
9646 Opc = X86ISD::UCOMI;
9649 case Intrinsic::x86_sse_ucomineq_ss:
9650 case Intrinsic::x86_sse2_ucomineq_sd:
9651 Opc = X86ISD::UCOMI;
9656 SDValue LHS = Op.getOperand(1);
9657 SDValue RHS = Op.getOperand(2);
9658 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9659 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9660 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9661 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9662 DAG.getConstant(X86CC, MVT::i8), Cond);
9663 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9666 // Arithmetic intrinsics.
9667 case Intrinsic::x86_sse2_pmulu_dq:
9668 case Intrinsic::x86_avx2_pmulu_dq:
9669 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9670 Op.getOperand(1), Op.getOperand(2));
9672 // SSE3/AVX horizontal add/sub intrinsics
9673 case Intrinsic::x86_sse3_hadd_ps:
9674 case Intrinsic::x86_sse3_hadd_pd:
9675 case Intrinsic::x86_avx_hadd_ps_256:
9676 case Intrinsic::x86_avx_hadd_pd_256:
9677 case Intrinsic::x86_sse3_hsub_ps:
9678 case Intrinsic::x86_sse3_hsub_pd:
9679 case Intrinsic::x86_avx_hsub_ps_256:
9680 case Intrinsic::x86_avx_hsub_pd_256:
9681 case Intrinsic::x86_ssse3_phadd_w_128:
9682 case Intrinsic::x86_ssse3_phadd_d_128:
9683 case Intrinsic::x86_avx2_phadd_w:
9684 case Intrinsic::x86_avx2_phadd_d:
9685 case Intrinsic::x86_ssse3_phsub_w_128:
9686 case Intrinsic::x86_ssse3_phsub_d_128:
9687 case Intrinsic::x86_avx2_phsub_w:
9688 case Intrinsic::x86_avx2_phsub_d: {
9691 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9692 case Intrinsic::x86_sse3_hadd_ps:
9693 case Intrinsic::x86_sse3_hadd_pd:
9694 case Intrinsic::x86_avx_hadd_ps_256:
9695 case Intrinsic::x86_avx_hadd_pd_256:
9696 Opcode = X86ISD::FHADD;
9698 case Intrinsic::x86_sse3_hsub_ps:
9699 case Intrinsic::x86_sse3_hsub_pd:
9700 case Intrinsic::x86_avx_hsub_ps_256:
9701 case Intrinsic::x86_avx_hsub_pd_256:
9702 Opcode = X86ISD::FHSUB;
9704 case Intrinsic::x86_ssse3_phadd_w_128:
9705 case Intrinsic::x86_ssse3_phadd_d_128:
9706 case Intrinsic::x86_avx2_phadd_w:
9707 case Intrinsic::x86_avx2_phadd_d:
9708 Opcode = X86ISD::HADD;
9710 case Intrinsic::x86_ssse3_phsub_w_128:
9711 case Intrinsic::x86_ssse3_phsub_d_128:
9712 case Intrinsic::x86_avx2_phsub_w:
9713 case Intrinsic::x86_avx2_phsub_d:
9714 Opcode = X86ISD::HSUB;
9717 return DAG.getNode(Opcode, dl, Op.getValueType(),
9718 Op.getOperand(1), Op.getOperand(2));
9721 // AVX2 variable shift intrinsics
9722 case Intrinsic::x86_avx2_psllv_d:
9723 case Intrinsic::x86_avx2_psllv_q:
9724 case Intrinsic::x86_avx2_psllv_d_256:
9725 case Intrinsic::x86_avx2_psllv_q_256:
9726 case Intrinsic::x86_avx2_psrlv_d:
9727 case Intrinsic::x86_avx2_psrlv_q:
9728 case Intrinsic::x86_avx2_psrlv_d_256:
9729 case Intrinsic::x86_avx2_psrlv_q_256:
9730 case Intrinsic::x86_avx2_psrav_d:
9731 case Intrinsic::x86_avx2_psrav_d_256: {
9734 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9735 case Intrinsic::x86_avx2_psllv_d:
9736 case Intrinsic::x86_avx2_psllv_q:
9737 case Intrinsic::x86_avx2_psllv_d_256:
9738 case Intrinsic::x86_avx2_psllv_q_256:
9741 case Intrinsic::x86_avx2_psrlv_d:
9742 case Intrinsic::x86_avx2_psrlv_q:
9743 case Intrinsic::x86_avx2_psrlv_d_256:
9744 case Intrinsic::x86_avx2_psrlv_q_256:
9747 case Intrinsic::x86_avx2_psrav_d:
9748 case Intrinsic::x86_avx2_psrav_d_256:
9752 return DAG.getNode(Opcode, dl, Op.getValueType(),
9753 Op.getOperand(1), Op.getOperand(2));
9756 case Intrinsic::x86_ssse3_pshuf_b_128:
9757 case Intrinsic::x86_avx2_pshuf_b:
9758 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9759 Op.getOperand(1), Op.getOperand(2));
9761 case Intrinsic::x86_ssse3_psign_b_128:
9762 case Intrinsic::x86_ssse3_psign_w_128:
9763 case Intrinsic::x86_ssse3_psign_d_128:
9764 case Intrinsic::x86_avx2_psign_b:
9765 case Intrinsic::x86_avx2_psign_w:
9766 case Intrinsic::x86_avx2_psign_d:
9767 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9768 Op.getOperand(1), Op.getOperand(2));
9770 case Intrinsic::x86_sse41_insertps:
9771 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9772 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9774 case Intrinsic::x86_avx_vperm2f128_ps_256:
9775 case Intrinsic::x86_avx_vperm2f128_pd_256:
9776 case Intrinsic::x86_avx_vperm2f128_si_256:
9777 case Intrinsic::x86_avx2_vperm2i128:
9778 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9779 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9781 case Intrinsic::x86_avx2_permd:
9782 case Intrinsic::x86_avx2_permps:
9783 // Operands intentionally swapped. Mask is last operand to intrinsic,
9784 // but second operand for node/intruction.
9785 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9786 Op.getOperand(2), Op.getOperand(1));
9788 // ptest and testp intrinsics. The intrinsic these come from are designed to
9789 // return an integer value, not just an instruction so lower it to the ptest
9790 // or testp pattern and a setcc for the result.
9791 case Intrinsic::x86_sse41_ptestz:
9792 case Intrinsic::x86_sse41_ptestc:
9793 case Intrinsic::x86_sse41_ptestnzc:
9794 case Intrinsic::x86_avx_ptestz_256:
9795 case Intrinsic::x86_avx_ptestc_256:
9796 case Intrinsic::x86_avx_ptestnzc_256:
9797 case Intrinsic::x86_avx_vtestz_ps:
9798 case Intrinsic::x86_avx_vtestc_ps:
9799 case Intrinsic::x86_avx_vtestnzc_ps:
9800 case Intrinsic::x86_avx_vtestz_pd:
9801 case Intrinsic::x86_avx_vtestc_pd:
9802 case Intrinsic::x86_avx_vtestnzc_pd:
9803 case Intrinsic::x86_avx_vtestz_ps_256:
9804 case Intrinsic::x86_avx_vtestc_ps_256:
9805 case Intrinsic::x86_avx_vtestnzc_ps_256:
9806 case Intrinsic::x86_avx_vtestz_pd_256:
9807 case Intrinsic::x86_avx_vtestc_pd_256:
9808 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9809 bool IsTestPacked = false;
9812 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9813 case Intrinsic::x86_avx_vtestz_ps:
9814 case Intrinsic::x86_avx_vtestz_pd:
9815 case Intrinsic::x86_avx_vtestz_ps_256:
9816 case Intrinsic::x86_avx_vtestz_pd_256:
9817 IsTestPacked = true; // Fallthrough
9818 case Intrinsic::x86_sse41_ptestz:
9819 case Intrinsic::x86_avx_ptestz_256:
9821 X86CC = X86::COND_E;
9823 case Intrinsic::x86_avx_vtestc_ps:
9824 case Intrinsic::x86_avx_vtestc_pd:
9825 case Intrinsic::x86_avx_vtestc_ps_256:
9826 case Intrinsic::x86_avx_vtestc_pd_256:
9827 IsTestPacked = true; // Fallthrough
9828 case Intrinsic::x86_sse41_ptestc:
9829 case Intrinsic::x86_avx_ptestc_256:
9831 X86CC = X86::COND_B;
9833 case Intrinsic::x86_avx_vtestnzc_ps:
9834 case Intrinsic::x86_avx_vtestnzc_pd:
9835 case Intrinsic::x86_avx_vtestnzc_ps_256:
9836 case Intrinsic::x86_avx_vtestnzc_pd_256:
9837 IsTestPacked = true; // Fallthrough
9838 case Intrinsic::x86_sse41_ptestnzc:
9839 case Intrinsic::x86_avx_ptestnzc_256:
9841 X86CC = X86::COND_A;
9845 SDValue LHS = Op.getOperand(1);
9846 SDValue RHS = Op.getOperand(2);
9847 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9848 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9849 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9850 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9851 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9854 // SSE/AVX shift intrinsics
9855 case Intrinsic::x86_sse2_psll_w:
9856 case Intrinsic::x86_sse2_psll_d:
9857 case Intrinsic::x86_sse2_psll_q:
9858 case Intrinsic::x86_avx2_psll_w:
9859 case Intrinsic::x86_avx2_psll_d:
9860 case Intrinsic::x86_avx2_psll_q:
9861 case Intrinsic::x86_sse2_psrl_w:
9862 case Intrinsic::x86_sse2_psrl_d:
9863 case Intrinsic::x86_sse2_psrl_q:
9864 case Intrinsic::x86_avx2_psrl_w:
9865 case Intrinsic::x86_avx2_psrl_d:
9866 case Intrinsic::x86_avx2_psrl_q:
9867 case Intrinsic::x86_sse2_psra_w:
9868 case Intrinsic::x86_sse2_psra_d:
9869 case Intrinsic::x86_avx2_psra_w:
9870 case Intrinsic::x86_avx2_psra_d: {
9873 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9874 case Intrinsic::x86_sse2_psll_w:
9875 case Intrinsic::x86_sse2_psll_d:
9876 case Intrinsic::x86_sse2_psll_q:
9877 case Intrinsic::x86_avx2_psll_w:
9878 case Intrinsic::x86_avx2_psll_d:
9879 case Intrinsic::x86_avx2_psll_q:
9880 Opcode = X86ISD::VSHL;
9882 case Intrinsic::x86_sse2_psrl_w:
9883 case Intrinsic::x86_sse2_psrl_d:
9884 case Intrinsic::x86_sse2_psrl_q:
9885 case Intrinsic::x86_avx2_psrl_w:
9886 case Intrinsic::x86_avx2_psrl_d:
9887 case Intrinsic::x86_avx2_psrl_q:
9888 Opcode = X86ISD::VSRL;
9890 case Intrinsic::x86_sse2_psra_w:
9891 case Intrinsic::x86_sse2_psra_d:
9892 case Intrinsic::x86_avx2_psra_w:
9893 case Intrinsic::x86_avx2_psra_d:
9894 Opcode = X86ISD::VSRA;
9897 return DAG.getNode(Opcode, dl, Op.getValueType(),
9898 Op.getOperand(1), Op.getOperand(2));
9901 // SSE/AVX immediate shift intrinsics
9902 case Intrinsic::x86_sse2_pslli_w:
9903 case Intrinsic::x86_sse2_pslli_d:
9904 case Intrinsic::x86_sse2_pslli_q:
9905 case Intrinsic::x86_avx2_pslli_w:
9906 case Intrinsic::x86_avx2_pslli_d:
9907 case Intrinsic::x86_avx2_pslli_q:
9908 case Intrinsic::x86_sse2_psrli_w:
9909 case Intrinsic::x86_sse2_psrli_d:
9910 case Intrinsic::x86_sse2_psrli_q:
9911 case Intrinsic::x86_avx2_psrli_w:
9912 case Intrinsic::x86_avx2_psrli_d:
9913 case Intrinsic::x86_avx2_psrli_q:
9914 case Intrinsic::x86_sse2_psrai_w:
9915 case Intrinsic::x86_sse2_psrai_d:
9916 case Intrinsic::x86_avx2_psrai_w:
9917 case Intrinsic::x86_avx2_psrai_d: {
9920 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9921 case Intrinsic::x86_sse2_pslli_w:
9922 case Intrinsic::x86_sse2_pslli_d:
9923 case Intrinsic::x86_sse2_pslli_q:
9924 case Intrinsic::x86_avx2_pslli_w:
9925 case Intrinsic::x86_avx2_pslli_d:
9926 case Intrinsic::x86_avx2_pslli_q:
9927 Opcode = X86ISD::VSHLI;
9929 case Intrinsic::x86_sse2_psrli_w:
9930 case Intrinsic::x86_sse2_psrli_d:
9931 case Intrinsic::x86_sse2_psrli_q:
9932 case Intrinsic::x86_avx2_psrli_w:
9933 case Intrinsic::x86_avx2_psrli_d:
9934 case Intrinsic::x86_avx2_psrli_q:
9935 Opcode = X86ISD::VSRLI;
9937 case Intrinsic::x86_sse2_psrai_w:
9938 case Intrinsic::x86_sse2_psrai_d:
9939 case Intrinsic::x86_avx2_psrai_w:
9940 case Intrinsic::x86_avx2_psrai_d:
9941 Opcode = X86ISD::VSRAI;
9944 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
9945 Op.getOperand(1), Op.getOperand(2), DAG);
9948 case Intrinsic::x86_sse42_pcmpistria128:
9949 case Intrinsic::x86_sse42_pcmpestria128:
9950 case Intrinsic::x86_sse42_pcmpistric128:
9951 case Intrinsic::x86_sse42_pcmpestric128:
9952 case Intrinsic::x86_sse42_pcmpistrio128:
9953 case Intrinsic::x86_sse42_pcmpestrio128:
9954 case Intrinsic::x86_sse42_pcmpistris128:
9955 case Intrinsic::x86_sse42_pcmpestris128:
9956 case Intrinsic::x86_sse42_pcmpistriz128:
9957 case Intrinsic::x86_sse42_pcmpestriz128: {
9961 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9962 case Intrinsic::x86_sse42_pcmpistria128:
9963 Opcode = X86ISD::PCMPISTRI;
9964 X86CC = X86::COND_A;
9966 case Intrinsic::x86_sse42_pcmpestria128:
9967 Opcode = X86ISD::PCMPESTRI;
9968 X86CC = X86::COND_A;
9970 case Intrinsic::x86_sse42_pcmpistric128:
9971 Opcode = X86ISD::PCMPISTRI;
9972 X86CC = X86::COND_B;
9974 case Intrinsic::x86_sse42_pcmpestric128:
9975 Opcode = X86ISD::PCMPESTRI;
9976 X86CC = X86::COND_B;
9978 case Intrinsic::x86_sse42_pcmpistrio128:
9979 Opcode = X86ISD::PCMPISTRI;
9980 X86CC = X86::COND_O;
9982 case Intrinsic::x86_sse42_pcmpestrio128:
9983 Opcode = X86ISD::PCMPESTRI;
9984 X86CC = X86::COND_O;
9986 case Intrinsic::x86_sse42_pcmpistris128:
9987 Opcode = X86ISD::PCMPISTRI;
9988 X86CC = X86::COND_S;
9990 case Intrinsic::x86_sse42_pcmpestris128:
9991 Opcode = X86ISD::PCMPESTRI;
9992 X86CC = X86::COND_S;
9994 case Intrinsic::x86_sse42_pcmpistriz128:
9995 Opcode = X86ISD::PCMPISTRI;
9996 X86CC = X86::COND_E;
9998 case Intrinsic::x86_sse42_pcmpestriz128:
9999 Opcode = X86ISD::PCMPESTRI;
10000 X86CC = X86::COND_E;
10003 SmallVector<SDValue, 5> NewOps;
10004 NewOps.append(Op->op_begin()+1, Op->op_end());
10005 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10006 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10007 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10008 DAG.getConstant(X86CC, MVT::i8),
10009 SDValue(PCMP.getNode(), 1));
10010 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10013 case Intrinsic::x86_sse42_pcmpistri128:
10014 case Intrinsic::x86_sse42_pcmpestri128: {
10016 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10017 Opcode = X86ISD::PCMPISTRI;
10019 Opcode = X86ISD::PCMPESTRI;
10021 SmallVector<SDValue, 5> NewOps;
10022 NewOps.append(Op->op_begin()+1, Op->op_end());
10023 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10024 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10026 case Intrinsic::x86_fma_vfmadd_ps:
10027 case Intrinsic::x86_fma_vfmadd_pd:
10028 case Intrinsic::x86_fma_vfmsub_ps:
10029 case Intrinsic::x86_fma_vfmsub_pd:
10030 case Intrinsic::x86_fma_vfnmadd_ps:
10031 case Intrinsic::x86_fma_vfnmadd_pd:
10032 case Intrinsic::x86_fma_vfnmsub_ps:
10033 case Intrinsic::x86_fma_vfnmsub_pd:
10034 case Intrinsic::x86_fma_vfmaddsub_ps:
10035 case Intrinsic::x86_fma_vfmaddsub_pd:
10036 case Intrinsic::x86_fma_vfmsubadd_ps:
10037 case Intrinsic::x86_fma_vfmsubadd_pd:
10038 case Intrinsic::x86_fma_vfmadd_ps_256:
10039 case Intrinsic::x86_fma_vfmadd_pd_256:
10040 case Intrinsic::x86_fma_vfmsub_ps_256:
10041 case Intrinsic::x86_fma_vfmsub_pd_256:
10042 case Intrinsic::x86_fma_vfnmadd_ps_256:
10043 case Intrinsic::x86_fma_vfnmadd_pd_256:
10044 case Intrinsic::x86_fma_vfnmsub_ps_256:
10045 case Intrinsic::x86_fma_vfnmsub_pd_256:
10046 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10047 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10048 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10049 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10052 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10053 case Intrinsic::x86_fma_vfmadd_ps:
10054 case Intrinsic::x86_fma_vfmadd_pd:
10055 case Intrinsic::x86_fma_vfmadd_ps_256:
10056 case Intrinsic::x86_fma_vfmadd_pd_256:
10057 Opc = X86ISD::FMADD;
10059 case Intrinsic::x86_fma_vfmsub_ps:
10060 case Intrinsic::x86_fma_vfmsub_pd:
10061 case Intrinsic::x86_fma_vfmsub_ps_256:
10062 case Intrinsic::x86_fma_vfmsub_pd_256:
10063 Opc = X86ISD::FMSUB;
10065 case Intrinsic::x86_fma_vfnmadd_ps:
10066 case Intrinsic::x86_fma_vfnmadd_pd:
10067 case Intrinsic::x86_fma_vfnmadd_ps_256:
10068 case Intrinsic::x86_fma_vfnmadd_pd_256:
10069 Opc = X86ISD::FNMADD;
10071 case Intrinsic::x86_fma_vfnmsub_ps:
10072 case Intrinsic::x86_fma_vfnmsub_pd:
10073 case Intrinsic::x86_fma_vfnmsub_ps_256:
10074 case Intrinsic::x86_fma_vfnmsub_pd_256:
10075 Opc = X86ISD::FNMSUB;
10077 case Intrinsic::x86_fma_vfmaddsub_ps:
10078 case Intrinsic::x86_fma_vfmaddsub_pd:
10079 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10080 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10081 Opc = X86ISD::FMADDSUB;
10083 case Intrinsic::x86_fma_vfmsubadd_ps:
10084 case Intrinsic::x86_fma_vfmsubadd_pd:
10085 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10086 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10087 Opc = X86ISD::FMSUBADD;
10091 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10092 Op.getOperand(2), Op.getOperand(3));
10098 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10099 DebugLoc dl = Op.getDebugLoc();
10100 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10102 default: return SDValue(); // Don't custom lower most intrinsics.
10104 // RDRAND intrinsics.
10105 case Intrinsic::x86_rdrand_16:
10106 case Intrinsic::x86_rdrand_32:
10107 case Intrinsic::x86_rdrand_64: {
10108 // Emit the node with the right value type.
10109 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10110 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10112 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10113 // return the value from Rand, which is always 0, casted to i32.
10114 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10115 DAG.getConstant(1, Op->getValueType(1)),
10116 DAG.getConstant(X86::COND_B, MVT::i32),
10117 SDValue(Result.getNode(), 1) };
10118 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10119 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10122 // Return { result, isValid, chain }.
10123 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10124 SDValue(Result.getNode(), 2));
10129 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10130 SelectionDAG &DAG) const {
10131 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10132 MFI->setReturnAddressIsTaken(true);
10134 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10135 DebugLoc dl = Op.getDebugLoc();
10138 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10140 DAG.getConstant(TD->getPointerSize(),
10141 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10142 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10143 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10144 FrameAddr, Offset),
10145 MachinePointerInfo(), false, false, false, 0);
10148 // Just load the return address.
10149 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10150 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10151 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10154 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10155 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10156 MFI->setFrameAddressIsTaken(true);
10158 EVT VT = Op.getValueType();
10159 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10160 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10161 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10162 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10164 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10165 MachinePointerInfo(),
10166 false, false, false, 0);
10170 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10171 SelectionDAG &DAG) const {
10172 return DAG.getIntPtrConstant(2*TD->getPointerSize());
10175 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10176 SDValue Chain = Op.getOperand(0);
10177 SDValue Offset = Op.getOperand(1);
10178 SDValue Handler = Op.getOperand(2);
10179 DebugLoc dl = Op.getDebugLoc();
10181 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10182 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10184 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10186 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10187 DAG.getIntPtrConstant(TD->getPointerSize()));
10188 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10189 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10191 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10193 return DAG.getNode(X86ISD::EH_RETURN, dl,
10195 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10198 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10199 SelectionDAG &DAG) const {
10200 return Op.getOperand(0);
10203 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10204 SelectionDAG &DAG) const {
10205 SDValue Root = Op.getOperand(0);
10206 SDValue Trmp = Op.getOperand(1); // trampoline
10207 SDValue FPtr = Op.getOperand(2); // nested function
10208 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10209 DebugLoc dl = Op.getDebugLoc();
10211 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10213 if (Subtarget->is64Bit()) {
10214 SDValue OutChains[6];
10216 // Large code-model.
10217 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10218 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10220 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10221 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10223 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10225 // Load the pointer to the nested function into R11.
10226 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10227 SDValue Addr = Trmp;
10228 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10229 Addr, MachinePointerInfo(TrmpAddr),
10232 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10233 DAG.getConstant(2, MVT::i64));
10234 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10235 MachinePointerInfo(TrmpAddr, 2),
10238 // Load the 'nest' parameter value into R10.
10239 // R10 is specified in X86CallingConv.td
10240 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10241 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10242 DAG.getConstant(10, MVT::i64));
10243 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10244 Addr, MachinePointerInfo(TrmpAddr, 10),
10247 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10248 DAG.getConstant(12, MVT::i64));
10249 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10250 MachinePointerInfo(TrmpAddr, 12),
10253 // Jump to the nested function.
10254 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10255 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10256 DAG.getConstant(20, MVT::i64));
10257 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10258 Addr, MachinePointerInfo(TrmpAddr, 20),
10261 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10262 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10263 DAG.getConstant(22, MVT::i64));
10264 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10265 MachinePointerInfo(TrmpAddr, 22),
10268 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10270 const Function *Func =
10271 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10272 CallingConv::ID CC = Func->getCallingConv();
10277 llvm_unreachable("Unsupported calling convention");
10278 case CallingConv::C:
10279 case CallingConv::X86_StdCall: {
10280 // Pass 'nest' parameter in ECX.
10281 // Must be kept in sync with X86CallingConv.td
10282 NestReg = X86::ECX;
10284 // Check that ECX wasn't needed by an 'inreg' parameter.
10285 FunctionType *FTy = Func->getFunctionType();
10286 const AttrListPtr &Attrs = Func->getAttributes();
10288 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10289 unsigned InRegCount = 0;
10292 for (FunctionType::param_iterator I = FTy->param_begin(),
10293 E = FTy->param_end(); I != E; ++I, ++Idx)
10294 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10295 // FIXME: should only count parameters that are lowered to integers.
10296 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10298 if (InRegCount > 2) {
10299 report_fatal_error("Nest register in use - reduce number of inreg"
10305 case CallingConv::X86_FastCall:
10306 case CallingConv::X86_ThisCall:
10307 case CallingConv::Fast:
10308 // Pass 'nest' parameter in EAX.
10309 // Must be kept in sync with X86CallingConv.td
10310 NestReg = X86::EAX;
10314 SDValue OutChains[4];
10315 SDValue Addr, Disp;
10317 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10318 DAG.getConstant(10, MVT::i32));
10319 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10321 // This is storing the opcode for MOV32ri.
10322 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10323 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10324 OutChains[0] = DAG.getStore(Root, dl,
10325 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10326 Trmp, MachinePointerInfo(TrmpAddr),
10329 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10330 DAG.getConstant(1, MVT::i32));
10331 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10332 MachinePointerInfo(TrmpAddr, 1),
10335 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10336 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10337 DAG.getConstant(5, MVT::i32));
10338 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10339 MachinePointerInfo(TrmpAddr, 5),
10342 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10343 DAG.getConstant(6, MVT::i32));
10344 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10345 MachinePointerInfo(TrmpAddr, 6),
10348 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10352 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10353 SelectionDAG &DAG) const {
10355 The rounding mode is in bits 11:10 of FPSR, and has the following
10357 00 Round to nearest
10362 FLT_ROUNDS, on the other hand, expects the following:
10369 To perform the conversion, we do:
10370 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10373 MachineFunction &MF = DAG.getMachineFunction();
10374 const TargetMachine &TM = MF.getTarget();
10375 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10376 unsigned StackAlignment = TFI.getStackAlignment();
10377 EVT VT = Op.getValueType();
10378 DebugLoc DL = Op.getDebugLoc();
10380 // Save FP Control Word to stack slot
10381 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10382 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10385 MachineMemOperand *MMO =
10386 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10387 MachineMemOperand::MOStore, 2, 2);
10389 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10390 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10391 DAG.getVTList(MVT::Other),
10392 Ops, 2, MVT::i16, MMO);
10394 // Load FP Control Word from stack slot
10395 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10396 MachinePointerInfo(), false, false, false, 0);
10398 // Transform as necessary
10400 DAG.getNode(ISD::SRL, DL, MVT::i16,
10401 DAG.getNode(ISD::AND, DL, MVT::i16,
10402 CWD, DAG.getConstant(0x800, MVT::i16)),
10403 DAG.getConstant(11, MVT::i8));
10405 DAG.getNode(ISD::SRL, DL, MVT::i16,
10406 DAG.getNode(ISD::AND, DL, MVT::i16,
10407 CWD, DAG.getConstant(0x400, MVT::i16)),
10408 DAG.getConstant(9, MVT::i8));
10411 DAG.getNode(ISD::AND, DL, MVT::i16,
10412 DAG.getNode(ISD::ADD, DL, MVT::i16,
10413 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10414 DAG.getConstant(1, MVT::i16)),
10415 DAG.getConstant(3, MVT::i16));
10418 return DAG.getNode((VT.getSizeInBits() < 16 ?
10419 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10422 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10423 EVT VT = Op.getValueType();
10425 unsigned NumBits = VT.getSizeInBits();
10426 DebugLoc dl = Op.getDebugLoc();
10428 Op = Op.getOperand(0);
10429 if (VT == MVT::i8) {
10430 // Zero extend to i32 since there is not an i8 bsr.
10432 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10435 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10436 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10437 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10439 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10442 DAG.getConstant(NumBits+NumBits-1, OpVT),
10443 DAG.getConstant(X86::COND_E, MVT::i8),
10446 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10448 // Finally xor with NumBits-1.
10449 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10452 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10456 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10457 SelectionDAG &DAG) const {
10458 EVT VT = Op.getValueType();
10460 unsigned NumBits = VT.getSizeInBits();
10461 DebugLoc dl = Op.getDebugLoc();
10463 Op = Op.getOperand(0);
10464 if (VT == MVT::i8) {
10465 // Zero extend to i32 since there is not an i8 bsr.
10467 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10470 // Issue a bsr (scan bits in reverse).
10471 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10472 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10474 // And xor with NumBits-1.
10475 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10478 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10482 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10483 EVT VT = Op.getValueType();
10484 unsigned NumBits = VT.getSizeInBits();
10485 DebugLoc dl = Op.getDebugLoc();
10486 Op = Op.getOperand(0);
10488 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10489 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10490 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10492 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10495 DAG.getConstant(NumBits, VT),
10496 DAG.getConstant(X86::COND_E, MVT::i8),
10499 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10502 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10503 // ones, and then concatenate the result back.
10504 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10505 EVT VT = Op.getValueType();
10507 assert(VT.is256BitVector() && VT.isInteger() &&
10508 "Unsupported value type for operation");
10510 unsigned NumElems = VT.getVectorNumElements();
10511 DebugLoc dl = Op.getDebugLoc();
10513 // Extract the LHS vectors
10514 SDValue LHS = Op.getOperand(0);
10515 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10516 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10518 // Extract the RHS vectors
10519 SDValue RHS = Op.getOperand(1);
10520 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10521 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10523 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10524 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10526 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10527 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10528 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10531 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10532 assert(Op.getValueType().is256BitVector() &&
10533 Op.getValueType().isInteger() &&
10534 "Only handle AVX 256-bit vector integer operation");
10535 return Lower256IntArith(Op, DAG);
10538 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10539 assert(Op.getValueType().is256BitVector() &&
10540 Op.getValueType().isInteger() &&
10541 "Only handle AVX 256-bit vector integer operation");
10542 return Lower256IntArith(Op, DAG);
10545 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10546 EVT VT = Op.getValueType();
10548 // Decompose 256-bit ops into smaller 128-bit ops.
10549 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10550 return Lower256IntArith(Op, DAG);
10552 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10553 "Only know how to lower V2I64/V4I64 multiply");
10555 DebugLoc dl = Op.getDebugLoc();
10557 // Ahi = psrlqi(a, 32);
10558 // Bhi = psrlqi(b, 32);
10560 // AloBlo = pmuludq(a, b);
10561 // AloBhi = pmuludq(a, Bhi);
10562 // AhiBlo = pmuludq(Ahi, b);
10564 // AloBhi = psllqi(AloBhi, 32);
10565 // AhiBlo = psllqi(AhiBlo, 32);
10566 // return AloBlo + AloBhi + AhiBlo;
10568 SDValue A = Op.getOperand(0);
10569 SDValue B = Op.getOperand(1);
10571 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10573 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10574 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10576 // Bit cast to 32-bit vectors for MULUDQ
10577 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10578 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10579 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10580 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10581 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10583 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10584 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10585 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10587 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10588 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10590 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10591 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10594 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10596 EVT VT = Op.getValueType();
10597 DebugLoc dl = Op.getDebugLoc();
10598 SDValue R = Op.getOperand(0);
10599 SDValue Amt = Op.getOperand(1);
10600 LLVMContext *Context = DAG.getContext();
10602 if (!Subtarget->hasSSE2())
10605 // Optimize shl/srl/sra with constant shift amount.
10606 if (isSplatVector(Amt.getNode())) {
10607 SDValue SclrAmt = Amt->getOperand(0);
10608 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10609 uint64_t ShiftAmt = C->getZExtValue();
10611 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10612 (Subtarget->hasAVX2() &&
10613 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10614 if (Op.getOpcode() == ISD::SHL)
10615 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10616 DAG.getConstant(ShiftAmt, MVT::i32));
10617 if (Op.getOpcode() == ISD::SRL)
10618 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10619 DAG.getConstant(ShiftAmt, MVT::i32));
10620 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10621 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10622 DAG.getConstant(ShiftAmt, MVT::i32));
10625 if (VT == MVT::v16i8) {
10626 if (Op.getOpcode() == ISD::SHL) {
10627 // Make a large shift.
10628 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10629 DAG.getConstant(ShiftAmt, MVT::i32));
10630 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10631 // Zero out the rightmost bits.
10632 SmallVector<SDValue, 16> V(16,
10633 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10635 return DAG.getNode(ISD::AND, dl, VT, SHL,
10636 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10638 if (Op.getOpcode() == ISD::SRL) {
10639 // Make a large shift.
10640 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10641 DAG.getConstant(ShiftAmt, MVT::i32));
10642 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10643 // Zero out the leftmost bits.
10644 SmallVector<SDValue, 16> V(16,
10645 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10647 return DAG.getNode(ISD::AND, dl, VT, SRL,
10648 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10650 if (Op.getOpcode() == ISD::SRA) {
10651 if (ShiftAmt == 7) {
10652 // R s>> 7 === R s< 0
10653 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10654 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10657 // R s>> a === ((R u>> a) ^ m) - m
10658 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10659 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10661 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10662 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10663 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10666 llvm_unreachable("Unknown shift opcode.");
10669 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10670 if (Op.getOpcode() == ISD::SHL) {
10671 // Make a large shift.
10672 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10673 DAG.getConstant(ShiftAmt, MVT::i32));
10674 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10675 // Zero out the rightmost bits.
10676 SmallVector<SDValue, 32> V(32,
10677 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10679 return DAG.getNode(ISD::AND, dl, VT, SHL,
10680 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10682 if (Op.getOpcode() == ISD::SRL) {
10683 // Make a large shift.
10684 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10685 DAG.getConstant(ShiftAmt, MVT::i32));
10686 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10687 // Zero out the leftmost bits.
10688 SmallVector<SDValue, 32> V(32,
10689 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10691 return DAG.getNode(ISD::AND, dl, VT, SRL,
10692 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10694 if (Op.getOpcode() == ISD::SRA) {
10695 if (ShiftAmt == 7) {
10696 // R s>> 7 === R s< 0
10697 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10698 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10701 // R s>> a === ((R u>> a) ^ m) - m
10702 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10703 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10705 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10706 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10707 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10710 llvm_unreachable("Unknown shift opcode.");
10715 // Lower SHL with variable shift amount.
10716 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10717 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10718 DAG.getConstant(23, MVT::i32));
10720 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10721 Constant *C = ConstantDataVector::get(*Context, CV);
10722 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10723 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10724 MachinePointerInfo::getConstantPool(),
10725 false, false, false, 16);
10727 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10728 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10729 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10730 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10732 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10733 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10736 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10737 DAG.getConstant(5, MVT::i32));
10738 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10740 // Turn 'a' into a mask suitable for VSELECT
10741 SDValue VSelM = DAG.getConstant(0x80, VT);
10742 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10743 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10745 SDValue CM1 = DAG.getConstant(0x0f, VT);
10746 SDValue CM2 = DAG.getConstant(0x3f, VT);
10748 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10749 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10750 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10751 DAG.getConstant(4, MVT::i32), DAG);
10752 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10753 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10756 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10757 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10758 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10760 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10761 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10762 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10763 DAG.getConstant(2, MVT::i32), DAG);
10764 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10765 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10768 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10769 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10770 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10772 // return VSELECT(r, r+r, a);
10773 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10774 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10778 // Decompose 256-bit shifts into smaller 128-bit shifts.
10779 if (VT.is256BitVector()) {
10780 unsigned NumElems = VT.getVectorNumElements();
10781 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10782 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10784 // Extract the two vectors
10785 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10786 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10788 // Recreate the shift amount vectors
10789 SDValue Amt1, Amt2;
10790 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10791 // Constant shift amount
10792 SmallVector<SDValue, 4> Amt1Csts;
10793 SmallVector<SDValue, 4> Amt2Csts;
10794 for (unsigned i = 0; i != NumElems/2; ++i)
10795 Amt1Csts.push_back(Amt->getOperand(i));
10796 for (unsigned i = NumElems/2; i != NumElems; ++i)
10797 Amt2Csts.push_back(Amt->getOperand(i));
10799 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10800 &Amt1Csts[0], NumElems/2);
10801 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10802 &Amt2Csts[0], NumElems/2);
10804 // Variable shift amount
10805 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10806 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10809 // Issue new vector shifts for the smaller types
10810 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10811 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10813 // Concatenate the result back
10814 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10820 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10821 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10822 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10823 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10824 // has only one use.
10825 SDNode *N = Op.getNode();
10826 SDValue LHS = N->getOperand(0);
10827 SDValue RHS = N->getOperand(1);
10828 unsigned BaseOp = 0;
10830 DebugLoc DL = Op.getDebugLoc();
10831 switch (Op.getOpcode()) {
10832 default: llvm_unreachable("Unknown ovf instruction!");
10834 // A subtract of one will be selected as a INC. Note that INC doesn't
10835 // set CF, so we can't do this for UADDO.
10836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10838 BaseOp = X86ISD::INC;
10839 Cond = X86::COND_O;
10842 BaseOp = X86ISD::ADD;
10843 Cond = X86::COND_O;
10846 BaseOp = X86ISD::ADD;
10847 Cond = X86::COND_B;
10850 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10851 // set CF, so we can't do this for USUBO.
10852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10854 BaseOp = X86ISD::DEC;
10855 Cond = X86::COND_O;
10858 BaseOp = X86ISD::SUB;
10859 Cond = X86::COND_O;
10862 BaseOp = X86ISD::SUB;
10863 Cond = X86::COND_B;
10866 BaseOp = X86ISD::SMUL;
10867 Cond = X86::COND_O;
10869 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10870 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10872 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10875 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10876 DAG.getConstant(X86::COND_O, MVT::i32),
10877 SDValue(Sum.getNode(), 2));
10879 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10883 // Also sets EFLAGS.
10884 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10885 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10888 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10889 DAG.getConstant(Cond, MVT::i32),
10890 SDValue(Sum.getNode(), 1));
10892 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10895 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10896 SelectionDAG &DAG) const {
10897 DebugLoc dl = Op.getDebugLoc();
10898 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10899 EVT VT = Op.getValueType();
10901 if (!Subtarget->hasSSE2() || !VT.isVector())
10904 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10905 ExtraVT.getScalarType().getSizeInBits();
10906 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10908 switch (VT.getSimpleVT().SimpleTy) {
10909 default: return SDValue();
10912 if (!Subtarget->hasAVX())
10914 if (!Subtarget->hasAVX2()) {
10915 // needs to be split
10916 unsigned NumElems = VT.getVectorNumElements();
10918 // Extract the LHS vectors
10919 SDValue LHS = Op.getOperand(0);
10920 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10921 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10923 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10924 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10926 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10927 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10928 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10930 SDValue Extra = DAG.getValueType(ExtraVT);
10932 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10933 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10935 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10940 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10941 Op.getOperand(0), ShAmt, DAG);
10942 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10948 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10949 DebugLoc dl = Op.getDebugLoc();
10951 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10952 // There isn't any reason to disable it if the target processor supports it.
10953 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10954 SDValue Chain = Op.getOperand(0);
10955 SDValue Zero = DAG.getConstant(0, MVT::i32);
10957 DAG.getRegister(X86::ESP, MVT::i32), // Base
10958 DAG.getTargetConstant(1, MVT::i8), // Scale
10959 DAG.getRegister(0, MVT::i32), // Index
10960 DAG.getTargetConstant(0, MVT::i32), // Disp
10961 DAG.getRegister(0, MVT::i32), // Segment.
10966 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10967 array_lengthof(Ops));
10968 return SDValue(Res, 0);
10971 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10973 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10975 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10976 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10977 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10978 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10980 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10981 if (!Op1 && !Op2 && !Op3 && Op4)
10982 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10984 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10985 if (Op1 && !Op2 && !Op3 && !Op4)
10986 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10988 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10990 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10993 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10994 SelectionDAG &DAG) const {
10995 DebugLoc dl = Op.getDebugLoc();
10996 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10997 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10998 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10999 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11001 // The only fence that needs an instruction is a sequentially-consistent
11002 // cross-thread fence.
11003 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11004 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11005 // no-sse2). There isn't any reason to disable it if the target processor
11007 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11008 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11010 SDValue Chain = Op.getOperand(0);
11011 SDValue Zero = DAG.getConstant(0, MVT::i32);
11013 DAG.getRegister(X86::ESP, MVT::i32), // Base
11014 DAG.getTargetConstant(1, MVT::i8), // Scale
11015 DAG.getRegister(0, MVT::i32), // Index
11016 DAG.getTargetConstant(0, MVT::i32), // Disp
11017 DAG.getRegister(0, MVT::i32), // Segment.
11022 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11023 array_lengthof(Ops));
11024 return SDValue(Res, 0);
11027 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11028 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11032 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11033 EVT T = Op.getValueType();
11034 DebugLoc DL = Op.getDebugLoc();
11037 switch(T.getSimpleVT().SimpleTy) {
11038 default: llvm_unreachable("Invalid value type!");
11039 case MVT::i8: Reg = X86::AL; size = 1; break;
11040 case MVT::i16: Reg = X86::AX; size = 2; break;
11041 case MVT::i32: Reg = X86::EAX; size = 4; break;
11043 assert(Subtarget->is64Bit() && "Node not type legal!");
11044 Reg = X86::RAX; size = 8;
11047 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11048 Op.getOperand(2), SDValue());
11049 SDValue Ops[] = { cpIn.getValue(0),
11052 DAG.getTargetConstant(size, MVT::i8),
11053 cpIn.getValue(1) };
11054 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11055 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11056 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11059 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11063 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11064 SelectionDAG &DAG) const {
11065 assert(Subtarget->is64Bit() && "Result not type legalized?");
11066 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11067 SDValue TheChain = Op.getOperand(0);
11068 DebugLoc dl = Op.getDebugLoc();
11069 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11070 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11071 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11073 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11074 DAG.getConstant(32, MVT::i8));
11076 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11079 return DAG.getMergeValues(Ops, 2, dl);
11082 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11083 SelectionDAG &DAG) const {
11084 EVT SrcVT = Op.getOperand(0).getValueType();
11085 EVT DstVT = Op.getValueType();
11086 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11087 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11088 assert((DstVT == MVT::i64 ||
11089 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11090 "Unexpected custom BITCAST");
11091 // i64 <=> MMX conversions are Legal.
11092 if (SrcVT==MVT::i64 && DstVT.isVector())
11094 if (DstVT==MVT::i64 && SrcVT.isVector())
11096 // MMX <=> MMX conversions are Legal.
11097 if (SrcVT.isVector() && DstVT.isVector())
11099 // All other conversions need to be expanded.
11103 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11104 SDNode *Node = Op.getNode();
11105 DebugLoc dl = Node->getDebugLoc();
11106 EVT T = Node->getValueType(0);
11107 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11108 DAG.getConstant(0, T), Node->getOperand(2));
11109 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11110 cast<AtomicSDNode>(Node)->getMemoryVT(),
11111 Node->getOperand(0),
11112 Node->getOperand(1), negOp,
11113 cast<AtomicSDNode>(Node)->getSrcValue(),
11114 cast<AtomicSDNode>(Node)->getAlignment(),
11115 cast<AtomicSDNode>(Node)->getOrdering(),
11116 cast<AtomicSDNode>(Node)->getSynchScope());
11119 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11120 SDNode *Node = Op.getNode();
11121 DebugLoc dl = Node->getDebugLoc();
11122 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11124 // Convert seq_cst store -> xchg
11125 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11126 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11127 // (The only way to get a 16-byte store is cmpxchg16b)
11128 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11129 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11130 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11131 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11132 cast<AtomicSDNode>(Node)->getMemoryVT(),
11133 Node->getOperand(0),
11134 Node->getOperand(1), Node->getOperand(2),
11135 cast<AtomicSDNode>(Node)->getMemOperand(),
11136 cast<AtomicSDNode>(Node)->getOrdering(),
11137 cast<AtomicSDNode>(Node)->getSynchScope());
11138 return Swap.getValue(1);
11140 // Other atomic stores have a simple pattern.
11144 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11145 EVT VT = Op.getNode()->getValueType(0);
11147 // Let legalize expand this if it isn't a legal type yet.
11148 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11151 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11154 bool ExtraOp = false;
11155 switch (Op.getOpcode()) {
11156 default: llvm_unreachable("Invalid code");
11157 case ISD::ADDC: Opc = X86ISD::ADD; break;
11158 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11159 case ISD::SUBC: Opc = X86ISD::SUB; break;
11160 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11164 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11166 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11167 Op.getOperand(1), Op.getOperand(2));
11170 /// LowerOperation - Provide custom lowering hooks for some operations.
11172 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11173 switch (Op.getOpcode()) {
11174 default: llvm_unreachable("Should not custom lower this!");
11175 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11176 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
11177 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
11178 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
11179 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11180 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11181 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11182 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11183 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11184 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11185 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11186 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
11187 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
11188 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11189 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11190 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11191 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11192 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11193 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11194 case ISD::SHL_PARTS:
11195 case ISD::SRA_PARTS:
11196 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11197 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11198 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11199 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11200 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11201 case ISD::FABS: return LowerFABS(Op, DAG);
11202 case ISD::FNEG: return LowerFNEG(Op, DAG);
11203 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11204 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11205 case ISD::SETCC: return LowerSETCC(Op, DAG);
11206 case ISD::SELECT: return LowerSELECT(Op, DAG);
11207 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11208 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11209 case ISD::VASTART: return LowerVASTART(Op, DAG);
11210 case ISD::VAARG: return LowerVAARG(Op, DAG);
11211 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
11212 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11213 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11214 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11215 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11216 case ISD::FRAME_TO_ARGS_OFFSET:
11217 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11218 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11219 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11220 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11221 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11222 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11223 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11224 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11225 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11226 case ISD::MUL: return LowerMUL(Op, DAG);
11229 case ISD::SHL: return LowerShift(Op, DAG);
11235 case ISD::UMULO: return LowerXALUO(Op, DAG);
11236 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
11237 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11241 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11242 case ISD::ADD: return LowerADD(Op, DAG);
11243 case ISD::SUB: return LowerSUB(Op, DAG);
11247 static void ReplaceATOMIC_LOAD(SDNode *Node,
11248 SmallVectorImpl<SDValue> &Results,
11249 SelectionDAG &DAG) {
11250 DebugLoc dl = Node->getDebugLoc();
11251 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11253 // Convert wide load -> cmpxchg8b/cmpxchg16b
11254 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11255 // (The only way to get a 16-byte load is cmpxchg16b)
11256 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11257 SDValue Zero = DAG.getConstant(0, VT);
11258 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11259 Node->getOperand(0),
11260 Node->getOperand(1), Zero, Zero,
11261 cast<AtomicSDNode>(Node)->getMemOperand(),
11262 cast<AtomicSDNode>(Node)->getOrdering(),
11263 cast<AtomicSDNode>(Node)->getSynchScope());
11264 Results.push_back(Swap.getValue(0));
11265 Results.push_back(Swap.getValue(1));
11269 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11270 SelectionDAG &DAG, unsigned NewOp) {
11271 DebugLoc dl = Node->getDebugLoc();
11272 assert (Node->getValueType(0) == MVT::i64 &&
11273 "Only know how to expand i64 atomics");
11275 SDValue Chain = Node->getOperand(0);
11276 SDValue In1 = Node->getOperand(1);
11277 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11278 Node->getOperand(2), DAG.getIntPtrConstant(0));
11279 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11280 Node->getOperand(2), DAG.getIntPtrConstant(1));
11281 SDValue Ops[] = { Chain, In1, In2L, In2H };
11282 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11284 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11285 cast<MemSDNode>(Node)->getMemOperand());
11286 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11287 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11288 Results.push_back(Result.getValue(2));
11291 /// ReplaceNodeResults - Replace a node with an illegal result type
11292 /// with a new node built out of custom code.
11293 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11294 SmallVectorImpl<SDValue>&Results,
11295 SelectionDAG &DAG) const {
11296 DebugLoc dl = N->getDebugLoc();
11297 switch (N->getOpcode()) {
11299 llvm_unreachable("Do not know how to custom type legalize this operation!");
11300 case ISD::SIGN_EXTEND_INREG:
11305 // We don't want to expand or promote these.
11307 case ISD::FP_TO_SINT:
11308 case ISD::FP_TO_UINT: {
11309 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11311 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11314 std::pair<SDValue,SDValue> Vals =
11315 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11316 SDValue FIST = Vals.first, StackSlot = Vals.second;
11317 if (FIST.getNode() != 0) {
11318 EVT VT = N->getValueType(0);
11319 // Return a load from the stack slot.
11320 if (StackSlot.getNode() != 0)
11321 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11322 MachinePointerInfo(),
11323 false, false, false, 0));
11325 Results.push_back(FIST);
11329 case ISD::READCYCLECOUNTER: {
11330 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11331 SDValue TheChain = N->getOperand(0);
11332 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11333 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11335 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11337 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11338 SDValue Ops[] = { eax, edx };
11339 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11340 Results.push_back(edx.getValue(1));
11343 case ISD::ATOMIC_CMP_SWAP: {
11344 EVT T = N->getValueType(0);
11345 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11346 bool Regs64bit = T == MVT::i128;
11347 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11348 SDValue cpInL, cpInH;
11349 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11350 DAG.getConstant(0, HalfT));
11351 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11352 DAG.getConstant(1, HalfT));
11353 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11354 Regs64bit ? X86::RAX : X86::EAX,
11356 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11357 Regs64bit ? X86::RDX : X86::EDX,
11358 cpInH, cpInL.getValue(1));
11359 SDValue swapInL, swapInH;
11360 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11361 DAG.getConstant(0, HalfT));
11362 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11363 DAG.getConstant(1, HalfT));
11364 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11365 Regs64bit ? X86::RBX : X86::EBX,
11366 swapInL, cpInH.getValue(1));
11367 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11368 Regs64bit ? X86::RCX : X86::ECX,
11369 swapInH, swapInL.getValue(1));
11370 SDValue Ops[] = { swapInH.getValue(0),
11372 swapInH.getValue(1) };
11373 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11374 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11375 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11376 X86ISD::LCMPXCHG8_DAG;
11377 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11379 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11380 Regs64bit ? X86::RAX : X86::EAX,
11381 HalfT, Result.getValue(1));
11382 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11383 Regs64bit ? X86::RDX : X86::EDX,
11384 HalfT, cpOutL.getValue(2));
11385 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11386 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11387 Results.push_back(cpOutH.getValue(1));
11390 case ISD::ATOMIC_LOAD_ADD:
11391 case ISD::ATOMIC_LOAD_AND:
11392 case ISD::ATOMIC_LOAD_NAND:
11393 case ISD::ATOMIC_LOAD_OR:
11394 case ISD::ATOMIC_LOAD_SUB:
11395 case ISD::ATOMIC_LOAD_XOR:
11396 case ISD::ATOMIC_SWAP: {
11398 switch (N->getOpcode()) {
11399 default: llvm_unreachable("Unexpected opcode");
11400 case ISD::ATOMIC_LOAD_ADD:
11401 Opc = X86ISD::ATOMADD64_DAG;
11403 case ISD::ATOMIC_LOAD_AND:
11404 Opc = X86ISD::ATOMAND64_DAG;
11406 case ISD::ATOMIC_LOAD_NAND:
11407 Opc = X86ISD::ATOMNAND64_DAG;
11409 case ISD::ATOMIC_LOAD_OR:
11410 Opc = X86ISD::ATOMOR64_DAG;
11412 case ISD::ATOMIC_LOAD_SUB:
11413 Opc = X86ISD::ATOMSUB64_DAG;
11415 case ISD::ATOMIC_LOAD_XOR:
11416 Opc = X86ISD::ATOMXOR64_DAG;
11418 case ISD::ATOMIC_SWAP:
11419 Opc = X86ISD::ATOMSWAP64_DAG;
11422 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11425 case ISD::ATOMIC_LOAD:
11426 ReplaceATOMIC_LOAD(N, Results, DAG);
11430 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11432 default: return NULL;
11433 case X86ISD::BSF: return "X86ISD::BSF";
11434 case X86ISD::BSR: return "X86ISD::BSR";
11435 case X86ISD::SHLD: return "X86ISD::SHLD";
11436 case X86ISD::SHRD: return "X86ISD::SHRD";
11437 case X86ISD::FAND: return "X86ISD::FAND";
11438 case X86ISD::FOR: return "X86ISD::FOR";
11439 case X86ISD::FXOR: return "X86ISD::FXOR";
11440 case X86ISD::FSRL: return "X86ISD::FSRL";
11441 case X86ISD::FILD: return "X86ISD::FILD";
11442 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11443 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11444 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11445 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11446 case X86ISD::FLD: return "X86ISD::FLD";
11447 case X86ISD::FST: return "X86ISD::FST";
11448 case X86ISD::CALL: return "X86ISD::CALL";
11449 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11450 case X86ISD::BT: return "X86ISD::BT";
11451 case X86ISD::CMP: return "X86ISD::CMP";
11452 case X86ISD::COMI: return "X86ISD::COMI";
11453 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11454 case X86ISD::SETCC: return "X86ISD::SETCC";
11455 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11456 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11457 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11458 case X86ISD::CMOV: return "X86ISD::CMOV";
11459 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11460 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11461 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11462 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11463 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11464 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11465 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11466 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11467 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11468 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11469 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11470 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11471 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11472 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11473 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11474 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11475 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11476 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11477 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11478 case X86ISD::HADD: return "X86ISD::HADD";
11479 case X86ISD::HSUB: return "X86ISD::HSUB";
11480 case X86ISD::FHADD: return "X86ISD::FHADD";
11481 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11482 case X86ISD::FMAX: return "X86ISD::FMAX";
11483 case X86ISD::FMIN: return "X86ISD::FMIN";
11484 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11485 case X86ISD::FMINC: return "X86ISD::FMINC";
11486 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11487 case X86ISD::FRCP: return "X86ISD::FRCP";
11488 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11489 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11490 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11491 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11492 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11493 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11494 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11495 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11496 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11497 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11498 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11499 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11500 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11501 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11502 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11503 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11504 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11505 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11506 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11507 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11508 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11509 case X86ISD::VSHL: return "X86ISD::VSHL";
11510 case X86ISD::VSRL: return "X86ISD::VSRL";
11511 case X86ISD::VSRA: return "X86ISD::VSRA";
11512 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11513 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11514 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11515 case X86ISD::CMPP: return "X86ISD::CMPP";
11516 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11517 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11518 case X86ISD::ADD: return "X86ISD::ADD";
11519 case X86ISD::SUB: return "X86ISD::SUB";
11520 case X86ISD::ADC: return "X86ISD::ADC";
11521 case X86ISD::SBB: return "X86ISD::SBB";
11522 case X86ISD::SMUL: return "X86ISD::SMUL";
11523 case X86ISD::UMUL: return "X86ISD::UMUL";
11524 case X86ISD::INC: return "X86ISD::INC";
11525 case X86ISD::DEC: return "X86ISD::DEC";
11526 case X86ISD::OR: return "X86ISD::OR";
11527 case X86ISD::XOR: return "X86ISD::XOR";
11528 case X86ISD::AND: return "X86ISD::AND";
11529 case X86ISD::ANDN: return "X86ISD::ANDN";
11530 case X86ISD::BLSI: return "X86ISD::BLSI";
11531 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11532 case X86ISD::BLSR: return "X86ISD::BLSR";
11533 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11534 case X86ISD::PTEST: return "X86ISD::PTEST";
11535 case X86ISD::TESTP: return "X86ISD::TESTP";
11536 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11537 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11538 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11539 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11540 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11541 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11542 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11543 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11544 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11545 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11546 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11547 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11548 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11549 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11550 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11551 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11552 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11553 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11554 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11555 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11556 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11557 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11558 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11559 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11560 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11561 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11562 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11563 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11564 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11565 case X86ISD::SAHF: return "X86ISD::SAHF";
11566 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11567 case X86ISD::FMADD: return "X86ISD::FMADD";
11568 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11569 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11570 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11571 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11572 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11576 // isLegalAddressingMode - Return true if the addressing mode represented
11577 // by AM is legal for this target, for a load/store of the specified type.
11578 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11580 // X86 supports extremely general addressing modes.
11581 CodeModel::Model M = getTargetMachine().getCodeModel();
11582 Reloc::Model R = getTargetMachine().getRelocationModel();
11584 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11585 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11590 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11592 // If a reference to this global requires an extra load, we can't fold it.
11593 if (isGlobalStubReference(GVFlags))
11596 // If BaseGV requires a register for the PIC base, we cannot also have a
11597 // BaseReg specified.
11598 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11601 // If lower 4G is not available, then we must use rip-relative addressing.
11602 if ((M != CodeModel::Small || R != Reloc::Static) &&
11603 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11607 switch (AM.Scale) {
11613 // These scales always work.
11618 // These scales are formed with basereg+scalereg. Only accept if there is
11623 default: // Other stuff never works.
11631 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11632 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11634 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11635 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11636 if (NumBits1 <= NumBits2)
11641 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11642 return Imm == (int32_t)Imm;
11645 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11646 // Can also use sub to handle negated immediates.
11647 return Imm == (int32_t)Imm;
11650 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11651 if (!VT1.isInteger() || !VT2.isInteger())
11653 unsigned NumBits1 = VT1.getSizeInBits();
11654 unsigned NumBits2 = VT2.getSizeInBits();
11655 if (NumBits1 <= NumBits2)
11660 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11661 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11662 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11665 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11666 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11667 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11670 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11671 // i16 instructions are longer (0x66 prefix) and potentially slower.
11672 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11675 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11676 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11677 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11678 /// are assumed to be legal.
11680 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11682 // Very little shuffling can be done for 64-bit vectors right now.
11683 if (VT.getSizeInBits() == 64)
11686 // FIXME: pshufb, blends, shifts.
11687 return (VT.getVectorNumElements() == 2 ||
11688 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11689 isMOVLMask(M, VT) ||
11690 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11691 isPSHUFDMask(M, VT) ||
11692 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11693 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11694 isPALIGNRMask(M, VT, Subtarget) ||
11695 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11696 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11697 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11698 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11702 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11704 unsigned NumElts = VT.getVectorNumElements();
11705 // FIXME: This collection of masks seems suspect.
11708 if (NumElts == 4 && VT.is128BitVector()) {
11709 return (isMOVLMask(Mask, VT) ||
11710 isCommutedMOVLMask(Mask, VT, true) ||
11711 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11712 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11717 //===----------------------------------------------------------------------===//
11718 // X86 Scheduler Hooks
11719 //===----------------------------------------------------------------------===//
11721 // private utility function
11722 MachineBasicBlock *
11723 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11724 MachineBasicBlock *MBB,
11731 const TargetRegisterClass *RC,
11732 bool Invert) const {
11733 // For the atomic bitwise operator, we generate
11736 // ld t1 = [bitinstr.addr]
11737 // op t2 = t1, [bitinstr.val]
11738 // not t3 = t2 (if Invert)
11740 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11742 // fallthrough -->nextMBB
11743 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11744 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11745 MachineFunction::iterator MBBIter = MBB;
11748 /// First build the CFG
11749 MachineFunction *F = MBB->getParent();
11750 MachineBasicBlock *thisMBB = MBB;
11751 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11752 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11753 F->insert(MBBIter, newMBB);
11754 F->insert(MBBIter, nextMBB);
11756 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11757 nextMBB->splice(nextMBB->begin(), thisMBB,
11758 llvm::next(MachineBasicBlock::iterator(bInstr)),
11760 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11762 // Update thisMBB to fall through to newMBB
11763 thisMBB->addSuccessor(newMBB);
11765 // newMBB jumps to itself and fall through to nextMBB
11766 newMBB->addSuccessor(nextMBB);
11767 newMBB->addSuccessor(newMBB);
11769 // Insert instructions into newMBB based on incoming instruction
11770 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11771 "unexpected number of operands");
11772 DebugLoc dl = bInstr->getDebugLoc();
11773 MachineOperand& destOper = bInstr->getOperand(0);
11774 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11775 int numArgs = bInstr->getNumOperands() - 1;
11776 for (int i=0; i < numArgs; ++i)
11777 argOpers[i] = &bInstr->getOperand(i+1);
11779 // x86 address has 4 operands: base, index, scale, and displacement
11780 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11781 int valArgIndx = lastAddrIndx + 1;
11783 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11784 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11785 for (int i=0; i <= lastAddrIndx; ++i)
11786 (*MIB).addOperand(*argOpers[i]);
11788 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11789 assert((argOpers[valArgIndx]->isReg() ||
11790 argOpers[valArgIndx]->isImm()) &&
11791 "invalid operand");
11792 if (argOpers[valArgIndx]->isReg())
11793 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11795 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11797 (*MIB).addOperand(*argOpers[valArgIndx]);
11799 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11801 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11806 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11809 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11810 for (int i=0; i <= lastAddrIndx; ++i)
11811 (*MIB).addOperand(*argOpers[i]);
11813 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11814 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11815 bInstr->memoperands_end());
11817 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11818 MIB.addReg(EAXreg);
11821 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11823 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11827 // private utility function: 64 bit atomics on 32 bit host.
11828 MachineBasicBlock *
11829 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11830 MachineBasicBlock *MBB,
11835 bool Invert) const {
11836 // For the atomic bitwise operator, we generate
11837 // thisMBB (instructions are in pairs, except cmpxchg8b)
11838 // ld t1,t2 = [bitinstr.addr]
11840 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11841 // op t5, t6 <- out1, out2, [bitinstr.val]
11842 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11843 // neg t7, t8 < t5, t6 (if Invert)
11844 // mov ECX, EBX <- t5, t6
11845 // mov EAX, EDX <- t1, t2
11846 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11847 // mov t3, t4 <- EAX, EDX
11849 // result in out1, out2
11850 // fallthrough -->nextMBB
11852 const TargetRegisterClass *RC = &X86::GR32RegClass;
11853 const unsigned LoadOpc = X86::MOV32rm;
11854 const unsigned NotOpc = X86::NOT32r;
11855 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11856 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11857 MachineFunction::iterator MBBIter = MBB;
11860 /// First build the CFG
11861 MachineFunction *F = MBB->getParent();
11862 MachineBasicBlock *thisMBB = MBB;
11863 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11864 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11865 F->insert(MBBIter, newMBB);
11866 F->insert(MBBIter, nextMBB);
11868 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11869 nextMBB->splice(nextMBB->begin(), thisMBB,
11870 llvm::next(MachineBasicBlock::iterator(bInstr)),
11872 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11874 // Update thisMBB to fall through to newMBB
11875 thisMBB->addSuccessor(newMBB);
11877 // newMBB jumps to itself and fall through to nextMBB
11878 newMBB->addSuccessor(nextMBB);
11879 newMBB->addSuccessor(newMBB);
11881 DebugLoc dl = bInstr->getDebugLoc();
11882 // Insert instructions into newMBB based on incoming instruction
11883 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11884 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11885 "unexpected number of operands");
11886 MachineOperand& dest1Oper = bInstr->getOperand(0);
11887 MachineOperand& dest2Oper = bInstr->getOperand(1);
11888 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11889 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11890 argOpers[i] = &bInstr->getOperand(i+2);
11892 // We use some of the operands multiple times, so conservatively just
11893 // clear any kill flags that might be present.
11894 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11895 argOpers[i]->setIsKill(false);
11898 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11899 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11901 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11902 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11903 for (int i=0; i <= lastAddrIndx; ++i)
11904 (*MIB).addOperand(*argOpers[i]);
11905 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11906 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11907 // add 4 to displacement.
11908 for (int i=0; i <= lastAddrIndx-2; ++i)
11909 (*MIB).addOperand(*argOpers[i]);
11910 MachineOperand newOp3 = *(argOpers[3]);
11911 if (newOp3.isImm())
11912 newOp3.setImm(newOp3.getImm()+4);
11914 newOp3.setOffset(newOp3.getOffset()+4);
11915 (*MIB).addOperand(newOp3);
11916 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11918 // t3/4 are defined later, at the bottom of the loop
11919 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11920 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11921 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11922 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11923 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11924 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11926 // The subsequent operations should be using the destination registers of
11927 // the PHI instructions.
11928 t1 = dest1Oper.getReg();
11929 t2 = dest2Oper.getReg();
11931 int valArgIndx = lastAddrIndx + 1;
11932 assert((argOpers[valArgIndx]->isReg() ||
11933 argOpers[valArgIndx]->isImm()) &&
11934 "invalid operand");
11935 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11936 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11937 if (argOpers[valArgIndx]->isReg())
11938 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11940 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11941 if (regOpcL != X86::MOV32rr)
11943 (*MIB).addOperand(*argOpers[valArgIndx]);
11944 assert(argOpers[valArgIndx + 1]->isReg() ==
11945 argOpers[valArgIndx]->isReg());
11946 assert(argOpers[valArgIndx + 1]->isImm() ==
11947 argOpers[valArgIndx]->isImm());
11948 if (argOpers[valArgIndx + 1]->isReg())
11949 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11951 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11952 if (regOpcH != X86::MOV32rr)
11954 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11958 t7 = F->getRegInfo().createVirtualRegister(RC);
11959 t8 = F->getRegInfo().createVirtualRegister(RC);
11960 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11961 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11967 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11969 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11972 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11974 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11977 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11978 for (int i=0; i <= lastAddrIndx; ++i)
11979 (*MIB).addOperand(*argOpers[i]);
11981 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11982 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11983 bInstr->memoperands_end());
11985 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11986 MIB.addReg(X86::EAX);
11987 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11988 MIB.addReg(X86::EDX);
11991 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11993 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11997 // private utility function
11998 MachineBasicBlock *
11999 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12000 MachineBasicBlock *MBB,
12001 unsigned cmovOpc) const {
12002 // For the atomic min/max operator, we generate
12005 // ld t1 = [min/max.addr]
12006 // mov t2 = [min/max.val]
12008 // cmov[cond] t2 = t1
12010 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
12012 // fallthrough -->nextMBB
12014 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12015 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12016 MachineFunction::iterator MBBIter = MBB;
12019 /// First build the CFG
12020 MachineFunction *F = MBB->getParent();
12021 MachineBasicBlock *thisMBB = MBB;
12022 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12023 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12024 F->insert(MBBIter, newMBB);
12025 F->insert(MBBIter, nextMBB);
12027 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12028 nextMBB->splice(nextMBB->begin(), thisMBB,
12029 llvm::next(MachineBasicBlock::iterator(mInstr)),
12031 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12033 // Update thisMBB to fall through to newMBB
12034 thisMBB->addSuccessor(newMBB);
12036 // newMBB jumps to newMBB and fall through to nextMBB
12037 newMBB->addSuccessor(nextMBB);
12038 newMBB->addSuccessor(newMBB);
12040 DebugLoc dl = mInstr->getDebugLoc();
12041 // Insert instructions into newMBB based on incoming instruction
12042 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12043 "unexpected number of operands");
12044 MachineOperand& destOper = mInstr->getOperand(0);
12045 MachineOperand* argOpers[2 + X86::AddrNumOperands];
12046 int numArgs = mInstr->getNumOperands() - 1;
12047 for (int i=0; i < numArgs; ++i)
12048 argOpers[i] = &mInstr->getOperand(i+1);
12050 // x86 address has 4 operands: base, index, scale, and displacement
12051 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12052 int valArgIndx = lastAddrIndx + 1;
12054 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12055 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12056 for (int i=0; i <= lastAddrIndx; ++i)
12057 (*MIB).addOperand(*argOpers[i]);
12059 // We only support register and immediate values
12060 assert((argOpers[valArgIndx]->isReg() ||
12061 argOpers[valArgIndx]->isImm()) &&
12062 "invalid operand");
12064 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12065 if (argOpers[valArgIndx]->isReg())
12066 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12068 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12069 (*MIB).addOperand(*argOpers[valArgIndx]);
12071 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12074 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12079 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12080 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12084 // Cmp and exchange if none has modified the memory location
12085 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12086 for (int i=0; i <= lastAddrIndx; ++i)
12087 (*MIB).addOperand(*argOpers[i]);
12089 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12090 (*MIB).setMemRefs(mInstr->memoperands_begin(),
12091 mInstr->memoperands_end());
12093 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12094 MIB.addReg(X86::EAX);
12097 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12099 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
12103 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12104 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12105 // in the .td file.
12106 MachineBasicBlock *
12107 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12108 unsigned numArgs, bool memArg) const {
12109 assert(Subtarget->hasSSE42() &&
12110 "Target must have SSE4.2 or AVX features enabled");
12112 DebugLoc dl = MI->getDebugLoc();
12113 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12115 if (!Subtarget->hasAVX()) {
12117 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12119 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12122 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12124 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12127 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12128 for (unsigned i = 0; i < numArgs; ++i) {
12129 MachineOperand &Op = MI->getOperand(i+1);
12130 if (!(Op.isReg() && Op.isImplicit()))
12131 MIB.addOperand(Op);
12133 BuildMI(*BB, MI, dl,
12134 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12135 .addReg(X86::XMM0);
12137 MI->eraseFromParent();
12141 MachineBasicBlock *
12142 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12143 DebugLoc dl = MI->getDebugLoc();
12144 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12146 // Address into RAX/EAX, other two args into ECX, EDX.
12147 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12148 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12149 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12150 for (int i = 0; i < X86::AddrNumOperands; ++i)
12151 MIB.addOperand(MI->getOperand(i));
12153 unsigned ValOps = X86::AddrNumOperands;
12154 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12155 .addReg(MI->getOperand(ValOps).getReg());
12156 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12157 .addReg(MI->getOperand(ValOps+1).getReg());
12159 // The instruction doesn't actually take any operands though.
12160 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12162 MI->eraseFromParent(); // The pseudo is gone now.
12166 MachineBasicBlock *
12167 X86TargetLowering::EmitVAARG64WithCustomInserter(
12169 MachineBasicBlock *MBB) const {
12170 // Emit va_arg instruction on X86-64.
12172 // Operands to this pseudo-instruction:
12173 // 0 ) Output : destination address (reg)
12174 // 1-5) Input : va_list address (addr, i64mem)
12175 // 6 ) ArgSize : Size (in bytes) of vararg type
12176 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12177 // 8 ) Align : Alignment of type
12178 // 9 ) EFLAGS (implicit-def)
12180 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12181 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12183 unsigned DestReg = MI->getOperand(0).getReg();
12184 MachineOperand &Base = MI->getOperand(1);
12185 MachineOperand &Scale = MI->getOperand(2);
12186 MachineOperand &Index = MI->getOperand(3);
12187 MachineOperand &Disp = MI->getOperand(4);
12188 MachineOperand &Segment = MI->getOperand(5);
12189 unsigned ArgSize = MI->getOperand(6).getImm();
12190 unsigned ArgMode = MI->getOperand(7).getImm();
12191 unsigned Align = MI->getOperand(8).getImm();
12193 // Memory Reference
12194 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12195 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12196 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12198 // Machine Information
12199 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12200 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12201 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12202 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12203 DebugLoc DL = MI->getDebugLoc();
12205 // struct va_list {
12208 // i64 overflow_area (address)
12209 // i64 reg_save_area (address)
12211 // sizeof(va_list) = 24
12212 // alignment(va_list) = 8
12214 unsigned TotalNumIntRegs = 6;
12215 unsigned TotalNumXMMRegs = 8;
12216 bool UseGPOffset = (ArgMode == 1);
12217 bool UseFPOffset = (ArgMode == 2);
12218 unsigned MaxOffset = TotalNumIntRegs * 8 +
12219 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12221 /* Align ArgSize to a multiple of 8 */
12222 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12223 bool NeedsAlign = (Align > 8);
12225 MachineBasicBlock *thisMBB = MBB;
12226 MachineBasicBlock *overflowMBB;
12227 MachineBasicBlock *offsetMBB;
12228 MachineBasicBlock *endMBB;
12230 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12231 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12232 unsigned OffsetReg = 0;
12234 if (!UseGPOffset && !UseFPOffset) {
12235 // If we only pull from the overflow region, we don't create a branch.
12236 // We don't need to alter control flow.
12237 OffsetDestReg = 0; // unused
12238 OverflowDestReg = DestReg;
12241 overflowMBB = thisMBB;
12244 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12245 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12246 // If not, pull from overflow_area. (branch to overflowMBB)
12251 // offsetMBB overflowMBB
12256 // Registers for the PHI in endMBB
12257 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12258 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12260 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12261 MachineFunction *MF = MBB->getParent();
12262 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12263 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12264 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12266 MachineFunction::iterator MBBIter = MBB;
12269 // Insert the new basic blocks
12270 MF->insert(MBBIter, offsetMBB);
12271 MF->insert(MBBIter, overflowMBB);
12272 MF->insert(MBBIter, endMBB);
12274 // Transfer the remainder of MBB and its successor edges to endMBB.
12275 endMBB->splice(endMBB->begin(), thisMBB,
12276 llvm::next(MachineBasicBlock::iterator(MI)),
12278 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12280 // Make offsetMBB and overflowMBB successors of thisMBB
12281 thisMBB->addSuccessor(offsetMBB);
12282 thisMBB->addSuccessor(overflowMBB);
12284 // endMBB is a successor of both offsetMBB and overflowMBB
12285 offsetMBB->addSuccessor(endMBB);
12286 overflowMBB->addSuccessor(endMBB);
12288 // Load the offset value into a register
12289 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12290 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12294 .addDisp(Disp, UseFPOffset ? 4 : 0)
12295 .addOperand(Segment)
12296 .setMemRefs(MMOBegin, MMOEnd);
12298 // Check if there is enough room left to pull this argument.
12299 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12301 .addImm(MaxOffset + 8 - ArgSizeA8);
12303 // Branch to "overflowMBB" if offset >= max
12304 // Fall through to "offsetMBB" otherwise
12305 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12306 .addMBB(overflowMBB);
12309 // In offsetMBB, emit code to use the reg_save_area.
12311 assert(OffsetReg != 0);
12313 // Read the reg_save_area address.
12314 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12315 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12320 .addOperand(Segment)
12321 .setMemRefs(MMOBegin, MMOEnd);
12323 // Zero-extend the offset
12324 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12325 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12328 .addImm(X86::sub_32bit);
12330 // Add the offset to the reg_save_area to get the final address.
12331 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12332 .addReg(OffsetReg64)
12333 .addReg(RegSaveReg);
12335 // Compute the offset for the next argument
12336 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12337 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12339 .addImm(UseFPOffset ? 16 : 8);
12341 // Store it back into the va_list.
12342 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12346 .addDisp(Disp, UseFPOffset ? 4 : 0)
12347 .addOperand(Segment)
12348 .addReg(NextOffsetReg)
12349 .setMemRefs(MMOBegin, MMOEnd);
12352 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12357 // Emit code to use overflow area
12360 // Load the overflow_area address into a register.
12361 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12362 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12367 .addOperand(Segment)
12368 .setMemRefs(MMOBegin, MMOEnd);
12370 // If we need to align it, do so. Otherwise, just copy the address
12371 // to OverflowDestReg.
12373 // Align the overflow address
12374 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12375 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12377 // aligned_addr = (addr + (align-1)) & ~(align-1)
12378 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12379 .addReg(OverflowAddrReg)
12382 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12384 .addImm(~(uint64_t)(Align-1));
12386 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12387 .addReg(OverflowAddrReg);
12390 // Compute the next overflow address after this argument.
12391 // (the overflow address should be kept 8-byte aligned)
12392 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12393 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12394 .addReg(OverflowDestReg)
12395 .addImm(ArgSizeA8);
12397 // Store the new overflow address.
12398 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12403 .addOperand(Segment)
12404 .addReg(NextAddrReg)
12405 .setMemRefs(MMOBegin, MMOEnd);
12407 // If we branched, emit the PHI to the front of endMBB.
12409 BuildMI(*endMBB, endMBB->begin(), DL,
12410 TII->get(X86::PHI), DestReg)
12411 .addReg(OffsetDestReg).addMBB(offsetMBB)
12412 .addReg(OverflowDestReg).addMBB(overflowMBB);
12415 // Erase the pseudo instruction
12416 MI->eraseFromParent();
12421 MachineBasicBlock *
12422 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12424 MachineBasicBlock *MBB) const {
12425 // Emit code to save XMM registers to the stack. The ABI says that the
12426 // number of registers to save is given in %al, so it's theoretically
12427 // possible to do an indirect jump trick to avoid saving all of them,
12428 // however this code takes a simpler approach and just executes all
12429 // of the stores if %al is non-zero. It's less code, and it's probably
12430 // easier on the hardware branch predictor, and stores aren't all that
12431 // expensive anyway.
12433 // Create the new basic blocks. One block contains all the XMM stores,
12434 // and one block is the final destination regardless of whether any
12435 // stores were performed.
12436 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12437 MachineFunction *F = MBB->getParent();
12438 MachineFunction::iterator MBBIter = MBB;
12440 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12441 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12442 F->insert(MBBIter, XMMSaveMBB);
12443 F->insert(MBBIter, EndMBB);
12445 // Transfer the remainder of MBB and its successor edges to EndMBB.
12446 EndMBB->splice(EndMBB->begin(), MBB,
12447 llvm::next(MachineBasicBlock::iterator(MI)),
12449 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12451 // The original block will now fall through to the XMM save block.
12452 MBB->addSuccessor(XMMSaveMBB);
12453 // The XMMSaveMBB will fall through to the end block.
12454 XMMSaveMBB->addSuccessor(EndMBB);
12456 // Now add the instructions.
12457 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12458 DebugLoc DL = MI->getDebugLoc();
12460 unsigned CountReg = MI->getOperand(0).getReg();
12461 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12462 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12464 if (!Subtarget->isTargetWin64()) {
12465 // If %al is 0, branch around the XMM save block.
12466 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12467 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12468 MBB->addSuccessor(EndMBB);
12471 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12472 // In the XMM save block, save all the XMM argument registers.
12473 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12474 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12475 MachineMemOperand *MMO =
12476 F->getMachineMemOperand(
12477 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12478 MachineMemOperand::MOStore,
12479 /*Size=*/16, /*Align=*/16);
12480 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12481 .addFrameIndex(RegSaveFrameIndex)
12482 .addImm(/*Scale=*/1)
12483 .addReg(/*IndexReg=*/0)
12484 .addImm(/*Disp=*/Offset)
12485 .addReg(/*Segment=*/0)
12486 .addReg(MI->getOperand(i).getReg())
12487 .addMemOperand(MMO);
12490 MI->eraseFromParent(); // The pseudo instruction is gone now.
12495 // The EFLAGS operand of SelectItr might be missing a kill marker
12496 // because there were multiple uses of EFLAGS, and ISel didn't know
12497 // which to mark. Figure out whether SelectItr should have had a
12498 // kill marker, and set it if it should. Returns the correct kill
12500 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12501 MachineBasicBlock* BB,
12502 const TargetRegisterInfo* TRI) {
12503 // Scan forward through BB for a use/def of EFLAGS.
12504 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12505 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12506 const MachineInstr& mi = *miI;
12507 if (mi.readsRegister(X86::EFLAGS))
12509 if (mi.definesRegister(X86::EFLAGS))
12510 break; // Should have kill-flag - update below.
12513 // If we hit the end of the block, check whether EFLAGS is live into a
12515 if (miI == BB->end()) {
12516 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12517 sEnd = BB->succ_end();
12518 sItr != sEnd; ++sItr) {
12519 MachineBasicBlock* succ = *sItr;
12520 if (succ->isLiveIn(X86::EFLAGS))
12525 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12526 // out. SelectMI should have a kill flag on EFLAGS.
12527 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12531 MachineBasicBlock *
12532 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12533 MachineBasicBlock *BB) const {
12534 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12535 DebugLoc DL = MI->getDebugLoc();
12537 // To "insert" a SELECT_CC instruction, we actually have to insert the
12538 // diamond control-flow pattern. The incoming instruction knows the
12539 // destination vreg to set, the condition code register to branch on, the
12540 // true/false values to select between, and a branch opcode to use.
12541 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12542 MachineFunction::iterator It = BB;
12548 // cmpTY ccX, r1, r2
12550 // fallthrough --> copy0MBB
12551 MachineBasicBlock *thisMBB = BB;
12552 MachineFunction *F = BB->getParent();
12553 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12554 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12555 F->insert(It, copy0MBB);
12556 F->insert(It, sinkMBB);
12558 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12559 // live into the sink and copy blocks.
12560 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12561 if (!MI->killsRegister(X86::EFLAGS) &&
12562 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12563 copy0MBB->addLiveIn(X86::EFLAGS);
12564 sinkMBB->addLiveIn(X86::EFLAGS);
12567 // Transfer the remainder of BB and its successor edges to sinkMBB.
12568 sinkMBB->splice(sinkMBB->begin(), BB,
12569 llvm::next(MachineBasicBlock::iterator(MI)),
12571 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12573 // Add the true and fallthrough blocks as its successors.
12574 BB->addSuccessor(copy0MBB);
12575 BB->addSuccessor(sinkMBB);
12577 // Create the conditional branch instruction.
12579 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12580 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12583 // %FalseValue = ...
12584 // # fallthrough to sinkMBB
12585 copy0MBB->addSuccessor(sinkMBB);
12588 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12590 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12591 TII->get(X86::PHI), MI->getOperand(0).getReg())
12592 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12593 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12595 MI->eraseFromParent(); // The pseudo instruction is gone now.
12599 MachineBasicBlock *
12600 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12601 bool Is64Bit) const {
12602 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12603 DebugLoc DL = MI->getDebugLoc();
12604 MachineFunction *MF = BB->getParent();
12605 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12607 assert(getTargetMachine().Options.EnableSegmentedStacks);
12609 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12610 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12613 // ... [Till the alloca]
12614 // If stacklet is not large enough, jump to mallocMBB
12617 // Allocate by subtracting from RSP
12618 // Jump to continueMBB
12621 // Allocate by call to runtime
12625 // [rest of original BB]
12628 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12629 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12630 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12632 MachineRegisterInfo &MRI = MF->getRegInfo();
12633 const TargetRegisterClass *AddrRegClass =
12634 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12636 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12637 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12638 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12639 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12640 sizeVReg = MI->getOperand(1).getReg(),
12641 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12643 MachineFunction::iterator MBBIter = BB;
12646 MF->insert(MBBIter, bumpMBB);
12647 MF->insert(MBBIter, mallocMBB);
12648 MF->insert(MBBIter, continueMBB);
12650 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12651 (MachineBasicBlock::iterator(MI)), BB->end());
12652 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12654 // Add code to the main basic block to check if the stack limit has been hit,
12655 // and if so, jump to mallocMBB otherwise to bumpMBB.
12656 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12657 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12658 .addReg(tmpSPVReg).addReg(sizeVReg);
12659 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12660 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12661 .addReg(SPLimitVReg);
12662 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12664 // bumpMBB simply decreases the stack pointer, since we know the current
12665 // stacklet has enough space.
12666 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12667 .addReg(SPLimitVReg);
12668 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12669 .addReg(SPLimitVReg);
12670 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12672 // Calls into a routine in libgcc to allocate more space from the heap.
12673 const uint32_t *RegMask =
12674 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12676 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12678 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12679 .addExternalSymbol("__morestack_allocate_stack_space")
12680 .addRegMask(RegMask)
12681 .addReg(X86::RDI, RegState::Implicit)
12682 .addReg(X86::RAX, RegState::ImplicitDefine);
12684 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12686 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12687 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12688 .addExternalSymbol("__morestack_allocate_stack_space")
12689 .addRegMask(RegMask)
12690 .addReg(X86::EAX, RegState::ImplicitDefine);
12694 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12697 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12698 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12699 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12701 // Set up the CFG correctly.
12702 BB->addSuccessor(bumpMBB);
12703 BB->addSuccessor(mallocMBB);
12704 mallocMBB->addSuccessor(continueMBB);
12705 bumpMBB->addSuccessor(continueMBB);
12707 // Take care of the PHI nodes.
12708 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12709 MI->getOperand(0).getReg())
12710 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12711 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12713 // Delete the original pseudo instruction.
12714 MI->eraseFromParent();
12717 return continueMBB;
12720 MachineBasicBlock *
12721 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12722 MachineBasicBlock *BB) const {
12723 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12724 DebugLoc DL = MI->getDebugLoc();
12726 assert(!Subtarget->isTargetEnvMacho());
12728 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12729 // non-trivial part is impdef of ESP.
12731 if (Subtarget->isTargetWin64()) {
12732 if (Subtarget->isTargetCygMing()) {
12733 // ___chkstk(Mingw64):
12734 // Clobbers R10, R11, RAX and EFLAGS.
12736 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12737 .addExternalSymbol("___chkstk")
12738 .addReg(X86::RAX, RegState::Implicit)
12739 .addReg(X86::RSP, RegState::Implicit)
12740 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12741 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12742 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12744 // __chkstk(MSVCRT): does not update stack pointer.
12745 // Clobbers R10, R11 and EFLAGS.
12746 // FIXME: RAX(allocated size) might be reused and not killed.
12747 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12748 .addExternalSymbol("__chkstk")
12749 .addReg(X86::RAX, RegState::Implicit)
12750 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12751 // RAX has the offset to subtracted from RSP.
12752 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12757 const char *StackProbeSymbol =
12758 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12760 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12761 .addExternalSymbol(StackProbeSymbol)
12762 .addReg(X86::EAX, RegState::Implicit)
12763 .addReg(X86::ESP, RegState::Implicit)
12764 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12765 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12766 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12769 MI->eraseFromParent(); // The pseudo instruction is gone now.
12773 MachineBasicBlock *
12774 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12775 MachineBasicBlock *BB) const {
12776 // This is pretty easy. We're taking the value that we received from
12777 // our load from the relocation, sticking it in either RDI (x86-64)
12778 // or EAX and doing an indirect call. The return value will then
12779 // be in the normal return register.
12780 const X86InstrInfo *TII
12781 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12782 DebugLoc DL = MI->getDebugLoc();
12783 MachineFunction *F = BB->getParent();
12785 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12786 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12788 // Get a register mask for the lowered call.
12789 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12790 // proper register mask.
12791 const uint32_t *RegMask =
12792 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12793 if (Subtarget->is64Bit()) {
12794 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12795 TII->get(X86::MOV64rm), X86::RDI)
12797 .addImm(0).addReg(0)
12798 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12799 MI->getOperand(3).getTargetFlags())
12801 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12802 addDirectMem(MIB, X86::RDI);
12803 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12804 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12805 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12806 TII->get(X86::MOV32rm), X86::EAX)
12808 .addImm(0).addReg(0)
12809 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12810 MI->getOperand(3).getTargetFlags())
12812 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12813 addDirectMem(MIB, X86::EAX);
12814 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12816 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12817 TII->get(X86::MOV32rm), X86::EAX)
12818 .addReg(TII->getGlobalBaseReg(F))
12819 .addImm(0).addReg(0)
12820 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12821 MI->getOperand(3).getTargetFlags())
12823 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12824 addDirectMem(MIB, X86::EAX);
12825 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12828 MI->eraseFromParent(); // The pseudo instruction is gone now.
12832 MachineBasicBlock *
12833 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12834 MachineBasicBlock *BB) const {
12835 switch (MI->getOpcode()) {
12836 default: llvm_unreachable("Unexpected instr type to insert");
12837 case X86::TAILJMPd64:
12838 case X86::TAILJMPr64:
12839 case X86::TAILJMPm64:
12840 llvm_unreachable("TAILJMP64 would not be touched here.");
12841 case X86::TCRETURNdi64:
12842 case X86::TCRETURNri64:
12843 case X86::TCRETURNmi64:
12845 case X86::WIN_ALLOCA:
12846 return EmitLoweredWinAlloca(MI, BB);
12847 case X86::SEG_ALLOCA_32:
12848 return EmitLoweredSegAlloca(MI, BB, false);
12849 case X86::SEG_ALLOCA_64:
12850 return EmitLoweredSegAlloca(MI, BB, true);
12851 case X86::TLSCall_32:
12852 case X86::TLSCall_64:
12853 return EmitLoweredTLSCall(MI, BB);
12854 case X86::CMOV_GR8:
12855 case X86::CMOV_FR32:
12856 case X86::CMOV_FR64:
12857 case X86::CMOV_V4F32:
12858 case X86::CMOV_V2F64:
12859 case X86::CMOV_V2I64:
12860 case X86::CMOV_V8F32:
12861 case X86::CMOV_V4F64:
12862 case X86::CMOV_V4I64:
12863 case X86::CMOV_GR16:
12864 case X86::CMOV_GR32:
12865 case X86::CMOV_RFP32:
12866 case X86::CMOV_RFP64:
12867 case X86::CMOV_RFP80:
12868 return EmitLoweredSelect(MI, BB);
12870 case X86::FP32_TO_INT16_IN_MEM:
12871 case X86::FP32_TO_INT32_IN_MEM:
12872 case X86::FP32_TO_INT64_IN_MEM:
12873 case X86::FP64_TO_INT16_IN_MEM:
12874 case X86::FP64_TO_INT32_IN_MEM:
12875 case X86::FP64_TO_INT64_IN_MEM:
12876 case X86::FP80_TO_INT16_IN_MEM:
12877 case X86::FP80_TO_INT32_IN_MEM:
12878 case X86::FP80_TO_INT64_IN_MEM: {
12879 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12880 DebugLoc DL = MI->getDebugLoc();
12882 // Change the floating point control register to use "round towards zero"
12883 // mode when truncating to an integer value.
12884 MachineFunction *F = BB->getParent();
12885 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12886 addFrameReference(BuildMI(*BB, MI, DL,
12887 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12889 // Load the old value of the high byte of the control word...
12891 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12892 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12895 // Set the high part to be round to zero...
12896 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12899 // Reload the modified control word now...
12900 addFrameReference(BuildMI(*BB, MI, DL,
12901 TII->get(X86::FLDCW16m)), CWFrameIdx);
12903 // Restore the memory image of control word to original value
12904 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12907 // Get the X86 opcode to use.
12909 switch (MI->getOpcode()) {
12910 default: llvm_unreachable("illegal opcode!");
12911 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12912 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12913 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12914 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12915 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12916 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12917 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12918 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12919 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12923 MachineOperand &Op = MI->getOperand(0);
12925 AM.BaseType = X86AddressMode::RegBase;
12926 AM.Base.Reg = Op.getReg();
12928 AM.BaseType = X86AddressMode::FrameIndexBase;
12929 AM.Base.FrameIndex = Op.getIndex();
12931 Op = MI->getOperand(1);
12933 AM.Scale = Op.getImm();
12934 Op = MI->getOperand(2);
12936 AM.IndexReg = Op.getImm();
12937 Op = MI->getOperand(3);
12938 if (Op.isGlobal()) {
12939 AM.GV = Op.getGlobal();
12941 AM.Disp = Op.getImm();
12943 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12944 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12946 // Reload the original control word now.
12947 addFrameReference(BuildMI(*BB, MI, DL,
12948 TII->get(X86::FLDCW16m)), CWFrameIdx);
12950 MI->eraseFromParent(); // The pseudo instruction is gone now.
12953 // String/text processing lowering.
12954 case X86::PCMPISTRM128REG:
12955 case X86::VPCMPISTRM128REG:
12956 case X86::PCMPISTRM128MEM:
12957 case X86::VPCMPISTRM128MEM:
12958 case X86::PCMPESTRM128REG:
12959 case X86::VPCMPESTRM128REG:
12960 case X86::PCMPESTRM128MEM:
12961 case X86::VPCMPESTRM128MEM: {
12964 switch (MI->getOpcode()) {
12965 default: llvm_unreachable("illegal opcode!");
12966 case X86::PCMPISTRM128REG:
12967 case X86::VPCMPISTRM128REG:
12968 NumArgs = 3; MemArg = false; break;
12969 case X86::PCMPISTRM128MEM:
12970 case X86::VPCMPISTRM128MEM:
12971 NumArgs = 3; MemArg = true; break;
12972 case X86::PCMPESTRM128REG:
12973 case X86::VPCMPESTRM128REG:
12974 NumArgs = 5; MemArg = false; break;
12975 case X86::PCMPESTRM128MEM:
12976 case X86::VPCMPESTRM128MEM:
12977 NumArgs = 5; MemArg = true; break;
12979 return EmitPCMP(MI, BB, NumArgs, MemArg);
12982 // Thread synchronization.
12984 return EmitMonitor(MI, BB);
12986 // Atomic Lowering.
12987 case X86::ATOMMIN32:
12988 case X86::ATOMMAX32:
12989 case X86::ATOMUMIN32:
12990 case X86::ATOMUMAX32:
12991 case X86::ATOMMIN16:
12992 case X86::ATOMMAX16:
12993 case X86::ATOMUMIN16:
12994 case X86::ATOMUMAX16:
12995 case X86::ATOMMIN64:
12996 case X86::ATOMMAX64:
12997 case X86::ATOMUMIN64:
12998 case X86::ATOMUMAX64: {
13000 switch (MI->getOpcode()) {
13001 default: llvm_unreachable("illegal opcode!");
13002 case X86::ATOMMIN32: Opc = X86::CMOVL32rr; break;
13003 case X86::ATOMMAX32: Opc = X86::CMOVG32rr; break;
13004 case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13005 case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13006 case X86::ATOMMIN16: Opc = X86::CMOVL16rr; break;
13007 case X86::ATOMMAX16: Opc = X86::CMOVG16rr; break;
13008 case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13009 case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13010 case X86::ATOMMIN64: Opc = X86::CMOVL64rr; break;
13011 case X86::ATOMMAX64: Opc = X86::CMOVG64rr; break;
13012 case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13013 case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13014 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13016 return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13019 case X86::ATOMAND32:
13020 case X86::ATOMOR32:
13021 case X86::ATOMXOR32:
13022 case X86::ATOMNAND32: {
13023 bool Invert = false;
13024 unsigned RegOpc, ImmOpc;
13025 switch (MI->getOpcode()) {
13026 default: llvm_unreachable("illegal opcode!");
13027 case X86::ATOMAND32:
13028 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13029 case X86::ATOMOR32:
13030 RegOpc = X86::OR32rr; ImmOpc = X86::OR32ri; break;
13031 case X86::ATOMXOR32:
13032 RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13033 case X86::ATOMNAND32:
13034 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13036 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13037 X86::MOV32rm, X86::LCMPXCHG32,
13038 X86::NOT32r, X86::EAX,
13039 &X86::GR32RegClass, Invert);
13042 case X86::ATOMAND16:
13043 case X86::ATOMOR16:
13044 case X86::ATOMXOR16:
13045 case X86::ATOMNAND16: {
13046 bool Invert = false;
13047 unsigned RegOpc, ImmOpc;
13048 switch (MI->getOpcode()) {
13049 default: llvm_unreachable("illegal opcode!");
13050 case X86::ATOMAND16:
13051 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13052 case X86::ATOMOR16:
13053 RegOpc = X86::OR16rr; ImmOpc = X86::OR16ri; break;
13054 case X86::ATOMXOR16:
13055 RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13056 case X86::ATOMNAND16:
13057 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13059 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13060 X86::MOV16rm, X86::LCMPXCHG16,
13061 X86::NOT16r, X86::AX,
13062 &X86::GR16RegClass, Invert);
13065 case X86::ATOMAND8:
13067 case X86::ATOMXOR8:
13068 case X86::ATOMNAND8: {
13069 bool Invert = false;
13070 unsigned RegOpc, ImmOpc;
13071 switch (MI->getOpcode()) {
13072 default: llvm_unreachable("illegal opcode!");
13073 case X86::ATOMAND8:
13074 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13076 RegOpc = X86::OR8rr; ImmOpc = X86::OR8ri; break;
13077 case X86::ATOMXOR8:
13078 RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13079 case X86::ATOMNAND8:
13080 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13082 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13083 X86::MOV8rm, X86::LCMPXCHG8,
13084 X86::NOT8r, X86::AL,
13085 &X86::GR8RegClass, Invert);
13088 // This group is for 64-bit host.
13089 case X86::ATOMAND64:
13090 case X86::ATOMOR64:
13091 case X86::ATOMXOR64:
13092 case X86::ATOMNAND64: {
13093 bool Invert = false;
13094 unsigned RegOpc, ImmOpc;
13095 switch (MI->getOpcode()) {
13096 default: llvm_unreachable("illegal opcode!");
13097 case X86::ATOMAND64:
13098 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13099 case X86::ATOMOR64:
13100 RegOpc = X86::OR64rr; ImmOpc = X86::OR64ri32; break;
13101 case X86::ATOMXOR64:
13102 RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13103 case X86::ATOMNAND64:
13104 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13106 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13107 X86::MOV64rm, X86::LCMPXCHG64,
13108 X86::NOT64r, X86::RAX,
13109 &X86::GR64RegClass, Invert);
13112 // This group does 64-bit operations on a 32-bit host.
13113 case X86::ATOMAND6432:
13114 case X86::ATOMOR6432:
13115 case X86::ATOMXOR6432:
13116 case X86::ATOMNAND6432:
13117 case X86::ATOMADD6432:
13118 case X86::ATOMSUB6432:
13119 case X86::ATOMSWAP6432: {
13120 bool Invert = false;
13121 unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13122 switch (MI->getOpcode()) {
13123 default: llvm_unreachable("illegal opcode!");
13124 case X86::ATOMAND6432:
13125 RegOpcL = RegOpcH = X86::AND32rr;
13126 ImmOpcL = ImmOpcH = X86::AND32ri;
13128 case X86::ATOMOR6432:
13129 RegOpcL = RegOpcH = X86::OR32rr;
13130 ImmOpcL = ImmOpcH = X86::OR32ri;
13132 case X86::ATOMXOR6432:
13133 RegOpcL = RegOpcH = X86::XOR32rr;
13134 ImmOpcL = ImmOpcH = X86::XOR32ri;
13136 case X86::ATOMNAND6432:
13137 RegOpcL = RegOpcH = X86::AND32rr;
13138 ImmOpcL = ImmOpcH = X86::AND32ri;
13141 case X86::ATOMADD6432:
13142 RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13143 ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13145 case X86::ATOMSUB6432:
13146 RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13147 ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13149 case X86::ATOMSWAP6432:
13150 RegOpcL = RegOpcH = X86::MOV32rr;
13151 ImmOpcL = ImmOpcH = X86::MOV32ri;
13154 return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13155 ImmOpcL, ImmOpcH, Invert);
13158 case X86::VASTART_SAVE_XMM_REGS:
13159 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13161 case X86::VAARG_64:
13162 return EmitVAARG64WithCustomInserter(MI, BB);
13166 //===----------------------------------------------------------------------===//
13167 // X86 Optimization Hooks
13168 //===----------------------------------------------------------------------===//
13170 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13173 const SelectionDAG &DAG,
13174 unsigned Depth) const {
13175 unsigned BitWidth = KnownZero.getBitWidth();
13176 unsigned Opc = Op.getOpcode();
13177 assert((Opc >= ISD::BUILTIN_OP_END ||
13178 Opc == ISD::INTRINSIC_WO_CHAIN ||
13179 Opc == ISD::INTRINSIC_W_CHAIN ||
13180 Opc == ISD::INTRINSIC_VOID) &&
13181 "Should use MaskedValueIsZero if you don't know whether Op"
13182 " is a target node!");
13184 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13198 // These nodes' second result is a boolean.
13199 if (Op.getResNo() == 0)
13202 case X86ISD::SETCC:
13203 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13205 case ISD::INTRINSIC_WO_CHAIN: {
13206 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13207 unsigned NumLoBits = 0;
13210 case Intrinsic::x86_sse_movmsk_ps:
13211 case Intrinsic::x86_avx_movmsk_ps_256:
13212 case Intrinsic::x86_sse2_movmsk_pd:
13213 case Intrinsic::x86_avx_movmsk_pd_256:
13214 case Intrinsic::x86_mmx_pmovmskb:
13215 case Intrinsic::x86_sse2_pmovmskb_128:
13216 case Intrinsic::x86_avx2_pmovmskb: {
13217 // High bits of movmskp{s|d}, pmovmskb are known zero.
13219 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13220 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13221 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13222 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13223 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13224 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13225 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13226 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13228 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13237 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13238 unsigned Depth) const {
13239 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13240 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13241 return Op.getValueType().getScalarType().getSizeInBits();
13247 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13248 /// node is a GlobalAddress + offset.
13249 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13250 const GlobalValue* &GA,
13251 int64_t &Offset) const {
13252 if (N->getOpcode() == X86ISD::Wrapper) {
13253 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13254 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13255 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13259 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13262 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13263 /// same as extracting the high 128-bit part of 256-bit vector and then
13264 /// inserting the result into the low part of a new 256-bit vector
13265 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13266 EVT VT = SVOp->getValueType(0);
13267 unsigned NumElems = VT.getVectorNumElements();
13269 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13270 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13271 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13272 SVOp->getMaskElt(j) >= 0)
13278 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13279 /// same as extracting the low 128-bit part of 256-bit vector and then
13280 /// inserting the result into the high part of a new 256-bit vector
13281 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13282 EVT VT = SVOp->getValueType(0);
13283 unsigned NumElems = VT.getVectorNumElements();
13285 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13286 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13287 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13288 SVOp->getMaskElt(j) >= 0)
13294 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13295 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13296 TargetLowering::DAGCombinerInfo &DCI,
13297 const X86Subtarget* Subtarget) {
13298 DebugLoc dl = N->getDebugLoc();
13299 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13300 SDValue V1 = SVOp->getOperand(0);
13301 SDValue V2 = SVOp->getOperand(1);
13302 EVT VT = SVOp->getValueType(0);
13303 unsigned NumElems = VT.getVectorNumElements();
13305 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13306 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13310 // V UNDEF BUILD_VECTOR UNDEF
13312 // CONCAT_VECTOR CONCAT_VECTOR
13315 // RESULT: V + zero extended
13317 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13318 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13319 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13322 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13325 // To match the shuffle mask, the first half of the mask should
13326 // be exactly the first vector, and all the rest a splat with the
13327 // first element of the second one.
13328 for (unsigned i = 0; i != NumElems/2; ++i)
13329 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13330 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13333 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13334 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13335 if (Ld->hasNUsesOfValue(1, 0)) {
13336 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13337 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13339 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13341 Ld->getPointerInfo(),
13342 Ld->getAlignment(),
13343 false/*isVolatile*/, true/*ReadMem*/,
13344 false/*WriteMem*/);
13345 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13349 // Emit a zeroed vector and insert the desired subvector on its
13351 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13352 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13353 return DCI.CombineTo(N, InsV);
13356 //===--------------------------------------------------------------------===//
13357 // Combine some shuffles into subvector extracts and inserts:
13360 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13361 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13362 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13363 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13364 return DCI.CombineTo(N, InsV);
13367 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13368 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13369 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13370 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13371 return DCI.CombineTo(N, InsV);
13377 /// PerformShuffleCombine - Performs several different shuffle combines.
13378 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13379 TargetLowering::DAGCombinerInfo &DCI,
13380 const X86Subtarget *Subtarget) {
13381 DebugLoc dl = N->getDebugLoc();
13382 EVT VT = N->getValueType(0);
13384 // Don't create instructions with illegal types after legalize types has run.
13385 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13386 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13389 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13390 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13391 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13392 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13394 // Only handle 128 wide vector from here on.
13395 if (!VT.is128BitVector())
13398 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13399 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13400 // consecutive, non-overlapping, and in the right order.
13401 SmallVector<SDValue, 16> Elts;
13402 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13403 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13405 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13409 /// DCI, PerformTruncateCombine - Converts truncate operation to
13410 /// a sequence of vector shuffle operations.
13411 /// It is possible when we truncate 256-bit vector to 128-bit vector
13413 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13414 DAGCombinerInfo &DCI) const {
13415 if (!DCI.isBeforeLegalizeOps())
13418 if (!Subtarget->hasAVX())
13421 EVT VT = N->getValueType(0);
13422 SDValue Op = N->getOperand(0);
13423 EVT OpVT = Op.getValueType();
13424 DebugLoc dl = N->getDebugLoc();
13426 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13428 if (Subtarget->hasAVX2()) {
13429 // AVX2: v4i64 -> v4i32
13432 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13434 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13435 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13438 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13439 DAG.getIntPtrConstant(0));
13442 // AVX: v4i64 -> v4i32
13443 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13444 DAG.getIntPtrConstant(0));
13446 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13447 DAG.getIntPtrConstant(2));
13449 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13450 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13453 static const int ShufMask1[] = {0, 2, 0, 0};
13455 SDValue Undef = DAG.getUNDEF(VT);
13456 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13457 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13460 static const int ShufMask2[] = {0, 1, 4, 5};
13462 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13465 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13467 if (Subtarget->hasAVX2()) {
13468 // AVX2: v8i32 -> v8i16
13470 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13473 SmallVector<SDValue,32> pshufbMask;
13474 for (unsigned i = 0; i < 2; ++i) {
13475 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13476 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13477 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13478 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13479 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13480 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13481 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13482 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13483 for (unsigned j = 0; j < 8; ++j)
13484 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13486 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13487 &pshufbMask[0], 32);
13488 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13490 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13492 static const int ShufMask[] = {0, 2, -1, -1};
13493 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13496 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13497 DAG.getIntPtrConstant(0));
13499 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13502 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13503 DAG.getIntPtrConstant(0));
13505 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13506 DAG.getIntPtrConstant(4));
13508 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13509 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13512 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13513 -1, -1, -1, -1, -1, -1, -1, -1};
13515 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13516 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13517 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13519 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13520 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13523 static const int ShufMask2[] = {0, 1, 4, 5};
13525 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13526 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13532 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13533 /// specific shuffle of a load can be folded into a single element load.
13534 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13535 /// shuffles have been customed lowered so we need to handle those here.
13536 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13537 TargetLowering::DAGCombinerInfo &DCI) {
13538 if (DCI.isBeforeLegalizeOps())
13541 SDValue InVec = N->getOperand(0);
13542 SDValue EltNo = N->getOperand(1);
13544 if (!isa<ConstantSDNode>(EltNo))
13547 EVT VT = InVec.getValueType();
13549 bool HasShuffleIntoBitcast = false;
13550 if (InVec.getOpcode() == ISD::BITCAST) {
13551 // Don't duplicate a load with other uses.
13552 if (!InVec.hasOneUse())
13554 EVT BCVT = InVec.getOperand(0).getValueType();
13555 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13557 InVec = InVec.getOperand(0);
13558 HasShuffleIntoBitcast = true;
13561 if (!isTargetShuffle(InVec.getOpcode()))
13564 // Don't duplicate a load with other uses.
13565 if (!InVec.hasOneUse())
13568 SmallVector<int, 16> ShuffleMask;
13570 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13574 // Select the input vector, guarding against out of range extract vector.
13575 unsigned NumElems = VT.getVectorNumElements();
13576 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13577 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13578 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13579 : InVec.getOperand(1);
13581 // If inputs to shuffle are the same for both ops, then allow 2 uses
13582 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13584 if (LdNode.getOpcode() == ISD::BITCAST) {
13585 // Don't duplicate a load with other uses.
13586 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13589 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13590 LdNode = LdNode.getOperand(0);
13593 if (!ISD::isNormalLoad(LdNode.getNode()))
13596 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13598 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13601 if (HasShuffleIntoBitcast) {
13602 // If there's a bitcast before the shuffle, check if the load type and
13603 // alignment is valid.
13604 unsigned Align = LN0->getAlignment();
13605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13606 unsigned NewAlign = TLI.getTargetData()->
13607 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13609 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13613 // All checks match so transform back to vector_shuffle so that DAG combiner
13614 // can finish the job
13615 DebugLoc dl = N->getDebugLoc();
13617 // Create shuffle node taking into account the case that its a unary shuffle
13618 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13619 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13620 InVec.getOperand(0), Shuffle,
13622 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13623 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13627 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13628 /// generation and convert it from being a bunch of shuffles and extracts
13629 /// to a simple store and scalar loads to extract the elements.
13630 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13631 TargetLowering::DAGCombinerInfo &DCI) {
13632 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13633 if (NewOp.getNode())
13636 SDValue InputVector = N->getOperand(0);
13638 // Only operate on vectors of 4 elements, where the alternative shuffling
13639 // gets to be more expensive.
13640 if (InputVector.getValueType() != MVT::v4i32)
13643 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13644 // single use which is a sign-extend or zero-extend, and all elements are
13646 SmallVector<SDNode *, 4> Uses;
13647 unsigned ExtractedElements = 0;
13648 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13649 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13650 if (UI.getUse().getResNo() != InputVector.getResNo())
13653 SDNode *Extract = *UI;
13654 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13657 if (Extract->getValueType(0) != MVT::i32)
13659 if (!Extract->hasOneUse())
13661 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13662 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13664 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13667 // Record which element was extracted.
13668 ExtractedElements |=
13669 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13671 Uses.push_back(Extract);
13674 // If not all the elements were used, this may not be worthwhile.
13675 if (ExtractedElements != 15)
13678 // Ok, we've now decided to do the transformation.
13679 DebugLoc dl = InputVector.getDebugLoc();
13681 // Store the value to a temporary stack slot.
13682 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13683 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13684 MachinePointerInfo(), false, false, 0);
13686 // Replace each use (extract) with a load of the appropriate element.
13687 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13688 UE = Uses.end(); UI != UE; ++UI) {
13689 SDNode *Extract = *UI;
13691 // cOMpute the element's address.
13692 SDValue Idx = Extract->getOperand(1);
13694 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13695 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13697 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13699 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13700 StackPtr, OffsetVal);
13702 // Load the scalar.
13703 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13704 ScalarAddr, MachinePointerInfo(),
13705 false, false, false, 0);
13707 // Replace the exact with the load.
13708 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13711 // The replacement was made in place; don't return anything.
13715 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13717 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13718 TargetLowering::DAGCombinerInfo &DCI,
13719 const X86Subtarget *Subtarget) {
13720 DebugLoc DL = N->getDebugLoc();
13721 SDValue Cond = N->getOperand(0);
13722 // Get the LHS/RHS of the select.
13723 SDValue LHS = N->getOperand(1);
13724 SDValue RHS = N->getOperand(2);
13725 EVT VT = LHS.getValueType();
13727 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13728 // instructions match the semantics of the common C idiom x<y?x:y but not
13729 // x<=y?x:y, because of how they handle negative zero (which can be
13730 // ignored in unsafe-math mode).
13731 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13732 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13733 (Subtarget->hasSSE2() ||
13734 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13735 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13737 unsigned Opcode = 0;
13738 // Check for x CC y ? x : y.
13739 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13740 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13744 // Converting this to a min would handle NaNs incorrectly, and swapping
13745 // the operands would cause it to handle comparisons between positive
13746 // and negative zero incorrectly.
13747 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13748 if (!DAG.getTarget().Options.UnsafeFPMath &&
13749 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13751 std::swap(LHS, RHS);
13753 Opcode = X86ISD::FMIN;
13756 // Converting this to a min would handle comparisons between positive
13757 // and negative zero incorrectly.
13758 if (!DAG.getTarget().Options.UnsafeFPMath &&
13759 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13761 Opcode = X86ISD::FMIN;
13764 // Converting this to a min would handle both negative zeros and NaNs
13765 // incorrectly, but we can swap the operands to fix both.
13766 std::swap(LHS, RHS);
13770 Opcode = X86ISD::FMIN;
13774 // Converting this to a max would handle comparisons between positive
13775 // and negative zero incorrectly.
13776 if (!DAG.getTarget().Options.UnsafeFPMath &&
13777 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13779 Opcode = X86ISD::FMAX;
13782 // Converting this to a max would handle NaNs incorrectly, and swapping
13783 // the operands would cause it to handle comparisons between positive
13784 // and negative zero incorrectly.
13785 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13786 if (!DAG.getTarget().Options.UnsafeFPMath &&
13787 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13789 std::swap(LHS, RHS);
13791 Opcode = X86ISD::FMAX;
13794 // Converting this to a max would handle both negative zeros and NaNs
13795 // incorrectly, but we can swap the operands to fix both.
13796 std::swap(LHS, RHS);
13800 Opcode = X86ISD::FMAX;
13803 // Check for x CC y ? y : x -- a min/max with reversed arms.
13804 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13805 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13809 // Converting this to a min would handle comparisons between positive
13810 // and negative zero incorrectly, and swapping the operands would
13811 // cause it to handle NaNs incorrectly.
13812 if (!DAG.getTarget().Options.UnsafeFPMath &&
13813 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13814 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13816 std::swap(LHS, RHS);
13818 Opcode = X86ISD::FMIN;
13821 // Converting this to a min would handle NaNs incorrectly.
13822 if (!DAG.getTarget().Options.UnsafeFPMath &&
13823 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13825 Opcode = X86ISD::FMIN;
13828 // Converting this to a min would handle both negative zeros and NaNs
13829 // incorrectly, but we can swap the operands to fix both.
13830 std::swap(LHS, RHS);
13834 Opcode = X86ISD::FMIN;
13838 // Converting this to a max would handle NaNs incorrectly.
13839 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13841 Opcode = X86ISD::FMAX;
13844 // Converting this to a max would handle comparisons between positive
13845 // and negative zero incorrectly, and swapping the operands would
13846 // cause it to handle NaNs incorrectly.
13847 if (!DAG.getTarget().Options.UnsafeFPMath &&
13848 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13849 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13851 std::swap(LHS, RHS);
13853 Opcode = X86ISD::FMAX;
13856 // Converting this to a max would handle both negative zeros and NaNs
13857 // incorrectly, but we can swap the operands to fix both.
13858 std::swap(LHS, RHS);
13862 Opcode = X86ISD::FMAX;
13868 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13871 // If this is a select between two integer constants, try to do some
13873 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13874 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13875 // Don't do this for crazy integer types.
13876 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13877 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13878 // so that TrueC (the true value) is larger than FalseC.
13879 bool NeedsCondInvert = false;
13881 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13882 // Efficiently invertible.
13883 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13884 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13885 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13886 NeedsCondInvert = true;
13887 std::swap(TrueC, FalseC);
13890 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13891 if (FalseC->getAPIntValue() == 0 &&
13892 TrueC->getAPIntValue().isPowerOf2()) {
13893 if (NeedsCondInvert) // Invert the condition if needed.
13894 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13895 DAG.getConstant(1, Cond.getValueType()));
13897 // Zero extend the condition if needed.
13898 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13900 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13901 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13902 DAG.getConstant(ShAmt, MVT::i8));
13905 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13906 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13907 if (NeedsCondInvert) // Invert the condition if needed.
13908 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13909 DAG.getConstant(1, Cond.getValueType()));
13911 // Zero extend the condition if needed.
13912 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13913 FalseC->getValueType(0), Cond);
13914 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13915 SDValue(FalseC, 0));
13918 // Optimize cases that will turn into an LEA instruction. This requires
13919 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13920 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13921 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13922 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13924 bool isFastMultiplier = false;
13926 switch ((unsigned char)Diff) {
13928 case 1: // result = add base, cond
13929 case 2: // result = lea base( , cond*2)
13930 case 3: // result = lea base(cond, cond*2)
13931 case 4: // result = lea base( , cond*4)
13932 case 5: // result = lea base(cond, cond*4)
13933 case 8: // result = lea base( , cond*8)
13934 case 9: // result = lea base(cond, cond*8)
13935 isFastMultiplier = true;
13940 if (isFastMultiplier) {
13941 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13942 if (NeedsCondInvert) // Invert the condition if needed.
13943 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13944 DAG.getConstant(1, Cond.getValueType()));
13946 // Zero extend the condition if needed.
13947 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13949 // Scale the condition by the difference.
13951 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13952 DAG.getConstant(Diff, Cond.getValueType()));
13954 // Add the base if non-zero.
13955 if (FalseC->getAPIntValue() != 0)
13956 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13957 SDValue(FalseC, 0));
13964 // Canonicalize max and min:
13965 // (x > y) ? x : y -> (x >= y) ? x : y
13966 // (x < y) ? x : y -> (x <= y) ? x : y
13967 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13968 // the need for an extra compare
13969 // against zero. e.g.
13970 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13972 // testl %edi, %edi
13974 // cmovgl %edi, %eax
13978 // cmovsl %eax, %edi
13979 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13980 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13981 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13982 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13987 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13988 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13989 Cond.getOperand(0), Cond.getOperand(1), NewCC);
13990 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13995 // If we know that this node is legal then we know that it is going to be
13996 // matched by one of the SSE/AVX BLEND instructions. These instructions only
13997 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13998 // to simplify previous instructions.
13999 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14000 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14001 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14002 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14004 // Don't optimize vector selects that map to mask-registers.
14008 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14009 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14011 APInt KnownZero, KnownOne;
14012 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14013 DCI.isBeforeLegalizeOps());
14014 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14015 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14016 DCI.CommitTargetLoweringOpt(TLO);
14022 // Check whether a boolean test is testing a boolean value generated by
14023 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14026 // Simplify the following patterns:
14027 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14028 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14029 // to (Op EFLAGS Cond)
14031 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14032 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14033 // to (Op EFLAGS !Cond)
14035 // where Op could be BRCOND or CMOV.
14037 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14038 // Quit if not CMP and SUB with its value result used.
14039 if (Cmp.getOpcode() != X86ISD::CMP &&
14040 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14043 // Quit if not used as a boolean value.
14044 if (CC != X86::COND_E && CC != X86::COND_NE)
14047 // Check CMP operands. One of them should be 0 or 1 and the other should be
14048 // an SetCC or extended from it.
14049 SDValue Op1 = Cmp.getOperand(0);
14050 SDValue Op2 = Cmp.getOperand(1);
14053 const ConstantSDNode* C = 0;
14054 bool needOppositeCond = (CC == X86::COND_E);
14056 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14058 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14060 else // Quit if all operands are not constants.
14063 if (C->getZExtValue() == 1)
14064 needOppositeCond = !needOppositeCond;
14065 else if (C->getZExtValue() != 0)
14066 // Quit if the constant is neither 0 or 1.
14069 // Skip 'zext' node.
14070 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14071 SetCC = SetCC.getOperand(0);
14073 // Quit if not SETCC.
14074 // FIXME: So far we only handle the boolean value generated from SETCC. If
14075 // there is other ways to generate boolean values, we need handle them here
14077 if (SetCC.getOpcode() != X86ISD::SETCC)
14080 // Set the condition code or opposite one if necessary.
14081 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14082 if (needOppositeCond)
14083 CC = X86::GetOppositeBranchCondition(CC);
14085 return SetCC.getOperand(1);
14088 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14089 /// updated. If only flag result is used and the result is evaluated from a
14090 /// series of element extraction, try to combine it into a PTEST.
14091 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14093 const X86Subtarget *Subtarget) {
14094 SDNode *N = Or.getNode();
14095 DebugLoc DL = N->getDebugLoc();
14097 // Only SSE4.1 and beyond supports PTEST or like.
14098 if (!Subtarget->hasSSE41())
14101 if (N->getOpcode() != X86ISD::OR)
14104 // Quit if the value result of OR is used.
14105 if (N->hasAnyUseOfValue(0))
14108 // Quit if not used as a boolean value.
14109 if (CC != X86::COND_E && CC != X86::COND_NE)
14112 SmallVector<SDValue, 8> Opnds;
14114 EVT VT = MVT::Other;
14117 // Recognize a special case where a vector is casted into wide integer to
14119 Opnds.push_back(N->getOperand(0));
14120 Opnds.push_back(N->getOperand(1));
14122 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14123 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14124 // BFS traverse all OR'd operands.
14125 if (I->getOpcode() == ISD::OR) {
14126 Opnds.push_back(I->getOperand(0));
14127 Opnds.push_back(I->getOperand(1));
14128 // Re-evaluate the number of nodes to be traversed.
14129 e += 2; // 2 more nodes (LHS and RHS) are pushed.
14133 // Quit if a non-EXTRACT_VECTOR_ELT
14134 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14137 // Quit if without a constant index.
14138 SDValue Idx = I->getOperand(1);
14139 if (!isa<ConstantSDNode>(Idx))
14142 // Check if all elements are extracted from the same vector.
14143 SDValue ExtractedFromVec = I->getOperand(0);
14144 if (VecIn.getNode() == 0) {
14145 VT = ExtractedFromVec.getValueType();
14146 // FIXME: only 128-bit vector is supported so far.
14147 if (!VT.is128BitVector())
14149 VecIn = ExtractedFromVec;
14150 } else if (VecIn != ExtractedFromVec)
14153 // Record the constant index.
14154 Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14157 assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14159 // Quit if not all elements are used.
14160 if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14163 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14166 static bool isValidFCMOVCondition(X86::CondCode CC) {
14182 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14183 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14184 TargetLowering::DAGCombinerInfo &DCI,
14185 const X86Subtarget *Subtarget) {
14186 DebugLoc DL = N->getDebugLoc();
14188 // If the flag operand isn't dead, don't touch this CMOV.
14189 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14192 SDValue FalseOp = N->getOperand(0);
14193 SDValue TrueOp = N->getOperand(1);
14194 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14195 SDValue Cond = N->getOperand(3);
14197 if (CC == X86::COND_E || CC == X86::COND_NE) {
14198 switch (Cond.getOpcode()) {
14202 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14203 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14204 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14210 Flags = checkBoolTestSetCCCombine(Cond, CC);
14211 if (Flags.getNode() &&
14212 // Extra check as FCMOV only supports a subset of X86 cond.
14213 (FalseOp.getValueType() != MVT::f80 || isValidFCMOVCondition(CC))) {
14214 SDValue Ops[] = { FalseOp, TrueOp,
14215 DAG.getConstant(CC, MVT::i8), Flags };
14216 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14217 Ops, array_lengthof(Ops));
14220 Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14221 if (Flags.getNode()) {
14222 SDValue Ops[] = { FalseOp, TrueOp,
14223 DAG.getConstant(CC, MVT::i8), Flags };
14224 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14225 Ops, array_lengthof(Ops));
14228 // If this is a select between two integer constants, try to do some
14229 // optimizations. Note that the operands are ordered the opposite of SELECT
14231 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14232 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14233 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14234 // larger than FalseC (the false value).
14235 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14236 CC = X86::GetOppositeBranchCondition(CC);
14237 std::swap(TrueC, FalseC);
14240 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14241 // This is efficient for any integer data type (including i8/i16) and
14243 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14244 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14245 DAG.getConstant(CC, MVT::i8), Cond);
14247 // Zero extend the condition if needed.
14248 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14250 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14251 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14252 DAG.getConstant(ShAmt, MVT::i8));
14253 if (N->getNumValues() == 2) // Dead flag value?
14254 return DCI.CombineTo(N, Cond, SDValue());
14258 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14259 // for any integer data type, including i8/i16.
14260 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14261 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14262 DAG.getConstant(CC, MVT::i8), Cond);
14264 // Zero extend the condition if needed.
14265 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14266 FalseC->getValueType(0), Cond);
14267 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14268 SDValue(FalseC, 0));
14270 if (N->getNumValues() == 2) // Dead flag value?
14271 return DCI.CombineTo(N, Cond, SDValue());
14275 // Optimize cases that will turn into an LEA instruction. This requires
14276 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14277 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14278 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14279 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14281 bool isFastMultiplier = false;
14283 switch ((unsigned char)Diff) {
14285 case 1: // result = add base, cond
14286 case 2: // result = lea base( , cond*2)
14287 case 3: // result = lea base(cond, cond*2)
14288 case 4: // result = lea base( , cond*4)
14289 case 5: // result = lea base(cond, cond*4)
14290 case 8: // result = lea base( , cond*8)
14291 case 9: // result = lea base(cond, cond*8)
14292 isFastMultiplier = true;
14297 if (isFastMultiplier) {
14298 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14299 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14300 DAG.getConstant(CC, MVT::i8), Cond);
14301 // Zero extend the condition if needed.
14302 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14304 // Scale the condition by the difference.
14306 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14307 DAG.getConstant(Diff, Cond.getValueType()));
14309 // Add the base if non-zero.
14310 if (FalseC->getAPIntValue() != 0)
14311 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14312 SDValue(FalseC, 0));
14313 if (N->getNumValues() == 2) // Dead flag value?
14314 return DCI.CombineTo(N, Cond, SDValue());
14324 /// PerformMulCombine - Optimize a single multiply with constant into two
14325 /// in order to implement it with two cheaper instructions, e.g.
14326 /// LEA + SHL, LEA + LEA.
14327 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14328 TargetLowering::DAGCombinerInfo &DCI) {
14329 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14332 EVT VT = N->getValueType(0);
14333 if (VT != MVT::i64)
14336 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14339 uint64_t MulAmt = C->getZExtValue();
14340 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14343 uint64_t MulAmt1 = 0;
14344 uint64_t MulAmt2 = 0;
14345 if ((MulAmt % 9) == 0) {
14347 MulAmt2 = MulAmt / 9;
14348 } else if ((MulAmt % 5) == 0) {
14350 MulAmt2 = MulAmt / 5;
14351 } else if ((MulAmt % 3) == 0) {
14353 MulAmt2 = MulAmt / 3;
14356 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14357 DebugLoc DL = N->getDebugLoc();
14359 if (isPowerOf2_64(MulAmt2) &&
14360 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14361 // If second multiplifer is pow2, issue it first. We want the multiply by
14362 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14364 std::swap(MulAmt1, MulAmt2);
14367 if (isPowerOf2_64(MulAmt1))
14368 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14369 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14371 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14372 DAG.getConstant(MulAmt1, VT));
14374 if (isPowerOf2_64(MulAmt2))
14375 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14376 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14378 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14379 DAG.getConstant(MulAmt2, VT));
14381 // Do not add new nodes to DAG combiner worklist.
14382 DCI.CombineTo(N, NewMul, false);
14387 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14388 SDValue N0 = N->getOperand(0);
14389 SDValue N1 = N->getOperand(1);
14390 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14391 EVT VT = N0.getValueType();
14393 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14394 // since the result of setcc_c is all zero's or all ones.
14395 if (VT.isInteger() && !VT.isVector() &&
14396 N1C && N0.getOpcode() == ISD::AND &&
14397 N0.getOperand(1).getOpcode() == ISD::Constant) {
14398 SDValue N00 = N0.getOperand(0);
14399 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14400 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14401 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14402 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14403 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14404 APInt ShAmt = N1C->getAPIntValue();
14405 Mask = Mask.shl(ShAmt);
14407 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14408 N00, DAG.getConstant(Mask, VT));
14413 // Hardware support for vector shifts is sparse which makes us scalarize the
14414 // vector operations in many cases. Also, on sandybridge ADD is faster than
14416 // (shl V, 1) -> add V,V
14417 if (isSplatVector(N1.getNode())) {
14418 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14419 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14420 // We shift all of the values by one. In many cases we do not have
14421 // hardware support for this operation. This is better expressed as an ADD
14423 if (N1C && (1 == N1C->getZExtValue())) {
14424 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14431 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14433 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14434 TargetLowering::DAGCombinerInfo &DCI,
14435 const X86Subtarget *Subtarget) {
14436 EVT VT = N->getValueType(0);
14437 if (N->getOpcode() == ISD::SHL) {
14438 SDValue V = PerformSHLCombine(N, DAG);
14439 if (V.getNode()) return V;
14442 // On X86 with SSE2 support, we can transform this to a vector shift if
14443 // all elements are shifted by the same amount. We can't do this in legalize
14444 // because the a constant vector is typically transformed to a constant pool
14445 // so we have no knowledge of the shift amount.
14446 if (!Subtarget->hasSSE2())
14449 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14450 (!Subtarget->hasAVX2() ||
14451 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14454 SDValue ShAmtOp = N->getOperand(1);
14455 EVT EltVT = VT.getVectorElementType();
14456 DebugLoc DL = N->getDebugLoc();
14457 SDValue BaseShAmt = SDValue();
14458 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14459 unsigned NumElts = VT.getVectorNumElements();
14461 for (; i != NumElts; ++i) {
14462 SDValue Arg = ShAmtOp.getOperand(i);
14463 if (Arg.getOpcode() == ISD::UNDEF) continue;
14467 // Handle the case where the build_vector is all undef
14468 // FIXME: Should DAG allow this?
14472 for (; i != NumElts; ++i) {
14473 SDValue Arg = ShAmtOp.getOperand(i);
14474 if (Arg.getOpcode() == ISD::UNDEF) continue;
14475 if (Arg != BaseShAmt) {
14479 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14480 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14481 SDValue InVec = ShAmtOp.getOperand(0);
14482 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14483 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14485 for (; i != NumElts; ++i) {
14486 SDValue Arg = InVec.getOperand(i);
14487 if (Arg.getOpcode() == ISD::UNDEF) continue;
14491 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14492 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14493 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14494 if (C->getZExtValue() == SplatIdx)
14495 BaseShAmt = InVec.getOperand(1);
14498 if (BaseShAmt.getNode() == 0) {
14499 // Don't create instructions with illegal types after legalize
14501 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14502 !DCI.isBeforeLegalize())
14505 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14506 DAG.getIntPtrConstant(0));
14511 // The shift amount is an i32.
14512 if (EltVT.bitsGT(MVT::i32))
14513 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14514 else if (EltVT.bitsLT(MVT::i32))
14515 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14517 // The shift amount is identical so we can do a vector shift.
14518 SDValue ValOp = N->getOperand(0);
14519 switch (N->getOpcode()) {
14521 llvm_unreachable("Unknown shift opcode!");
14523 switch (VT.getSimpleVT().SimpleTy) {
14524 default: return SDValue();
14531 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14534 switch (VT.getSimpleVT().SimpleTy) {
14535 default: return SDValue();
14540 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14543 switch (VT.getSimpleVT().SimpleTy) {
14544 default: return SDValue();
14551 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14557 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14558 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14559 // and friends. Likewise for OR -> CMPNEQSS.
14560 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14561 TargetLowering::DAGCombinerInfo &DCI,
14562 const X86Subtarget *Subtarget) {
14565 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14566 // we're requiring SSE2 for both.
14567 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14568 SDValue N0 = N->getOperand(0);
14569 SDValue N1 = N->getOperand(1);
14570 SDValue CMP0 = N0->getOperand(1);
14571 SDValue CMP1 = N1->getOperand(1);
14572 DebugLoc DL = N->getDebugLoc();
14574 // The SETCCs should both refer to the same CMP.
14575 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14578 SDValue CMP00 = CMP0->getOperand(0);
14579 SDValue CMP01 = CMP0->getOperand(1);
14580 EVT VT = CMP00.getValueType();
14582 if (VT == MVT::f32 || VT == MVT::f64) {
14583 bool ExpectingFlags = false;
14584 // Check for any users that want flags:
14585 for (SDNode::use_iterator UI = N->use_begin(),
14587 !ExpectingFlags && UI != UE; ++UI)
14588 switch (UI->getOpcode()) {
14593 ExpectingFlags = true;
14595 case ISD::CopyToReg:
14596 case ISD::SIGN_EXTEND:
14597 case ISD::ZERO_EXTEND:
14598 case ISD::ANY_EXTEND:
14602 if (!ExpectingFlags) {
14603 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14604 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14606 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14607 X86::CondCode tmp = cc0;
14612 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14613 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14614 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14615 X86ISD::NodeType NTOperator = is64BitFP ?
14616 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14617 // FIXME: need symbolic constants for these magic numbers.
14618 // See X86ATTInstPrinter.cpp:printSSECC().
14619 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14620 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14621 DAG.getConstant(x86cc, MVT::i8));
14622 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14624 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14625 DAG.getConstant(1, MVT::i32));
14626 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14627 return OneBitOfTruth;
14635 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14636 /// so it can be folded inside ANDNP.
14637 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14638 EVT VT = N->getValueType(0);
14640 // Match direct AllOnes for 128 and 256-bit vectors
14641 if (ISD::isBuildVectorAllOnes(N))
14644 // Look through a bit convert.
14645 if (N->getOpcode() == ISD::BITCAST)
14646 N = N->getOperand(0).getNode();
14648 // Sometimes the operand may come from a insert_subvector building a 256-bit
14650 if (VT.is256BitVector() &&
14651 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14652 SDValue V1 = N->getOperand(0);
14653 SDValue V2 = N->getOperand(1);
14655 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14656 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14657 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14658 ISD::isBuildVectorAllOnes(V2.getNode()))
14665 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14666 TargetLowering::DAGCombinerInfo &DCI,
14667 const X86Subtarget *Subtarget) {
14668 if (DCI.isBeforeLegalizeOps())
14671 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14675 EVT VT = N->getValueType(0);
14677 // Create ANDN, BLSI, and BLSR instructions
14678 // BLSI is X & (-X)
14679 // BLSR is X & (X-1)
14680 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14681 SDValue N0 = N->getOperand(0);
14682 SDValue N1 = N->getOperand(1);
14683 DebugLoc DL = N->getDebugLoc();
14685 // Check LHS for not
14686 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14687 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14688 // Check RHS for not
14689 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14690 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14692 // Check LHS for neg
14693 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14694 isZero(N0.getOperand(0)))
14695 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14697 // Check RHS for neg
14698 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14699 isZero(N1.getOperand(0)))
14700 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14702 // Check LHS for X-1
14703 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14704 isAllOnes(N0.getOperand(1)))
14705 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14707 // Check RHS for X-1
14708 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14709 isAllOnes(N1.getOperand(1)))
14710 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14715 // Want to form ANDNP nodes:
14716 // 1) In the hopes of then easily combining them with OR and AND nodes
14717 // to form PBLEND/PSIGN.
14718 // 2) To match ANDN packed intrinsics
14719 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14722 SDValue N0 = N->getOperand(0);
14723 SDValue N1 = N->getOperand(1);
14724 DebugLoc DL = N->getDebugLoc();
14726 // Check LHS for vnot
14727 if (N0.getOpcode() == ISD::XOR &&
14728 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14729 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14730 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14732 // Check RHS for vnot
14733 if (N1.getOpcode() == ISD::XOR &&
14734 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14735 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14736 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14741 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14742 TargetLowering::DAGCombinerInfo &DCI,
14743 const X86Subtarget *Subtarget) {
14744 if (DCI.isBeforeLegalizeOps())
14747 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14751 EVT VT = N->getValueType(0);
14753 SDValue N0 = N->getOperand(0);
14754 SDValue N1 = N->getOperand(1);
14756 // look for psign/blend
14757 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14758 if (!Subtarget->hasSSSE3() ||
14759 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14762 // Canonicalize pandn to RHS
14763 if (N0.getOpcode() == X86ISD::ANDNP)
14765 // or (and (m, y), (pandn m, x))
14766 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14767 SDValue Mask = N1.getOperand(0);
14768 SDValue X = N1.getOperand(1);
14770 if (N0.getOperand(0) == Mask)
14771 Y = N0.getOperand(1);
14772 if (N0.getOperand(1) == Mask)
14773 Y = N0.getOperand(0);
14775 // Check to see if the mask appeared in both the AND and ANDNP and
14779 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14780 // Look through mask bitcast.
14781 if (Mask.getOpcode() == ISD::BITCAST)
14782 Mask = Mask.getOperand(0);
14783 if (X.getOpcode() == ISD::BITCAST)
14784 X = X.getOperand(0);
14785 if (Y.getOpcode() == ISD::BITCAST)
14786 Y = Y.getOperand(0);
14788 EVT MaskVT = Mask.getValueType();
14790 // Validate that the Mask operand is a vector sra node.
14791 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14792 // there is no psrai.b
14793 if (Mask.getOpcode() != X86ISD::VSRAI)
14796 // Check that the SRA is all signbits.
14797 SDValue SraC = Mask.getOperand(1);
14798 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14799 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14800 if ((SraAmt + 1) != EltBits)
14803 DebugLoc DL = N->getDebugLoc();
14805 // Now we know we at least have a plendvb with the mask val. See if
14806 // we can form a psignb/w/d.
14807 // psign = x.type == y.type == mask.type && y = sub(0, x);
14808 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14809 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14810 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14811 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14812 "Unsupported VT for PSIGN");
14813 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14814 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14816 // PBLENDVB only available on SSE 4.1
14817 if (!Subtarget->hasSSE41())
14820 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14822 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14823 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14824 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14825 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14826 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14830 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14833 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14834 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14836 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14838 if (!N0.hasOneUse() || !N1.hasOneUse())
14841 SDValue ShAmt0 = N0.getOperand(1);
14842 if (ShAmt0.getValueType() != MVT::i8)
14844 SDValue ShAmt1 = N1.getOperand(1);
14845 if (ShAmt1.getValueType() != MVT::i8)
14847 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14848 ShAmt0 = ShAmt0.getOperand(0);
14849 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14850 ShAmt1 = ShAmt1.getOperand(0);
14852 DebugLoc DL = N->getDebugLoc();
14853 unsigned Opc = X86ISD::SHLD;
14854 SDValue Op0 = N0.getOperand(0);
14855 SDValue Op1 = N1.getOperand(0);
14856 if (ShAmt0.getOpcode() == ISD::SUB) {
14857 Opc = X86ISD::SHRD;
14858 std::swap(Op0, Op1);
14859 std::swap(ShAmt0, ShAmt1);
14862 unsigned Bits = VT.getSizeInBits();
14863 if (ShAmt1.getOpcode() == ISD::SUB) {
14864 SDValue Sum = ShAmt1.getOperand(0);
14865 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14866 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14867 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14868 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14869 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14870 return DAG.getNode(Opc, DL, VT,
14872 DAG.getNode(ISD::TRUNCATE, DL,
14875 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14876 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14878 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14879 return DAG.getNode(Opc, DL, VT,
14880 N0.getOperand(0), N1.getOperand(0),
14881 DAG.getNode(ISD::TRUNCATE, DL,
14888 // Generate NEG and CMOV for integer abs.
14889 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14890 EVT VT = N->getValueType(0);
14892 // Since X86 does not have CMOV for 8-bit integer, we don't convert
14893 // 8-bit integer abs to NEG and CMOV.
14894 if (VT.isInteger() && VT.getSizeInBits() == 8)
14897 SDValue N0 = N->getOperand(0);
14898 SDValue N1 = N->getOperand(1);
14899 DebugLoc DL = N->getDebugLoc();
14901 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14902 // and change it to SUB and CMOV.
14903 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14904 N0.getOpcode() == ISD::ADD &&
14905 N0.getOperand(1) == N1 &&
14906 N1.getOpcode() == ISD::SRA &&
14907 N1.getOperand(0) == N0.getOperand(0))
14908 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14909 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14910 // Generate SUB & CMOV.
14911 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14912 DAG.getConstant(0, VT), N0.getOperand(0));
14914 SDValue Ops[] = { N0.getOperand(0), Neg,
14915 DAG.getConstant(X86::COND_GE, MVT::i8),
14916 SDValue(Neg.getNode(), 1) };
14917 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14918 Ops, array_lengthof(Ops));
14923 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14924 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14925 TargetLowering::DAGCombinerInfo &DCI,
14926 const X86Subtarget *Subtarget) {
14927 if (DCI.isBeforeLegalizeOps())
14930 if (Subtarget->hasCMov()) {
14931 SDValue RV = performIntegerAbsCombine(N, DAG);
14936 // Try forming BMI if it is available.
14937 if (!Subtarget->hasBMI())
14940 EVT VT = N->getValueType(0);
14942 if (VT != MVT::i32 && VT != MVT::i64)
14945 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14947 // Create BLSMSK instructions by finding X ^ (X-1)
14948 SDValue N0 = N->getOperand(0);
14949 SDValue N1 = N->getOperand(1);
14950 DebugLoc DL = N->getDebugLoc();
14952 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14953 isAllOnes(N0.getOperand(1)))
14954 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14956 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14957 isAllOnes(N1.getOperand(1)))
14958 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14963 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14964 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14965 TargetLowering::DAGCombinerInfo &DCI,
14966 const X86Subtarget *Subtarget) {
14967 LoadSDNode *Ld = cast<LoadSDNode>(N);
14968 EVT RegVT = Ld->getValueType(0);
14969 EVT MemVT = Ld->getMemoryVT();
14970 DebugLoc dl = Ld->getDebugLoc();
14971 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14973 ISD::LoadExtType Ext = Ld->getExtensionType();
14975 // If this is a vector EXT Load then attempt to optimize it using a
14976 // shuffle. We need SSE4 for the shuffles.
14977 // TODO: It is possible to support ZExt by zeroing the undef values
14978 // during the shuffle phase or after the shuffle.
14979 if (RegVT.isVector() && RegVT.isInteger() &&
14980 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14981 assert(MemVT != RegVT && "Cannot extend to the same type");
14982 assert(MemVT.isVector() && "Must load a vector from memory");
14984 unsigned NumElems = RegVT.getVectorNumElements();
14985 unsigned RegSz = RegVT.getSizeInBits();
14986 unsigned MemSz = MemVT.getSizeInBits();
14987 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14989 // All sizes must be a power of two.
14990 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14993 // Attempt to load the original value using scalar loads.
14994 // Find the largest scalar type that divides the total loaded size.
14995 MVT SclrLoadTy = MVT::i8;
14996 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14997 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14998 MVT Tp = (MVT::SimpleValueType)tp;
14999 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15004 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15005 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15007 SclrLoadTy = MVT::f64;
15009 // Calculate the number of scalar loads that we need to perform
15010 // in order to load our vector from memory.
15011 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15013 // Represent our vector as a sequence of elements which are the
15014 // largest scalar that we can load.
15015 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15016 RegSz/SclrLoadTy.getSizeInBits());
15018 // Represent the data using the same element type that is stored in
15019 // memory. In practice, we ''widen'' MemVT.
15020 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15021 RegSz/MemVT.getScalarType().getSizeInBits());
15023 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15024 "Invalid vector type");
15026 // We can't shuffle using an illegal type.
15027 if (!TLI.isTypeLegal(WideVecVT))
15030 SmallVector<SDValue, 8> Chains;
15031 SDValue Ptr = Ld->getBasePtr();
15032 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15033 TLI.getPointerTy());
15034 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15036 for (unsigned i = 0; i < NumLoads; ++i) {
15037 // Perform a single load.
15038 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15039 Ptr, Ld->getPointerInfo(),
15040 Ld->isVolatile(), Ld->isNonTemporal(),
15041 Ld->isInvariant(), Ld->getAlignment());
15042 Chains.push_back(ScalarLoad.getValue(1));
15043 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15044 // another round of DAGCombining.
15046 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15048 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15049 ScalarLoad, DAG.getIntPtrConstant(i));
15051 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15054 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15057 // Bitcast the loaded value to a vector of the original element type, in
15058 // the size of the target vector type.
15059 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15060 unsigned SizeRatio = RegSz/MemSz;
15062 // Redistribute the loaded elements into the different locations.
15063 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15064 for (unsigned i = 0; i != NumElems; ++i)
15065 ShuffleVec[i*SizeRatio] = i;
15067 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15068 DAG.getUNDEF(WideVecVT),
15071 // Bitcast to the requested type.
15072 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15073 // Replace the original load with the new sequence
15074 // and return the new chain.
15075 return DCI.CombineTo(N, Shuff, TF, true);
15081 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15082 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15083 const X86Subtarget *Subtarget) {
15084 StoreSDNode *St = cast<StoreSDNode>(N);
15085 EVT VT = St->getValue().getValueType();
15086 EVT StVT = St->getMemoryVT();
15087 DebugLoc dl = St->getDebugLoc();
15088 SDValue StoredVal = St->getOperand(1);
15089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15091 // If we are saving a concatenation of two XMM registers, perform two stores.
15092 // On Sandy Bridge, 256-bit memory operations are executed by two
15093 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15094 // memory operation.
15095 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15096 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15097 StoredVal.getNumOperands() == 2) {
15098 SDValue Value0 = StoredVal.getOperand(0);
15099 SDValue Value1 = StoredVal.getOperand(1);
15101 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15102 SDValue Ptr0 = St->getBasePtr();
15103 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15105 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15106 St->getPointerInfo(), St->isVolatile(),
15107 St->isNonTemporal(), St->getAlignment());
15108 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15109 St->getPointerInfo(), St->isVolatile(),
15110 St->isNonTemporal(), St->getAlignment());
15111 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15114 // Optimize trunc store (of multiple scalars) to shuffle and store.
15115 // First, pack all of the elements in one place. Next, store to memory
15116 // in fewer chunks.
15117 if (St->isTruncatingStore() && VT.isVector()) {
15118 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15119 unsigned NumElems = VT.getVectorNumElements();
15120 assert(StVT != VT && "Cannot truncate to the same type");
15121 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15122 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15124 // From, To sizes and ElemCount must be pow of two
15125 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15126 // We are going to use the original vector elt for storing.
15127 // Accumulated smaller vector elements must be a multiple of the store size.
15128 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15130 unsigned SizeRatio = FromSz / ToSz;
15132 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15134 // Create a type on which we perform the shuffle
15135 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15136 StVT.getScalarType(), NumElems*SizeRatio);
15138 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15140 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15141 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15142 for (unsigned i = 0; i != NumElems; ++i)
15143 ShuffleVec[i] = i * SizeRatio;
15145 // Can't shuffle using an illegal type.
15146 if (!TLI.isTypeLegal(WideVecVT))
15149 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15150 DAG.getUNDEF(WideVecVT),
15152 // At this point all of the data is stored at the bottom of the
15153 // register. We now need to save it to mem.
15155 // Find the largest store unit
15156 MVT StoreType = MVT::i8;
15157 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15158 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15159 MVT Tp = (MVT::SimpleValueType)tp;
15160 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15164 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15165 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15166 (64 <= NumElems * ToSz))
15167 StoreType = MVT::f64;
15169 // Bitcast the original vector into a vector of store-size units
15170 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15171 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15172 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15173 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15174 SmallVector<SDValue, 8> Chains;
15175 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15176 TLI.getPointerTy());
15177 SDValue Ptr = St->getBasePtr();
15179 // Perform one or more big stores into memory.
15180 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15181 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15182 StoreType, ShuffWide,
15183 DAG.getIntPtrConstant(i));
15184 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15185 St->getPointerInfo(), St->isVolatile(),
15186 St->isNonTemporal(), St->getAlignment());
15187 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15188 Chains.push_back(Ch);
15191 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15196 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15197 // the FP state in cases where an emms may be missing.
15198 // A preferable solution to the general problem is to figure out the right
15199 // places to insert EMMS. This qualifies as a quick hack.
15201 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15202 if (VT.getSizeInBits() != 64)
15205 const Function *F = DAG.getMachineFunction().getFunction();
15206 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15207 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15208 && Subtarget->hasSSE2();
15209 if ((VT.isVector() ||
15210 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15211 isa<LoadSDNode>(St->getValue()) &&
15212 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15213 St->getChain().hasOneUse() && !St->isVolatile()) {
15214 SDNode* LdVal = St->getValue().getNode();
15215 LoadSDNode *Ld = 0;
15216 int TokenFactorIndex = -1;
15217 SmallVector<SDValue, 8> Ops;
15218 SDNode* ChainVal = St->getChain().getNode();
15219 // Must be a store of a load. We currently handle two cases: the load
15220 // is a direct child, and it's under an intervening TokenFactor. It is
15221 // possible to dig deeper under nested TokenFactors.
15222 if (ChainVal == LdVal)
15223 Ld = cast<LoadSDNode>(St->getChain());
15224 else if (St->getValue().hasOneUse() &&
15225 ChainVal->getOpcode() == ISD::TokenFactor) {
15226 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15227 if (ChainVal->getOperand(i).getNode() == LdVal) {
15228 TokenFactorIndex = i;
15229 Ld = cast<LoadSDNode>(St->getValue());
15231 Ops.push_back(ChainVal->getOperand(i));
15235 if (!Ld || !ISD::isNormalLoad(Ld))
15238 // If this is not the MMX case, i.e. we are just turning i64 load/store
15239 // into f64 load/store, avoid the transformation if there are multiple
15240 // uses of the loaded value.
15241 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15244 DebugLoc LdDL = Ld->getDebugLoc();
15245 DebugLoc StDL = N->getDebugLoc();
15246 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15247 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15249 if (Subtarget->is64Bit() || F64IsLegal) {
15250 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15251 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15252 Ld->getPointerInfo(), Ld->isVolatile(),
15253 Ld->isNonTemporal(), Ld->isInvariant(),
15254 Ld->getAlignment());
15255 SDValue NewChain = NewLd.getValue(1);
15256 if (TokenFactorIndex != -1) {
15257 Ops.push_back(NewChain);
15258 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15261 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15262 St->getPointerInfo(),
15263 St->isVolatile(), St->isNonTemporal(),
15264 St->getAlignment());
15267 // Otherwise, lower to two pairs of 32-bit loads / stores.
15268 SDValue LoAddr = Ld->getBasePtr();
15269 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15270 DAG.getConstant(4, MVT::i32));
15272 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15273 Ld->getPointerInfo(),
15274 Ld->isVolatile(), Ld->isNonTemporal(),
15275 Ld->isInvariant(), Ld->getAlignment());
15276 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15277 Ld->getPointerInfo().getWithOffset(4),
15278 Ld->isVolatile(), Ld->isNonTemporal(),
15280 MinAlign(Ld->getAlignment(), 4));
15282 SDValue NewChain = LoLd.getValue(1);
15283 if (TokenFactorIndex != -1) {
15284 Ops.push_back(LoLd);
15285 Ops.push_back(HiLd);
15286 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15290 LoAddr = St->getBasePtr();
15291 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15292 DAG.getConstant(4, MVT::i32));
15294 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15295 St->getPointerInfo(),
15296 St->isVolatile(), St->isNonTemporal(),
15297 St->getAlignment());
15298 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15299 St->getPointerInfo().getWithOffset(4),
15301 St->isNonTemporal(),
15302 MinAlign(St->getAlignment(), 4));
15303 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15308 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15309 /// and return the operands for the horizontal operation in LHS and RHS. A
15310 /// horizontal operation performs the binary operation on successive elements
15311 /// of its first operand, then on successive elements of its second operand,
15312 /// returning the resulting values in a vector. For example, if
15313 /// A = < float a0, float a1, float a2, float a3 >
15315 /// B = < float b0, float b1, float b2, float b3 >
15316 /// then the result of doing a horizontal operation on A and B is
15317 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15318 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15319 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15320 /// set to A, RHS to B, and the routine returns 'true'.
15321 /// Note that the binary operation should have the property that if one of the
15322 /// operands is UNDEF then the result is UNDEF.
15323 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15324 // Look for the following pattern: if
15325 // A = < float a0, float a1, float a2, float a3 >
15326 // B = < float b0, float b1, float b2, float b3 >
15328 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15329 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15330 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15331 // which is A horizontal-op B.
15333 // At least one of the operands should be a vector shuffle.
15334 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15335 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15338 EVT VT = LHS.getValueType();
15340 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15341 "Unsupported vector type for horizontal add/sub");
15343 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15344 // operate independently on 128-bit lanes.
15345 unsigned NumElts = VT.getVectorNumElements();
15346 unsigned NumLanes = VT.getSizeInBits()/128;
15347 unsigned NumLaneElts = NumElts / NumLanes;
15348 assert((NumLaneElts % 2 == 0) &&
15349 "Vector type should have an even number of elements in each lane");
15350 unsigned HalfLaneElts = NumLaneElts/2;
15352 // View LHS in the form
15353 // LHS = VECTOR_SHUFFLE A, B, LMask
15354 // If LHS is not a shuffle then pretend it is the shuffle
15355 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15356 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15359 SmallVector<int, 16> LMask(NumElts);
15360 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15361 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15362 A = LHS.getOperand(0);
15363 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15364 B = LHS.getOperand(1);
15365 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15366 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15368 if (LHS.getOpcode() != ISD::UNDEF)
15370 for (unsigned i = 0; i != NumElts; ++i)
15374 // Likewise, view RHS in the form
15375 // RHS = VECTOR_SHUFFLE C, D, RMask
15377 SmallVector<int, 16> RMask(NumElts);
15378 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15379 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15380 C = RHS.getOperand(0);
15381 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15382 D = RHS.getOperand(1);
15383 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15384 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15386 if (RHS.getOpcode() != ISD::UNDEF)
15388 for (unsigned i = 0; i != NumElts; ++i)
15392 // Check that the shuffles are both shuffling the same vectors.
15393 if (!(A == C && B == D) && !(A == D && B == C))
15396 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15397 if (!A.getNode() && !B.getNode())
15400 // If A and B occur in reverse order in RHS, then "swap" them (which means
15401 // rewriting the mask).
15403 CommuteVectorShuffleMask(RMask, NumElts);
15405 // At this point LHS and RHS are equivalent to
15406 // LHS = VECTOR_SHUFFLE A, B, LMask
15407 // RHS = VECTOR_SHUFFLE A, B, RMask
15408 // Check that the masks correspond to performing a horizontal operation.
15409 for (unsigned i = 0; i != NumElts; ++i) {
15410 int LIdx = LMask[i], RIdx = RMask[i];
15412 // Ignore any UNDEF components.
15413 if (LIdx < 0 || RIdx < 0 ||
15414 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15415 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15418 // Check that successive elements are being operated on. If not, this is
15419 // not a horizontal operation.
15420 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15421 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15422 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15423 if (!(LIdx == Index && RIdx == Index + 1) &&
15424 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15428 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15429 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15433 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15434 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15435 const X86Subtarget *Subtarget) {
15436 EVT VT = N->getValueType(0);
15437 SDValue LHS = N->getOperand(0);
15438 SDValue RHS = N->getOperand(1);
15440 // Try to synthesize horizontal adds from adds of shuffles.
15441 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15442 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15443 isHorizontalBinOp(LHS, RHS, true))
15444 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15448 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15449 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15450 const X86Subtarget *Subtarget) {
15451 EVT VT = N->getValueType(0);
15452 SDValue LHS = N->getOperand(0);
15453 SDValue RHS = N->getOperand(1);
15455 // Try to synthesize horizontal subs from subs of shuffles.
15456 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15457 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15458 isHorizontalBinOp(LHS, RHS, false))
15459 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15463 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15464 /// X86ISD::FXOR nodes.
15465 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15466 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15467 // F[X]OR(0.0, x) -> x
15468 // F[X]OR(x, 0.0) -> x
15469 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15470 if (C->getValueAPF().isPosZero())
15471 return N->getOperand(1);
15472 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15473 if (C->getValueAPF().isPosZero())
15474 return N->getOperand(0);
15478 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15479 /// X86ISD::FMAX nodes.
15480 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15481 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15483 // Only perform optimizations if UnsafeMath is used.
15484 if (!DAG.getTarget().Options.UnsafeFPMath)
15487 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15488 // into FMINC and MMAXC, which are Commutative operations.
15489 unsigned NewOp = 0;
15490 switch (N->getOpcode()) {
15491 default: llvm_unreachable("unknown opcode");
15492 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15493 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15496 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15497 N->getOperand(0), N->getOperand(1));
15501 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15502 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15503 // FAND(0.0, x) -> 0.0
15504 // FAND(x, 0.0) -> 0.0
15505 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15506 if (C->getValueAPF().isPosZero())
15507 return N->getOperand(0);
15508 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15509 if (C->getValueAPF().isPosZero())
15510 return N->getOperand(1);
15514 static SDValue PerformBTCombine(SDNode *N,
15516 TargetLowering::DAGCombinerInfo &DCI) {
15517 // BT ignores high bits in the bit index operand.
15518 SDValue Op1 = N->getOperand(1);
15519 if (Op1.hasOneUse()) {
15520 unsigned BitWidth = Op1.getValueSizeInBits();
15521 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15522 APInt KnownZero, KnownOne;
15523 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15524 !DCI.isBeforeLegalizeOps());
15525 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15526 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15527 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15528 DCI.CommitTargetLoweringOpt(TLO);
15533 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15534 SDValue Op = N->getOperand(0);
15535 if (Op.getOpcode() == ISD::BITCAST)
15536 Op = Op.getOperand(0);
15537 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15538 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15539 VT.getVectorElementType().getSizeInBits() ==
15540 OpVT.getVectorElementType().getSizeInBits()) {
15541 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15546 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15547 TargetLowering::DAGCombinerInfo &DCI,
15548 const X86Subtarget *Subtarget) {
15549 if (!DCI.isBeforeLegalizeOps())
15552 if (!Subtarget->hasAVX())
15555 EVT VT = N->getValueType(0);
15556 SDValue Op = N->getOperand(0);
15557 EVT OpVT = Op.getValueType();
15558 DebugLoc dl = N->getDebugLoc();
15560 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15561 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15563 if (Subtarget->hasAVX2())
15564 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15566 // Optimize vectors in AVX mode
15567 // Sign extend v8i16 to v8i32 and
15570 // Divide input vector into two parts
15571 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15572 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15573 // concat the vectors to original VT
15575 unsigned NumElems = OpVT.getVectorNumElements();
15576 SDValue Undef = DAG.getUNDEF(OpVT);
15578 SmallVector<int,8> ShufMask1(NumElems, -1);
15579 for (unsigned i = 0; i != NumElems/2; ++i)
15582 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15584 SmallVector<int,8> ShufMask2(NumElems, -1);
15585 for (unsigned i = 0; i != NumElems/2; ++i)
15586 ShufMask2[i] = i + NumElems/2;
15588 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15590 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15591 VT.getVectorNumElements()/2);
15593 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15594 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15596 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15601 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15602 const X86Subtarget* Subtarget) {
15603 DebugLoc dl = N->getDebugLoc();
15604 EVT VT = N->getValueType(0);
15606 // Let legalize expand this if it isn't a legal type yet.
15607 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15610 EVT ScalarVT = VT.getScalarType();
15611 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15612 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15615 SDValue A = N->getOperand(0);
15616 SDValue B = N->getOperand(1);
15617 SDValue C = N->getOperand(2);
15619 bool NegA = (A.getOpcode() == ISD::FNEG);
15620 bool NegB = (B.getOpcode() == ISD::FNEG);
15621 bool NegC = (C.getOpcode() == ISD::FNEG);
15623 // Negative multiplication when NegA xor NegB
15624 bool NegMul = (NegA != NegB);
15626 A = A.getOperand(0);
15628 B = B.getOperand(0);
15630 C = C.getOperand(0);
15634 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15636 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15638 return DAG.getNode(Opcode, dl, VT, A, B, C);
15641 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15642 TargetLowering::DAGCombinerInfo &DCI,
15643 const X86Subtarget *Subtarget) {
15644 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15645 // (and (i32 x86isd::setcc_carry), 1)
15646 // This eliminates the zext. This transformation is necessary because
15647 // ISD::SETCC is always legalized to i8.
15648 DebugLoc dl = N->getDebugLoc();
15649 SDValue N0 = N->getOperand(0);
15650 EVT VT = N->getValueType(0);
15651 EVT OpVT = N0.getValueType();
15653 if (N0.getOpcode() == ISD::AND &&
15655 N0.getOperand(0).hasOneUse()) {
15656 SDValue N00 = N0.getOperand(0);
15657 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15659 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15660 if (!C || C->getZExtValue() != 1)
15662 return DAG.getNode(ISD::AND, dl, VT,
15663 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15664 N00.getOperand(0), N00.getOperand(1)),
15665 DAG.getConstant(1, VT));
15668 // Optimize vectors in AVX mode:
15671 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15672 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15673 // Concat upper and lower parts.
15676 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15677 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15678 // Concat upper and lower parts.
15680 if (!DCI.isBeforeLegalizeOps())
15683 if (!Subtarget->hasAVX())
15686 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15687 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15689 if (Subtarget->hasAVX2())
15690 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15692 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15693 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15694 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15696 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15697 VT.getVectorNumElements()/2);
15699 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15700 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15702 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15708 // Optimize x == -y --> x+y == 0
15709 // x != -y --> x+y != 0
15710 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15711 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15712 SDValue LHS = N->getOperand(0);
15713 SDValue RHS = N->getOperand(1);
15715 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15716 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15717 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15718 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15719 LHS.getValueType(), RHS, LHS.getOperand(1));
15720 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15721 addV, DAG.getConstant(0, addV.getValueType()), CC);
15723 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15725 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15726 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15727 RHS.getValueType(), LHS, RHS.getOperand(1));
15728 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15729 addV, DAG.getConstant(0, addV.getValueType()), CC);
15734 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15735 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15736 TargetLowering::DAGCombinerInfo &DCI,
15737 const X86Subtarget *Subtarget) {
15738 DebugLoc DL = N->getDebugLoc();
15739 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15740 SDValue EFLAGS = N->getOperand(1);
15742 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15743 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15745 if (CC == X86::COND_B)
15746 return DAG.getNode(ISD::AND, DL, MVT::i8,
15747 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15748 DAG.getConstant(CC, MVT::i8), EFLAGS),
15749 DAG.getConstant(1, MVT::i8));
15753 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15754 if (Flags.getNode()) {
15755 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15756 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15759 Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15760 if (Flags.getNode()) {
15761 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15762 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15768 // Optimize branch condition evaluation.
15770 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15771 TargetLowering::DAGCombinerInfo &DCI,
15772 const X86Subtarget *Subtarget) {
15773 DebugLoc DL = N->getDebugLoc();
15774 SDValue Chain = N->getOperand(0);
15775 SDValue Dest = N->getOperand(1);
15776 SDValue EFLAGS = N->getOperand(3);
15777 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15781 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15782 if (Flags.getNode()) {
15783 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15784 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15788 Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15789 if (Flags.getNode()) {
15790 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15791 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15798 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15799 SDValue Op0 = N->getOperand(0);
15800 EVT InVT = Op0->getValueType(0);
15802 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15803 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15804 DebugLoc dl = N->getDebugLoc();
15805 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15806 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15807 // Notice that we use SINT_TO_FP because we know that the high bits
15808 // are zero and SINT_TO_FP is better supported by the hardware.
15809 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15815 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15816 const X86TargetLowering *XTLI) {
15817 SDValue Op0 = N->getOperand(0);
15818 EVT InVT = Op0->getValueType(0);
15820 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15821 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15822 DebugLoc dl = N->getDebugLoc();
15823 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15824 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15825 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15828 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15829 // a 32-bit target where SSE doesn't support i64->FP operations.
15830 if (Op0.getOpcode() == ISD::LOAD) {
15831 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15832 EVT VT = Ld->getValueType(0);
15833 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15834 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15835 !XTLI->getSubtarget()->is64Bit() &&
15836 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15837 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15838 Ld->getChain(), Op0, DAG);
15839 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15846 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15847 EVT VT = N->getValueType(0);
15849 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15850 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15851 DebugLoc dl = N->getDebugLoc();
15852 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15853 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15854 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15860 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15861 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15862 X86TargetLowering::DAGCombinerInfo &DCI) {
15863 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15864 // the result is either zero or one (depending on the input carry bit).
15865 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15866 if (X86::isZeroNode(N->getOperand(0)) &&
15867 X86::isZeroNode(N->getOperand(1)) &&
15868 // We don't have a good way to replace an EFLAGS use, so only do this when
15870 SDValue(N, 1).use_empty()) {
15871 DebugLoc DL = N->getDebugLoc();
15872 EVT VT = N->getValueType(0);
15873 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15874 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15875 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15876 DAG.getConstant(X86::COND_B,MVT::i8),
15878 DAG.getConstant(1, VT));
15879 return DCI.CombineTo(N, Res1, CarryOut);
15885 // fold (add Y, (sete X, 0)) -> adc 0, Y
15886 // (add Y, (setne X, 0)) -> sbb -1, Y
15887 // (sub (sete X, 0), Y) -> sbb 0, Y
15888 // (sub (setne X, 0), Y) -> adc -1, Y
15889 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15890 DebugLoc DL = N->getDebugLoc();
15892 // Look through ZExts.
15893 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15894 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15897 SDValue SetCC = Ext.getOperand(0);
15898 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15901 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15902 if (CC != X86::COND_E && CC != X86::COND_NE)
15905 SDValue Cmp = SetCC.getOperand(1);
15906 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15907 !X86::isZeroNode(Cmp.getOperand(1)) ||
15908 !Cmp.getOperand(0).getValueType().isInteger())
15911 SDValue CmpOp0 = Cmp.getOperand(0);
15912 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15913 DAG.getConstant(1, CmpOp0.getValueType()));
15915 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15916 if (CC == X86::COND_NE)
15917 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15918 DL, OtherVal.getValueType(), OtherVal,
15919 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15920 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15921 DL, OtherVal.getValueType(), OtherVal,
15922 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15925 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15926 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15927 const X86Subtarget *Subtarget) {
15928 EVT VT = N->getValueType(0);
15929 SDValue Op0 = N->getOperand(0);
15930 SDValue Op1 = N->getOperand(1);
15932 // Try to synthesize horizontal adds from adds of shuffles.
15933 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15934 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15935 isHorizontalBinOp(Op0, Op1, true))
15936 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15938 return OptimizeConditionalInDecrement(N, DAG);
15941 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15942 const X86Subtarget *Subtarget) {
15943 SDValue Op0 = N->getOperand(0);
15944 SDValue Op1 = N->getOperand(1);
15946 // X86 can't encode an immediate LHS of a sub. See if we can push the
15947 // negation into a preceding instruction.
15948 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15949 // If the RHS of the sub is a XOR with one use and a constant, invert the
15950 // immediate. Then add one to the LHS of the sub so we can turn
15951 // X-Y -> X+~Y+1, saving one register.
15952 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15953 isa<ConstantSDNode>(Op1.getOperand(1))) {
15954 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15955 EVT VT = Op0.getValueType();
15956 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15958 DAG.getConstant(~XorC, VT));
15959 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15960 DAG.getConstant(C->getAPIntValue()+1, VT));
15964 // Try to synthesize horizontal adds from adds of shuffles.
15965 EVT VT = N->getValueType(0);
15966 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15967 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15968 isHorizontalBinOp(Op0, Op1, true))
15969 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15971 return OptimizeConditionalInDecrement(N, DAG);
15974 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15975 DAGCombinerInfo &DCI) const {
15976 SelectionDAG &DAG = DCI.DAG;
15977 switch (N->getOpcode()) {
15979 case ISD::EXTRACT_VECTOR_ELT:
15980 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15982 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15983 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
15984 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
15985 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
15986 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
15987 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
15990 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
15991 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
15992 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
15993 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
15994 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
15995 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
15996 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
15997 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
15998 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
15999 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16000 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16002 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16004 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16005 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16006 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16007 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16008 case ISD::ANY_EXTEND:
16009 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16010 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16011 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI);
16012 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16013 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16014 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16015 case X86ISD::SHUFP: // Handle all target specific shuffles
16016 case X86ISD::PALIGN:
16017 case X86ISD::UNPCKH:
16018 case X86ISD::UNPCKL:
16019 case X86ISD::MOVHLPS:
16020 case X86ISD::MOVLHPS:
16021 case X86ISD::PSHUFD:
16022 case X86ISD::PSHUFHW:
16023 case X86ISD::PSHUFLW:
16024 case X86ISD::MOVSS:
16025 case X86ISD::MOVSD:
16026 case X86ISD::VPERMILP:
16027 case X86ISD::VPERM2X128:
16028 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16029 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16035 /// isTypeDesirableForOp - Return true if the target has native support for
16036 /// the specified value type and it is 'desirable' to use the type for the
16037 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16038 /// instruction encodings are longer and some i16 instructions are slow.
16039 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16040 if (!isTypeLegal(VT))
16042 if (VT != MVT::i16)
16049 case ISD::SIGN_EXTEND:
16050 case ISD::ZERO_EXTEND:
16051 case ISD::ANY_EXTEND:
16064 /// IsDesirableToPromoteOp - This method query the target whether it is
16065 /// beneficial for dag combiner to promote the specified node. If true, it
16066 /// should return the desired promotion type by reference.
16067 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16068 EVT VT = Op.getValueType();
16069 if (VT != MVT::i16)
16072 bool Promote = false;
16073 bool Commute = false;
16074 switch (Op.getOpcode()) {
16077 LoadSDNode *LD = cast<LoadSDNode>(Op);
16078 // If the non-extending load has a single use and it's not live out, then it
16079 // might be folded.
16080 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16081 Op.hasOneUse()*/) {
16082 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16083 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16084 // The only case where we'd want to promote LOAD (rather then it being
16085 // promoted as an operand is when it's only use is liveout.
16086 if (UI->getOpcode() != ISD::CopyToReg)
16093 case ISD::SIGN_EXTEND:
16094 case ISD::ZERO_EXTEND:
16095 case ISD::ANY_EXTEND:
16100 SDValue N0 = Op.getOperand(0);
16101 // Look out for (store (shl (load), x)).
16102 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16115 SDValue N0 = Op.getOperand(0);
16116 SDValue N1 = Op.getOperand(1);
16117 if (!Commute && MayFoldLoad(N1))
16119 // Avoid disabling potential load folding opportunities.
16120 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16122 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16132 //===----------------------------------------------------------------------===//
16133 // X86 Inline Assembly Support
16134 //===----------------------------------------------------------------------===//
16137 // Helper to match a string separated by whitespace.
16138 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16139 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16141 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16142 StringRef piece(*args[i]);
16143 if (!s.startswith(piece)) // Check if the piece matches.
16146 s = s.substr(piece.size());
16147 StringRef::size_type pos = s.find_first_not_of(" \t");
16148 if (pos == 0) // We matched a prefix.
16156 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16159 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16160 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16162 std::string AsmStr = IA->getAsmString();
16164 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16165 if (!Ty || Ty->getBitWidth() % 16 != 0)
16168 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16169 SmallVector<StringRef, 4> AsmPieces;
16170 SplitString(AsmStr, AsmPieces, ";\n");
16172 switch (AsmPieces.size()) {
16173 default: return false;
16175 // FIXME: this should verify that we are targeting a 486 or better. If not,
16176 // we will turn this bswap into something that will be lowered to logical
16177 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16178 // lower so don't worry about this.
16180 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16181 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16182 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16183 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16184 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16185 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16186 // No need to check constraints, nothing other than the equivalent of
16187 // "=r,0" would be valid here.
16188 return IntrinsicLowering::LowerToByteSwap(CI);
16191 // rorw $$8, ${0:w} --> llvm.bswap.i16
16192 if (CI->getType()->isIntegerTy(16) &&
16193 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16194 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16195 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16197 const std::string &ConstraintsStr = IA->getConstraintString();
16198 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16199 std::sort(AsmPieces.begin(), AsmPieces.end());
16200 if (AsmPieces.size() == 4 &&
16201 AsmPieces[0] == "~{cc}" &&
16202 AsmPieces[1] == "~{dirflag}" &&
16203 AsmPieces[2] == "~{flags}" &&
16204 AsmPieces[3] == "~{fpsr}")
16205 return IntrinsicLowering::LowerToByteSwap(CI);
16209 if (CI->getType()->isIntegerTy(32) &&
16210 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16211 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16212 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16213 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16215 const std::string &ConstraintsStr = IA->getConstraintString();
16216 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16217 std::sort(AsmPieces.begin(), AsmPieces.end());
16218 if (AsmPieces.size() == 4 &&
16219 AsmPieces[0] == "~{cc}" &&
16220 AsmPieces[1] == "~{dirflag}" &&
16221 AsmPieces[2] == "~{flags}" &&
16222 AsmPieces[3] == "~{fpsr}")
16223 return IntrinsicLowering::LowerToByteSwap(CI);
16226 if (CI->getType()->isIntegerTy(64)) {
16227 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16228 if (Constraints.size() >= 2 &&
16229 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16230 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16231 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16232 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16233 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16234 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16235 return IntrinsicLowering::LowerToByteSwap(CI);
16245 /// getConstraintType - Given a constraint letter, return the type of
16246 /// constraint it is for this target.
16247 X86TargetLowering::ConstraintType
16248 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16249 if (Constraint.size() == 1) {
16250 switch (Constraint[0]) {
16261 return C_RegisterClass;
16285 return TargetLowering::getConstraintType(Constraint);
16288 /// Examine constraint type and operand type and determine a weight value.
16289 /// This object must already have been set up with the operand type
16290 /// and the current alternative constraint selected.
16291 TargetLowering::ConstraintWeight
16292 X86TargetLowering::getSingleConstraintMatchWeight(
16293 AsmOperandInfo &info, const char *constraint) const {
16294 ConstraintWeight weight = CW_Invalid;
16295 Value *CallOperandVal = info.CallOperandVal;
16296 // If we don't have a value, we can't do a match,
16297 // but allow it at the lowest weight.
16298 if (CallOperandVal == NULL)
16300 Type *type = CallOperandVal->getType();
16301 // Look at the constraint type.
16302 switch (*constraint) {
16304 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16315 if (CallOperandVal->getType()->isIntegerTy())
16316 weight = CW_SpecificReg;
16321 if (type->isFloatingPointTy())
16322 weight = CW_SpecificReg;
16325 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16326 weight = CW_SpecificReg;
16330 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16331 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16332 weight = CW_Register;
16335 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16336 if (C->getZExtValue() <= 31)
16337 weight = CW_Constant;
16341 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16342 if (C->getZExtValue() <= 63)
16343 weight = CW_Constant;
16347 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16348 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16349 weight = CW_Constant;
16353 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16354 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16355 weight = CW_Constant;
16359 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16360 if (C->getZExtValue() <= 3)
16361 weight = CW_Constant;
16365 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16366 if (C->getZExtValue() <= 0xff)
16367 weight = CW_Constant;
16372 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16373 weight = CW_Constant;
16377 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16378 if ((C->getSExtValue() >= -0x80000000LL) &&
16379 (C->getSExtValue() <= 0x7fffffffLL))
16380 weight = CW_Constant;
16384 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16385 if (C->getZExtValue() <= 0xffffffff)
16386 weight = CW_Constant;
16393 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16394 /// with another that has more specific requirements based on the type of the
16395 /// corresponding operand.
16396 const char *X86TargetLowering::
16397 LowerXConstraint(EVT ConstraintVT) const {
16398 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16399 // 'f' like normal targets.
16400 if (ConstraintVT.isFloatingPoint()) {
16401 if (Subtarget->hasSSE2())
16403 if (Subtarget->hasSSE1())
16407 return TargetLowering::LowerXConstraint(ConstraintVT);
16410 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16411 /// vector. If it is invalid, don't add anything to Ops.
16412 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16413 std::string &Constraint,
16414 std::vector<SDValue>&Ops,
16415 SelectionDAG &DAG) const {
16416 SDValue Result(0, 0);
16418 // Only support length 1 constraints for now.
16419 if (Constraint.length() > 1) return;
16421 char ConstraintLetter = Constraint[0];
16422 switch (ConstraintLetter) {
16425 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16426 if (C->getZExtValue() <= 31) {
16427 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16434 if (C->getZExtValue() <= 63) {
16435 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16441 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16442 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16443 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16449 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16450 if (C->getZExtValue() <= 255) {
16451 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16457 // 32-bit signed value
16458 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16459 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16460 C->getSExtValue())) {
16461 // Widen to 64 bits here to get it sign extended.
16462 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16465 // FIXME gcc accepts some relocatable values here too, but only in certain
16466 // memory models; it's complicated.
16471 // 32-bit unsigned value
16472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16473 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16474 C->getZExtValue())) {
16475 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16479 // FIXME gcc accepts some relocatable values here too, but only in certain
16480 // memory models; it's complicated.
16484 // Literal immediates are always ok.
16485 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16486 // Widen to 64 bits here to get it sign extended.
16487 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16491 // In any sort of PIC mode addresses need to be computed at runtime by
16492 // adding in a register or some sort of table lookup. These can't
16493 // be used as immediates.
16494 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16497 // If we are in non-pic codegen mode, we allow the address of a global (with
16498 // an optional displacement) to be used with 'i'.
16499 GlobalAddressSDNode *GA = 0;
16500 int64_t Offset = 0;
16502 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16504 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16505 Offset += GA->getOffset();
16507 } else if (Op.getOpcode() == ISD::ADD) {
16508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16509 Offset += C->getZExtValue();
16510 Op = Op.getOperand(0);
16513 } else if (Op.getOpcode() == ISD::SUB) {
16514 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16515 Offset += -C->getZExtValue();
16516 Op = Op.getOperand(0);
16521 // Otherwise, this isn't something we can handle, reject it.
16525 const GlobalValue *GV = GA->getGlobal();
16526 // If we require an extra load to get this address, as in PIC mode, we
16527 // can't accept it.
16528 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16529 getTargetMachine())))
16532 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16533 GA->getValueType(0), Offset);
16538 if (Result.getNode()) {
16539 Ops.push_back(Result);
16542 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16545 std::pair<unsigned, const TargetRegisterClass*>
16546 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16548 // First, see if this is a constraint that directly corresponds to an LLVM
16550 if (Constraint.size() == 1) {
16551 // GCC Constraint Letters
16552 switch (Constraint[0]) {
16554 // TODO: Slight differences here in allocation order and leaving
16555 // RIP in the class. Do they matter any more here than they do
16556 // in the normal allocation?
16557 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16558 if (Subtarget->is64Bit()) {
16559 if (VT == MVT::i32 || VT == MVT::f32)
16560 return std::make_pair(0U, &X86::GR32RegClass);
16561 if (VT == MVT::i16)
16562 return std::make_pair(0U, &X86::GR16RegClass);
16563 if (VT == MVT::i8 || VT == MVT::i1)
16564 return std::make_pair(0U, &X86::GR8RegClass);
16565 if (VT == MVT::i64 || VT == MVT::f64)
16566 return std::make_pair(0U, &X86::GR64RegClass);
16569 // 32-bit fallthrough
16570 case 'Q': // Q_REGS
16571 if (VT == MVT::i32 || VT == MVT::f32)
16572 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16573 if (VT == MVT::i16)
16574 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16575 if (VT == MVT::i8 || VT == MVT::i1)
16576 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16577 if (VT == MVT::i64)
16578 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16580 case 'r': // GENERAL_REGS
16581 case 'l': // INDEX_REGS
16582 if (VT == MVT::i8 || VT == MVT::i1)
16583 return std::make_pair(0U, &X86::GR8RegClass);
16584 if (VT == MVT::i16)
16585 return std::make_pair(0U, &X86::GR16RegClass);
16586 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16587 return std::make_pair(0U, &X86::GR32RegClass);
16588 return std::make_pair(0U, &X86::GR64RegClass);
16589 case 'R': // LEGACY_REGS
16590 if (VT == MVT::i8 || VT == MVT::i1)
16591 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16592 if (VT == MVT::i16)
16593 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16594 if (VT == MVT::i32 || !Subtarget->is64Bit())
16595 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16596 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16597 case 'f': // FP Stack registers.
16598 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16599 // value to the correct fpstack register class.
16600 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16601 return std::make_pair(0U, &X86::RFP32RegClass);
16602 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16603 return std::make_pair(0U, &X86::RFP64RegClass);
16604 return std::make_pair(0U, &X86::RFP80RegClass);
16605 case 'y': // MMX_REGS if MMX allowed.
16606 if (!Subtarget->hasMMX()) break;
16607 return std::make_pair(0U, &X86::VR64RegClass);
16608 case 'Y': // SSE_REGS if SSE2 allowed
16609 if (!Subtarget->hasSSE2()) break;
16611 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16612 if (!Subtarget->hasSSE1()) break;
16614 switch (VT.getSimpleVT().SimpleTy) {
16616 // Scalar SSE types.
16619 return std::make_pair(0U, &X86::FR32RegClass);
16622 return std::make_pair(0U, &X86::FR64RegClass);
16630 return std::make_pair(0U, &X86::VR128RegClass);
16638 return std::make_pair(0U, &X86::VR256RegClass);
16644 // Use the default implementation in TargetLowering to convert the register
16645 // constraint into a member of a register class.
16646 std::pair<unsigned, const TargetRegisterClass*> Res;
16647 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16649 // Not found as a standard register?
16650 if (Res.second == 0) {
16651 // Map st(0) -> st(7) -> ST0
16652 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16653 tolower(Constraint[1]) == 's' &&
16654 tolower(Constraint[2]) == 't' &&
16655 Constraint[3] == '(' &&
16656 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16657 Constraint[5] == ')' &&
16658 Constraint[6] == '}') {
16660 Res.first = X86::ST0+Constraint[4]-'0';
16661 Res.second = &X86::RFP80RegClass;
16665 // GCC allows "st(0)" to be called just plain "st".
16666 if (StringRef("{st}").equals_lower(Constraint)) {
16667 Res.first = X86::ST0;
16668 Res.second = &X86::RFP80RegClass;
16673 if (StringRef("{flags}").equals_lower(Constraint)) {
16674 Res.first = X86::EFLAGS;
16675 Res.second = &X86::CCRRegClass;
16679 // 'A' means EAX + EDX.
16680 if (Constraint == "A") {
16681 Res.first = X86::EAX;
16682 Res.second = &X86::GR32_ADRegClass;
16688 // Otherwise, check to see if this is a register class of the wrong value
16689 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16690 // turn into {ax},{dx}.
16691 if (Res.second->hasType(VT))
16692 return Res; // Correct type already, nothing to do.
16694 // All of the single-register GCC register classes map their values onto
16695 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16696 // really want an 8-bit or 32-bit register, map to the appropriate register
16697 // class and return the appropriate register.
16698 if (Res.second == &X86::GR16RegClass) {
16699 if (VT == MVT::i8) {
16700 unsigned DestReg = 0;
16701 switch (Res.first) {
16703 case X86::AX: DestReg = X86::AL; break;
16704 case X86::DX: DestReg = X86::DL; break;
16705 case X86::CX: DestReg = X86::CL; break;
16706 case X86::BX: DestReg = X86::BL; break;
16709 Res.first = DestReg;
16710 Res.second = &X86::GR8RegClass;
16712 } else if (VT == MVT::i32) {
16713 unsigned DestReg = 0;
16714 switch (Res.first) {
16716 case X86::AX: DestReg = X86::EAX; break;
16717 case X86::DX: DestReg = X86::EDX; break;
16718 case X86::CX: DestReg = X86::ECX; break;
16719 case X86::BX: DestReg = X86::EBX; break;
16720 case X86::SI: DestReg = X86::ESI; break;
16721 case X86::DI: DestReg = X86::EDI; break;
16722 case X86::BP: DestReg = X86::EBP; break;
16723 case X86::SP: DestReg = X86::ESP; break;
16726 Res.first = DestReg;
16727 Res.second = &X86::GR32RegClass;
16729 } else if (VT == MVT::i64) {
16730 unsigned DestReg = 0;
16731 switch (Res.first) {
16733 case X86::AX: DestReg = X86::RAX; break;
16734 case X86::DX: DestReg = X86::RDX; break;
16735 case X86::CX: DestReg = X86::RCX; break;
16736 case X86::BX: DestReg = X86::RBX; break;
16737 case X86::SI: DestReg = X86::RSI; break;
16738 case X86::DI: DestReg = X86::RDI; break;
16739 case X86::BP: DestReg = X86::RBP; break;
16740 case X86::SP: DestReg = X86::RSP; break;
16743 Res.first = DestReg;
16744 Res.second = &X86::GR64RegClass;
16747 } else if (Res.second == &X86::FR32RegClass ||
16748 Res.second == &X86::FR64RegClass ||
16749 Res.second == &X86::VR128RegClass) {
16750 // Handle references to XMM physical registers that got mapped into the
16751 // wrong class. This can happen with constraints like {xmm0} where the
16752 // target independent register mapper will just pick the first match it can
16753 // find, ignoring the required type.
16755 if (VT == MVT::f32 || VT == MVT::i32)
16756 Res.second = &X86::FR32RegClass;
16757 else if (VT == MVT::f64 || VT == MVT::i64)
16758 Res.second = &X86::FR64RegClass;
16759 else if (X86::VR128RegClass.hasType(VT))
16760 Res.second = &X86::VR128RegClass;
16761 else if (X86::VR256RegClass.hasType(VT))
16762 Res.second = &X86::VR256RegClass;