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.getSizeInBits() == 256 && "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.getSizeInBits() == 128 && "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);
832 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
835 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
836 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
838 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
839 // registers cannot be used even for integer operations.
840 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
841 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
842 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
843 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
845 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
846 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
847 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
848 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
849 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
850 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
851 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
852 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
853 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
854 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
855 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
856 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
857 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
858 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
859 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
860 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
862 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
863 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
864 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
865 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
867 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
868 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
873 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
874 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
875 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
876 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
877 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
879 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881 EVT VT = (MVT::SimpleValueType)i;
882 // Do not attempt to custom lower non-power-of-2 vectors
883 if (!isPowerOf2_32(VT.getVectorNumElements()))
885 // Do not attempt to custom lower non-128-bit vectors
886 if (!VT.is128BitVector())
888 setOperationAction(ISD::BUILD_VECTOR,
889 VT.getSimpleVT().SimpleTy, Custom);
890 setOperationAction(ISD::VECTOR_SHUFFLE,
891 VT.getSimpleVT().SimpleTy, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
893 VT.getSimpleVT().SimpleTy, Custom);
896 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
897 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
898 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
899 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
901 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
903 if (Subtarget->is64Bit()) {
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
908 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
913 // Do not attempt to promote non-128-bit vectors
914 if (!VT.is128BitVector())
917 setOperationAction(ISD::AND, SVT, Promote);
918 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
919 setOperationAction(ISD::OR, SVT, Promote);
920 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
921 setOperationAction(ISD::XOR, SVT, Promote);
922 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
923 setOperationAction(ISD::LOAD, SVT, Promote);
924 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
925 setOperationAction(ISD::SELECT, SVT, Promote);
926 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
929 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
931 // Custom lower v2i64 and v2f64 selects.
932 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
933 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
934 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
935 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
937 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
938 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
941 if (Subtarget->hasSSE41()) {
942 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
943 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
944 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
945 setOperationAction(ISD::FRINT, MVT::f32, Legal);
946 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
947 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
948 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
949 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
950 setOperationAction(ISD::FRINT, MVT::f64, Legal);
951 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
953 // FIXME: Do we need to handle scalar-to-vector here?
954 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
956 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
957 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
958 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
959 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
960 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
962 // i8 and i16 vectors are custom , because the source register and source
963 // source memory operand types are not the same width. f32 vectors are
964 // custom since the immediate controlling the insert encodes additional
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
974 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
976 // FIXME: these should be Legal but thats only for the case where
977 // the index is constant. For now custom expand to deal with that.
978 if (Subtarget->is64Bit()) {
979 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
984 if (Subtarget->hasSSE2()) {
985 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
986 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
988 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
989 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
991 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
992 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
994 if (Subtarget->hasAVX2()) {
995 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
996 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
998 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
999 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1001 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1003 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1004 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1006 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1007 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1009 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1013 if (Subtarget->hasSSE42())
1014 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1016 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1017 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1018 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1019 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1020 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1021 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1022 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1024 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1025 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1026 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1028 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1029 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1030 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1031 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1032 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1033 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1035 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1036 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1037 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1038 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1039 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1040 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1042 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1043 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1044 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1046 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1047 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1048 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1049 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1050 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1051 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1053 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1054 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1056 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1057 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1059 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1060 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1062 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1063 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1064 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1065 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1067 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1068 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1069 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1071 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1073 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1074 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1076 if (Subtarget->hasFMA()) {
1077 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1078 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1079 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1080 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1081 setOperationAction(ISD::FMA, MVT::f32, Custom);
1082 setOperationAction(ISD::FMA, MVT::f64, Custom);
1084 if (Subtarget->hasAVX2()) {
1085 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1086 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1087 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1088 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1090 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1091 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1092 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1093 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1095 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1096 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1097 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1098 // Don't lower v32i8 because there is no 128-bit byte mul
1100 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1102 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1103 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1105 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1106 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1108 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1110 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1111 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1112 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1113 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1115 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1116 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1117 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1118 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1120 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1121 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1122 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1123 // Don't lower v32i8 because there is no 128-bit byte mul
1125 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1126 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1128 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1129 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1131 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1134 // Custom lower several nodes for 256-bit types.
1135 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1136 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1137 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1140 // Extract subvector is special because the value type
1141 // (result) is 128-bit but the source is 256-bit wide.
1142 if (VT.is128BitVector())
1143 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1145 // Do not attempt to custom lower other non-256-bit vectors
1146 if (!VT.is256BitVector())
1149 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1150 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1151 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1152 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1153 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1154 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1157 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1158 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1159 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1162 // Do not attempt to promote non-256-bit vectors
1163 if (!VT.is256BitVector())
1166 setOperationAction(ISD::AND, SVT, Promote);
1167 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1168 setOperationAction(ISD::OR, SVT, Promote);
1169 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1170 setOperationAction(ISD::XOR, SVT, Promote);
1171 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1172 setOperationAction(ISD::LOAD, SVT, Promote);
1173 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1174 setOperationAction(ISD::SELECT, SVT, Promote);
1175 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1179 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1180 // of this type with custom code.
1181 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1182 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1183 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1187 // We want to custom lower some of our intrinsics.
1188 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1189 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1192 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1193 // handle type legalization for these operations here.
1195 // FIXME: We really should do custom legalization for addition and
1196 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1197 // than generic legalization for 64-bit multiplication-with-overflow, though.
1198 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1199 // Add/Sub/Mul with overflow operations are custom lowered.
1201 setOperationAction(ISD::SADDO, VT, Custom);
1202 setOperationAction(ISD::UADDO, VT, Custom);
1203 setOperationAction(ISD::SSUBO, VT, Custom);
1204 setOperationAction(ISD::USUBO, VT, Custom);
1205 setOperationAction(ISD::SMULO, VT, Custom);
1206 setOperationAction(ISD::UMULO, VT, Custom);
1209 // There are no 8-bit 3-address imul/mul instructions
1210 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1211 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1213 if (!Subtarget->is64Bit()) {
1214 // These libcalls are not available in 32-bit.
1215 setLibcallName(RTLIB::SHL_I128, 0);
1216 setLibcallName(RTLIB::SRL_I128, 0);
1217 setLibcallName(RTLIB::SRA_I128, 0);
1220 // We have target-specific dag combine patterns for the following nodes:
1221 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1222 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1223 setTargetDAGCombine(ISD::VSELECT);
1224 setTargetDAGCombine(ISD::SELECT);
1225 setTargetDAGCombine(ISD::SHL);
1226 setTargetDAGCombine(ISD::SRA);
1227 setTargetDAGCombine(ISD::SRL);
1228 setTargetDAGCombine(ISD::OR);
1229 setTargetDAGCombine(ISD::AND);
1230 setTargetDAGCombine(ISD::ADD);
1231 setTargetDAGCombine(ISD::FADD);
1232 setTargetDAGCombine(ISD::FSUB);
1233 setTargetDAGCombine(ISD::FMA);
1234 setTargetDAGCombine(ISD::SUB);
1235 setTargetDAGCombine(ISD::LOAD);
1236 setTargetDAGCombine(ISD::STORE);
1237 setTargetDAGCombine(ISD::ZERO_EXTEND);
1238 setTargetDAGCombine(ISD::ANY_EXTEND);
1239 setTargetDAGCombine(ISD::SIGN_EXTEND);
1240 setTargetDAGCombine(ISD::TRUNCATE);
1241 setTargetDAGCombine(ISD::UINT_TO_FP);
1242 setTargetDAGCombine(ISD::SINT_TO_FP);
1243 setTargetDAGCombine(ISD::SETCC);
1244 setTargetDAGCombine(ISD::FP_TO_SINT);
1245 if (Subtarget->is64Bit())
1246 setTargetDAGCombine(ISD::MUL);
1247 setTargetDAGCombine(ISD::XOR);
1249 computeRegisterProperties();
1251 // On Darwin, -Os means optimize for size without hurting performance,
1252 // do not reduce the limit.
1253 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1254 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1255 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1256 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1257 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1258 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1259 setPrefLoopAlignment(4); // 2^4 bytes.
1260 benefitFromCodePlacementOpt = true;
1262 // Predictable cmov don't hurt on atom because it's in-order.
1263 predictableSelectIsExpensive = !Subtarget->isAtom();
1265 setPrefFunctionAlignment(4); // 2^4 bytes.
1269 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1270 if (!VT.isVector()) return MVT::i8;
1271 return VT.changeVectorElementTypeToInteger();
1275 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1276 /// the desired ByVal argument alignment.
1277 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1280 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1281 if (VTy->getBitWidth() == 128)
1283 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1284 unsigned EltAlign = 0;
1285 getMaxByValAlign(ATy->getElementType(), EltAlign);
1286 if (EltAlign > MaxAlign)
1287 MaxAlign = EltAlign;
1288 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1289 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1290 unsigned EltAlign = 0;
1291 getMaxByValAlign(STy->getElementType(i), EltAlign);
1292 if (EltAlign > MaxAlign)
1293 MaxAlign = EltAlign;
1300 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1301 /// function arguments in the caller parameter area. For X86, aggregates
1302 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1303 /// are at 4-byte boundaries.
1304 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1305 if (Subtarget->is64Bit()) {
1306 // Max of 8 and alignment of type.
1307 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1314 if (Subtarget->hasSSE1())
1315 getMaxByValAlign(Ty, Align);
1319 /// getOptimalMemOpType - Returns the target specific optimal type for load
1320 /// and store operations as a result of memset, memcpy, and memmove
1321 /// lowering. If DstAlign is zero that means it's safe to destination
1322 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1323 /// means there isn't a need to check it against alignment requirement,
1324 /// probably because the source does not need to be loaded. If
1325 /// 'IsZeroVal' is true, that means it's safe to return a
1326 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1327 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1328 /// constant so it does not need to be loaded.
1329 /// It returns EVT::Other if the type should be determined using generic
1330 /// target-independent logic.
1332 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1333 unsigned DstAlign, unsigned SrcAlign,
1336 MachineFunction &MF) const {
1337 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1338 // linux. This is because the stack realignment code can't handle certain
1339 // cases like PR2962. This should be removed when PR2962 is fixed.
1340 const Function *F = MF.getFunction();
1342 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1344 (Subtarget->isUnalignedMemAccessFast() ||
1345 ((DstAlign == 0 || DstAlign >= 16) &&
1346 (SrcAlign == 0 || SrcAlign >= 16))) &&
1347 Subtarget->getStackAlignment() >= 16) {
1348 if (Subtarget->getStackAlignment() >= 32) {
1349 if (Subtarget->hasAVX2())
1351 if (Subtarget->hasAVX())
1354 if (Subtarget->hasSSE2())
1356 if (Subtarget->hasSSE1())
1358 } else if (!MemcpyStrSrc && Size >= 8 &&
1359 !Subtarget->is64Bit() &&
1360 Subtarget->getStackAlignment() >= 8 &&
1361 Subtarget->hasSSE2()) {
1362 // Do not use f64 to lower memcpy if source is string constant. It's
1363 // better to use i32 to avoid the loads.
1367 if (Subtarget->is64Bit() && Size >= 8)
1372 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1373 /// current function. The returned value is a member of the
1374 /// MachineJumpTableInfo::JTEntryKind enum.
1375 unsigned X86TargetLowering::getJumpTableEncoding() const {
1376 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1378 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1379 Subtarget->isPICStyleGOT())
1380 return MachineJumpTableInfo::EK_Custom32;
1382 // Otherwise, use the normal jump table encoding heuristics.
1383 return TargetLowering::getJumpTableEncoding();
1387 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1388 const MachineBasicBlock *MBB,
1389 unsigned uid,MCContext &Ctx) const{
1390 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1391 Subtarget->isPICStyleGOT());
1392 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1394 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1395 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1398 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1400 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1401 SelectionDAG &DAG) const {
1402 if (!Subtarget->is64Bit())
1403 // This doesn't have DebugLoc associated with it, but is not really the
1404 // same as a Register.
1405 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1409 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1410 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1412 const MCExpr *X86TargetLowering::
1413 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1414 MCContext &Ctx) const {
1415 // X86-64 uses RIP relative addressing based on the jump table label.
1416 if (Subtarget->isPICStyleRIPRel())
1417 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1419 // Otherwise, the reference is relative to the PIC base.
1420 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1423 // FIXME: Why this routine is here? Move to RegInfo!
1424 std::pair<const TargetRegisterClass*, uint8_t>
1425 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1426 const TargetRegisterClass *RRC = 0;
1428 switch (VT.getSimpleVT().SimpleTy) {
1430 return TargetLowering::findRepresentativeClass(VT);
1431 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1432 RRC = Subtarget->is64Bit() ?
1433 (const TargetRegisterClass*)&X86::GR64RegClass :
1434 (const TargetRegisterClass*)&X86::GR32RegClass;
1437 RRC = &X86::VR64RegClass;
1439 case MVT::f32: case MVT::f64:
1440 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1441 case MVT::v4f32: case MVT::v2f64:
1442 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1444 RRC = &X86::VR128RegClass;
1447 return std::make_pair(RRC, Cost);
1450 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1451 unsigned &Offset) const {
1452 if (!Subtarget->isTargetLinux())
1455 if (Subtarget->is64Bit()) {
1456 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1458 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1471 //===----------------------------------------------------------------------===//
1472 // Return Value Calling Convention Implementation
1473 //===----------------------------------------------------------------------===//
1475 #include "X86GenCallingConv.inc"
1478 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1479 MachineFunction &MF, bool isVarArg,
1480 const SmallVectorImpl<ISD::OutputArg> &Outs,
1481 LLVMContext &Context) const {
1482 SmallVector<CCValAssign, 16> RVLocs;
1483 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1485 return CCInfo.CheckReturn(Outs, RetCC_X86);
1489 X86TargetLowering::LowerReturn(SDValue Chain,
1490 CallingConv::ID CallConv, bool isVarArg,
1491 const SmallVectorImpl<ISD::OutputArg> &Outs,
1492 const SmallVectorImpl<SDValue> &OutVals,
1493 DebugLoc dl, SelectionDAG &DAG) const {
1494 MachineFunction &MF = DAG.getMachineFunction();
1495 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1497 SmallVector<CCValAssign, 16> RVLocs;
1498 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1499 RVLocs, *DAG.getContext());
1500 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1502 // Add the regs to the liveout set for the function.
1503 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1504 for (unsigned i = 0; i != RVLocs.size(); ++i)
1505 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1506 MRI.addLiveOut(RVLocs[i].getLocReg());
1510 SmallVector<SDValue, 6> RetOps;
1511 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1512 // Operand #1 = Bytes To Pop
1513 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1516 // Copy the result values into the output registers.
1517 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1518 CCValAssign &VA = RVLocs[i];
1519 assert(VA.isRegLoc() && "Can only return in registers!");
1520 SDValue ValToCopy = OutVals[i];
1521 EVT ValVT = ValToCopy.getValueType();
1523 // Promote values to the appropriate types
1524 if (VA.getLocInfo() == CCValAssign::SExt)
1525 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1526 else if (VA.getLocInfo() == CCValAssign::ZExt)
1527 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1528 else if (VA.getLocInfo() == CCValAssign::AExt)
1529 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1530 else if (VA.getLocInfo() == CCValAssign::BCvt)
1531 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1533 // If this is x86-64, and we disabled SSE, we can't return FP values,
1534 // or SSE or MMX vectors.
1535 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1536 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1537 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1538 report_fatal_error("SSE register return with SSE disabled");
1540 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1541 // llvm-gcc has never done it right and no one has noticed, so this
1542 // should be OK for now.
1543 if (ValVT == MVT::f64 &&
1544 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1545 report_fatal_error("SSE2 register return with SSE2 disabled");
1547 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1548 // the RET instruction and handled by the FP Stackifier.
1549 if (VA.getLocReg() == X86::ST0 ||
1550 VA.getLocReg() == X86::ST1) {
1551 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1552 // change the value to the FP stack register class.
1553 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1554 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1555 RetOps.push_back(ValToCopy);
1556 // Don't emit a copytoreg.
1560 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1561 // which is returned in RAX / RDX.
1562 if (Subtarget->is64Bit()) {
1563 if (ValVT == MVT::x86mmx) {
1564 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1565 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1566 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1568 // If we don't have SSE2 available, convert to v4f32 so the generated
1569 // register is legal.
1570 if (!Subtarget->hasSSE2())
1571 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1576 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1577 Flag = Chain.getValue(1);
1580 // The x86-64 ABI for returning structs by value requires that we copy
1581 // the sret argument into %rax for the return. We saved the argument into
1582 // a virtual register in the entry block, so now we copy the value out
1584 if (Subtarget->is64Bit() &&
1585 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1586 MachineFunction &MF = DAG.getMachineFunction();
1587 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1588 unsigned Reg = FuncInfo->getSRetReturnReg();
1590 "SRetReturnReg should have been set in LowerFormalArguments().");
1591 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1593 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1594 Flag = Chain.getValue(1);
1596 // RAX now acts like a return value.
1597 MRI.addLiveOut(X86::RAX);
1600 RetOps[0] = Chain; // Update chain.
1602 // Add the flag if we have it.
1604 RetOps.push_back(Flag);
1606 return DAG.getNode(X86ISD::RET_FLAG, dl,
1607 MVT::Other, &RetOps[0], RetOps.size());
1610 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1611 if (N->getNumValues() != 1)
1613 if (!N->hasNUsesOfValue(1, 0))
1616 SDValue TCChain = Chain;
1617 SDNode *Copy = *N->use_begin();
1618 if (Copy->getOpcode() == ISD::CopyToReg) {
1619 // If the copy has a glue operand, we conservatively assume it isn't safe to
1620 // perform a tail call.
1621 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1623 TCChain = Copy->getOperand(0);
1624 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1627 bool HasRet = false;
1628 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1630 if (UI->getOpcode() != X86ISD::RET_FLAG)
1643 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1644 ISD::NodeType ExtendKind) const {
1646 // TODO: Is this also valid on 32-bit?
1647 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1648 ReturnMVT = MVT::i8;
1650 ReturnMVT = MVT::i32;
1652 EVT MinVT = getRegisterType(Context, ReturnMVT);
1653 return VT.bitsLT(MinVT) ? MinVT : VT;
1656 /// LowerCallResult - Lower the result values of a call into the
1657 /// appropriate copies out of appropriate physical registers.
1660 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1661 CallingConv::ID CallConv, bool isVarArg,
1662 const SmallVectorImpl<ISD::InputArg> &Ins,
1663 DebugLoc dl, SelectionDAG &DAG,
1664 SmallVectorImpl<SDValue> &InVals) const {
1666 // Assign locations to each value returned by this call.
1667 SmallVector<CCValAssign, 16> RVLocs;
1668 bool Is64Bit = Subtarget->is64Bit();
1669 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1670 getTargetMachine(), RVLocs, *DAG.getContext());
1671 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1673 // Copy all of the result registers out of their specified physreg.
1674 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1675 CCValAssign &VA = RVLocs[i];
1676 EVT CopyVT = VA.getValVT();
1678 // If this is x86-64, and we disabled SSE, we can't return FP values
1679 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1680 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1681 report_fatal_error("SSE register return with SSE disabled");
1686 // If this is a call to a function that returns an fp value on the floating
1687 // point stack, we must guarantee the value is popped from the stack, so
1688 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1689 // if the return value is not used. We use the FpPOP_RETVAL instruction
1691 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1692 // If we prefer to use the value in xmm registers, copy it out as f80 and
1693 // use a truncate to move it from fp stack reg to xmm reg.
1694 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1695 SDValue Ops[] = { Chain, InFlag };
1696 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1697 MVT::Other, MVT::Glue, Ops, 2), 1);
1698 Val = Chain.getValue(0);
1700 // Round the f80 to the right size, which also moves it to the appropriate
1702 if (CopyVT != VA.getValVT())
1703 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1704 // This truncation won't change the value.
1705 DAG.getIntPtrConstant(1));
1707 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1708 CopyVT, InFlag).getValue(1);
1709 Val = Chain.getValue(0);
1711 InFlag = Chain.getValue(2);
1712 InVals.push_back(Val);
1719 //===----------------------------------------------------------------------===//
1720 // C & StdCall & Fast Calling Convention implementation
1721 //===----------------------------------------------------------------------===//
1722 // StdCall calling convention seems to be standard for many Windows' API
1723 // routines and around. It differs from C calling convention just a little:
1724 // callee should clean up the stack, not caller. Symbols should be also
1725 // decorated in some fancy way :) It doesn't support any vector arguments.
1726 // For info on fast calling convention see Fast Calling Convention (tail call)
1727 // implementation LowerX86_32FastCCCallTo.
1729 /// CallIsStructReturn - Determines whether a call uses struct return
1731 enum StructReturnType {
1736 static StructReturnType
1737 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1739 return NotStructReturn;
1741 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1742 if (!Flags.isSRet())
1743 return NotStructReturn;
1744 if (Flags.isInReg())
1745 return RegStructReturn;
1746 return StackStructReturn;
1749 /// ArgsAreStructReturn - Determines whether a function uses struct
1750 /// return semantics.
1751 static StructReturnType
1752 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1754 return NotStructReturn;
1756 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1757 if (!Flags.isSRet())
1758 return NotStructReturn;
1759 if (Flags.isInReg())
1760 return RegStructReturn;
1761 return StackStructReturn;
1764 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1765 /// by "Src" to address "Dst" with size and alignment information specified by
1766 /// the specific parameter attribute. The copy will be passed as a byval
1767 /// function parameter.
1769 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1770 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1772 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1774 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1775 /*isVolatile*/false, /*AlwaysInline=*/true,
1776 MachinePointerInfo(), MachinePointerInfo());
1779 /// IsTailCallConvention - Return true if the calling convention is one that
1780 /// supports tail call optimization.
1781 static bool IsTailCallConvention(CallingConv::ID CC) {
1782 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1785 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1786 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1790 CallingConv::ID CalleeCC = CS.getCallingConv();
1791 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1797 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1798 /// a tailcall target by changing its ABI.
1799 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1800 bool GuaranteedTailCallOpt) {
1801 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1805 X86TargetLowering::LowerMemArgument(SDValue Chain,
1806 CallingConv::ID CallConv,
1807 const SmallVectorImpl<ISD::InputArg> &Ins,
1808 DebugLoc dl, SelectionDAG &DAG,
1809 const CCValAssign &VA,
1810 MachineFrameInfo *MFI,
1812 // Create the nodes corresponding to a load from this parameter slot.
1813 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1814 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1815 getTargetMachine().Options.GuaranteedTailCallOpt);
1816 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1819 // If value is passed by pointer we have address passed instead of the value
1821 if (VA.getLocInfo() == CCValAssign::Indirect)
1822 ValVT = VA.getLocVT();
1824 ValVT = VA.getValVT();
1826 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1827 // changed with more analysis.
1828 // In case of tail call optimization mark all arguments mutable. Since they
1829 // could be overwritten by lowering of arguments in case of a tail call.
1830 if (Flags.isByVal()) {
1831 unsigned Bytes = Flags.getByValSize();
1832 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1833 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1834 return DAG.getFrameIndex(FI, getPointerTy());
1836 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1837 VA.getLocMemOffset(), isImmutable);
1838 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1839 return DAG.getLoad(ValVT, dl, Chain, FIN,
1840 MachinePointerInfo::getFixedStack(FI),
1841 false, false, false, 0);
1846 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1847 CallingConv::ID CallConv,
1849 const SmallVectorImpl<ISD::InputArg> &Ins,
1852 SmallVectorImpl<SDValue> &InVals)
1854 MachineFunction &MF = DAG.getMachineFunction();
1855 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1857 const Function* Fn = MF.getFunction();
1858 if (Fn->hasExternalLinkage() &&
1859 Subtarget->isTargetCygMing() &&
1860 Fn->getName() == "main")
1861 FuncInfo->setForceFramePointer(true);
1863 MachineFrameInfo *MFI = MF.getFrameInfo();
1864 bool Is64Bit = Subtarget->is64Bit();
1865 bool IsWindows = Subtarget->isTargetWindows();
1866 bool IsWin64 = Subtarget->isTargetWin64();
1868 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1869 "Var args not supported with calling convention fastcc or ghc");
1871 // Assign locations to all of the incoming arguments.
1872 SmallVector<CCValAssign, 16> ArgLocs;
1873 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1874 ArgLocs, *DAG.getContext());
1876 // Allocate shadow area for Win64
1878 CCInfo.AllocateStack(32, 8);
1881 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1883 unsigned LastVal = ~0U;
1885 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1886 CCValAssign &VA = ArgLocs[i];
1887 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1889 assert(VA.getValNo() != LastVal &&
1890 "Don't support value assigned to multiple locs yet");
1892 LastVal = VA.getValNo();
1894 if (VA.isRegLoc()) {
1895 EVT RegVT = VA.getLocVT();
1896 const TargetRegisterClass *RC;
1897 if (RegVT == MVT::i32)
1898 RC = &X86::GR32RegClass;
1899 else if (Is64Bit && RegVT == MVT::i64)
1900 RC = &X86::GR64RegClass;
1901 else if (RegVT == MVT::f32)
1902 RC = &X86::FR32RegClass;
1903 else if (RegVT == MVT::f64)
1904 RC = &X86::FR64RegClass;
1905 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1906 RC = &X86::VR256RegClass;
1907 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1908 RC = &X86::VR128RegClass;
1909 else if (RegVT == MVT::x86mmx)
1910 RC = &X86::VR64RegClass;
1912 llvm_unreachable("Unknown argument type!");
1914 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1915 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1917 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1918 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1920 if (VA.getLocInfo() == CCValAssign::SExt)
1921 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1922 DAG.getValueType(VA.getValVT()));
1923 else if (VA.getLocInfo() == CCValAssign::ZExt)
1924 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1925 DAG.getValueType(VA.getValVT()));
1926 else if (VA.getLocInfo() == CCValAssign::BCvt)
1927 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1929 if (VA.isExtInLoc()) {
1930 // Handle MMX values passed in XMM regs.
1931 if (RegVT.isVector()) {
1932 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1935 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1938 assert(VA.isMemLoc());
1939 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1942 // If value is passed via pointer - do a load.
1943 if (VA.getLocInfo() == CCValAssign::Indirect)
1944 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1945 MachinePointerInfo(), false, false, false, 0);
1947 InVals.push_back(ArgValue);
1950 // The x86-64 ABI for returning structs by value requires that we copy
1951 // the sret argument into %rax for the return. Save the argument into
1952 // a virtual register so that we can access it from the return points.
1953 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1954 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1955 unsigned Reg = FuncInfo->getSRetReturnReg();
1957 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1958 FuncInfo->setSRetReturnReg(Reg);
1960 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1961 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1964 unsigned StackSize = CCInfo.getNextStackOffset();
1965 // Align stack specially for tail calls.
1966 if (FuncIsMadeTailCallSafe(CallConv,
1967 MF.getTarget().Options.GuaranteedTailCallOpt))
1968 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1970 // If the function takes variable number of arguments, make a frame index for
1971 // the start of the first vararg value... for expansion of llvm.va_start.
1973 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1974 CallConv != CallingConv::X86_ThisCall)) {
1975 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1978 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1980 // FIXME: We should really autogenerate these arrays
1981 static const uint16_t GPR64ArgRegsWin64[] = {
1982 X86::RCX, X86::RDX, X86::R8, X86::R9
1984 static const uint16_t GPR64ArgRegs64Bit[] = {
1985 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1987 static const uint16_t XMMArgRegs64Bit[] = {
1988 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1989 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1991 const uint16_t *GPR64ArgRegs;
1992 unsigned NumXMMRegs = 0;
1995 // The XMM registers which might contain var arg parameters are shadowed
1996 // in their paired GPR. So we only need to save the GPR to their home
1998 TotalNumIntRegs = 4;
1999 GPR64ArgRegs = GPR64ArgRegsWin64;
2001 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2002 GPR64ArgRegs = GPR64ArgRegs64Bit;
2004 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2007 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2010 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2011 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2012 "SSE register cannot be used when SSE is disabled!");
2013 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2014 NoImplicitFloatOps) &&
2015 "SSE register cannot be used when SSE is disabled!");
2016 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2017 !Subtarget->hasSSE1())
2018 // Kernel mode asks for SSE to be disabled, so don't push them
2020 TotalNumXMMRegs = 0;
2023 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2024 // Get to the caller-allocated home save location. Add 8 to account
2025 // for the return address.
2026 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2027 FuncInfo->setRegSaveFrameIndex(
2028 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2029 // Fixup to set vararg frame on shadow area (4 x i64).
2031 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2033 // For X86-64, if there are vararg parameters that are passed via
2034 // registers, then we must store them to their spots on the stack so
2035 // they may be loaded by deferencing the result of va_next.
2036 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2037 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2038 FuncInfo->setRegSaveFrameIndex(
2039 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2043 // Store the integer parameter registers.
2044 SmallVector<SDValue, 8> MemOps;
2045 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2047 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2048 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2049 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2050 DAG.getIntPtrConstant(Offset));
2051 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2052 &X86::GR64RegClass);
2053 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2055 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2056 MachinePointerInfo::getFixedStack(
2057 FuncInfo->getRegSaveFrameIndex(), Offset),
2059 MemOps.push_back(Store);
2063 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2064 // Now store the XMM (fp + vector) parameter registers.
2065 SmallVector<SDValue, 11> SaveXMMOps;
2066 SaveXMMOps.push_back(Chain);
2068 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2069 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2070 SaveXMMOps.push_back(ALVal);
2072 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2073 FuncInfo->getRegSaveFrameIndex()));
2074 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2075 FuncInfo->getVarArgsFPOffset()));
2077 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2078 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2079 &X86::VR128RegClass);
2080 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2081 SaveXMMOps.push_back(Val);
2083 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2085 &SaveXMMOps[0], SaveXMMOps.size()));
2088 if (!MemOps.empty())
2089 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2090 &MemOps[0], MemOps.size());
2094 // Some CCs need callee pop.
2095 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2096 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2097 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2099 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2100 // If this is an sret function, the return should pop the hidden pointer.
2101 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2102 argsAreStructReturn(Ins) == StackStructReturn)
2103 FuncInfo->setBytesToPopOnReturn(4);
2107 // RegSaveFrameIndex is X86-64 only.
2108 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2109 if (CallConv == CallingConv::X86_FastCall ||
2110 CallConv == CallingConv::X86_ThisCall)
2111 // fastcc functions can't have varargs.
2112 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2115 FuncInfo->setArgumentStackSize(StackSize);
2121 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2122 SDValue StackPtr, SDValue Arg,
2123 DebugLoc dl, SelectionDAG &DAG,
2124 const CCValAssign &VA,
2125 ISD::ArgFlagsTy Flags) const {
2126 unsigned LocMemOffset = VA.getLocMemOffset();
2127 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2128 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2129 if (Flags.isByVal())
2130 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2132 return DAG.getStore(Chain, dl, Arg, PtrOff,
2133 MachinePointerInfo::getStack(LocMemOffset),
2137 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2138 /// optimization is performed and it is required.
2140 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2141 SDValue &OutRetAddr, SDValue Chain,
2142 bool IsTailCall, bool Is64Bit,
2143 int FPDiff, DebugLoc dl) const {
2144 // Adjust the Return address stack slot.
2145 EVT VT = getPointerTy();
2146 OutRetAddr = getReturnAddressFrameIndex(DAG);
2148 // Load the "old" Return address.
2149 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2150 false, false, false, 0);
2151 return SDValue(OutRetAddr.getNode(), 1);
2154 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2155 /// optimization is performed and it is required (FPDiff!=0).
2157 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2158 SDValue Chain, SDValue RetAddrFrIdx,
2159 bool Is64Bit, int FPDiff, DebugLoc dl) {
2160 // Store the return address to the appropriate stack slot.
2161 if (!FPDiff) return Chain;
2162 // Calculate the new stack slot for the return address.
2163 int SlotSize = Is64Bit ? 8 : 4;
2164 int NewReturnAddrFI =
2165 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2166 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2167 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2168 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2169 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2175 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2176 SmallVectorImpl<SDValue> &InVals) const {
2177 SelectionDAG &DAG = CLI.DAG;
2178 DebugLoc &dl = CLI.DL;
2179 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2180 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2181 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2182 SDValue Chain = CLI.Chain;
2183 SDValue Callee = CLI.Callee;
2184 CallingConv::ID CallConv = CLI.CallConv;
2185 bool &isTailCall = CLI.IsTailCall;
2186 bool isVarArg = CLI.IsVarArg;
2188 MachineFunction &MF = DAG.getMachineFunction();
2189 bool Is64Bit = Subtarget->is64Bit();
2190 bool IsWin64 = Subtarget->isTargetWin64();
2191 bool IsWindows = Subtarget->isTargetWindows();
2192 StructReturnType SR = callIsStructReturn(Outs);
2193 bool IsSibcall = false;
2195 if (MF.getTarget().Options.DisableTailCalls)
2199 // Check if it's really possible to do a tail call.
2200 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2201 isVarArg, SR != NotStructReturn,
2202 MF.getFunction()->hasStructRetAttr(),
2203 Outs, OutVals, Ins, DAG);
2205 // Sibcalls are automatically detected tailcalls which do not require
2207 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2214 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2215 "Var args not supported with calling convention fastcc or ghc");
2217 // Analyze operands of the call, assigning locations to each operand.
2218 SmallVector<CCValAssign, 16> ArgLocs;
2219 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2220 ArgLocs, *DAG.getContext());
2222 // Allocate shadow area for Win64
2224 CCInfo.AllocateStack(32, 8);
2227 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2229 // Get a count of how many bytes are to be pushed on the stack.
2230 unsigned NumBytes = CCInfo.getNextStackOffset();
2232 // This is a sibcall. The memory operands are available in caller's
2233 // own caller's stack.
2235 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2236 IsTailCallConvention(CallConv))
2237 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2240 if (isTailCall && !IsSibcall) {
2241 // Lower arguments at fp - stackoffset + fpdiff.
2242 unsigned NumBytesCallerPushed =
2243 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2244 FPDiff = NumBytesCallerPushed - NumBytes;
2246 // Set the delta of movement of the returnaddr stackslot.
2247 // But only set if delta is greater than previous delta.
2248 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2249 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2253 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2255 SDValue RetAddrFrIdx;
2256 // Load return address for tail calls.
2257 if (isTailCall && FPDiff)
2258 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2259 Is64Bit, FPDiff, dl);
2261 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2262 SmallVector<SDValue, 8> MemOpChains;
2265 // Walk the register/memloc assignments, inserting copies/loads. In the case
2266 // of tail call optimization arguments are handle later.
2267 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2268 CCValAssign &VA = ArgLocs[i];
2269 EVT RegVT = VA.getLocVT();
2270 SDValue Arg = OutVals[i];
2271 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2272 bool isByVal = Flags.isByVal();
2274 // Promote the value if needed.
2275 switch (VA.getLocInfo()) {
2276 default: llvm_unreachable("Unknown loc info!");
2277 case CCValAssign::Full: break;
2278 case CCValAssign::SExt:
2279 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2281 case CCValAssign::ZExt:
2282 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2284 case CCValAssign::AExt:
2285 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2286 // Special case: passing MMX values in XMM registers.
2287 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2288 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2289 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2291 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2293 case CCValAssign::BCvt:
2294 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2296 case CCValAssign::Indirect: {
2297 // Store the argument.
2298 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2299 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2300 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2301 MachinePointerInfo::getFixedStack(FI),
2308 if (VA.isRegLoc()) {
2309 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2310 if (isVarArg && IsWin64) {
2311 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2312 // shadow reg if callee is a varargs function.
2313 unsigned ShadowReg = 0;
2314 switch (VA.getLocReg()) {
2315 case X86::XMM0: ShadowReg = X86::RCX; break;
2316 case X86::XMM1: ShadowReg = X86::RDX; break;
2317 case X86::XMM2: ShadowReg = X86::R8; break;
2318 case X86::XMM3: ShadowReg = X86::R9; break;
2321 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2323 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2324 assert(VA.isMemLoc());
2325 if (StackPtr.getNode() == 0)
2326 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2327 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2328 dl, DAG, VA, Flags));
2332 if (!MemOpChains.empty())
2333 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2334 &MemOpChains[0], MemOpChains.size());
2336 if (Subtarget->isPICStyleGOT()) {
2337 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2340 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2341 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2343 // If we are tail calling and generating PIC/GOT style code load the
2344 // address of the callee into ECX. The value in ecx is used as target of
2345 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2346 // for tail calls on PIC/GOT architectures. Normally we would just put the
2347 // address of GOT into ebx and then call target@PLT. But for tail calls
2348 // ebx would be restored (since ebx is callee saved) before jumping to the
2351 // Note: The actual moving to ECX is done further down.
2352 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2353 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2354 !G->getGlobal()->hasProtectedVisibility())
2355 Callee = LowerGlobalAddress(Callee, DAG);
2356 else if (isa<ExternalSymbolSDNode>(Callee))
2357 Callee = LowerExternalSymbol(Callee, DAG);
2361 if (Is64Bit && isVarArg && !IsWin64) {
2362 // From AMD64 ABI document:
2363 // For calls that may call functions that use varargs or stdargs
2364 // (prototype-less calls or calls to functions containing ellipsis (...) in
2365 // the declaration) %al is used as hidden argument to specify the number
2366 // of SSE registers used. The contents of %al do not need to match exactly
2367 // the number of registers, but must be an ubound on the number of SSE
2368 // registers used and is in the range 0 - 8 inclusive.
2370 // Count the number of XMM registers allocated.
2371 static const uint16_t XMMArgRegs[] = {
2372 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2373 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2375 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2376 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2377 && "SSE registers cannot be used when SSE is disabled");
2379 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2380 DAG.getConstant(NumXMMRegs, MVT::i8)));
2383 // For tail calls lower the arguments to the 'real' stack slot.
2385 // Force all the incoming stack arguments to be loaded from the stack
2386 // before any new outgoing arguments are stored to the stack, because the
2387 // outgoing stack slots may alias the incoming argument stack slots, and
2388 // the alias isn't otherwise explicit. This is slightly more conservative
2389 // than necessary, because it means that each store effectively depends
2390 // on every argument instead of just those arguments it would clobber.
2391 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2393 SmallVector<SDValue, 8> MemOpChains2;
2396 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2397 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2398 CCValAssign &VA = ArgLocs[i];
2401 assert(VA.isMemLoc());
2402 SDValue Arg = OutVals[i];
2403 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2404 // Create frame index.
2405 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2406 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2407 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2408 FIN = DAG.getFrameIndex(FI, getPointerTy());
2410 if (Flags.isByVal()) {
2411 // Copy relative to framepointer.
2412 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2413 if (StackPtr.getNode() == 0)
2414 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2416 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2418 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2422 // Store relative to framepointer.
2423 MemOpChains2.push_back(
2424 DAG.getStore(ArgChain, dl, Arg, FIN,
2425 MachinePointerInfo::getFixedStack(FI),
2431 if (!MemOpChains2.empty())
2432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433 &MemOpChains2[0], MemOpChains2.size());
2435 // Store the return address to the appropriate stack slot.
2436 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2440 // Build a sequence of copy-to-reg nodes chained together with token chain
2441 // and flag operands which copy the outgoing args into registers.
2443 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2444 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2445 RegsToPass[i].second, InFlag);
2446 InFlag = Chain.getValue(1);
2449 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2450 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2451 // In the 64-bit large code model, we have to make all calls
2452 // through a register, since the call instruction's 32-bit
2453 // pc-relative offset may not be large enough to hold the whole
2455 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2456 // If the callee is a GlobalAddress node (quite common, every direct call
2457 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2460 // We should use extra load for direct calls to dllimported functions in
2462 const GlobalValue *GV = G->getGlobal();
2463 if (!GV->hasDLLImportLinkage()) {
2464 unsigned char OpFlags = 0;
2465 bool ExtraLoad = false;
2466 unsigned WrapperKind = ISD::DELETED_NODE;
2468 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2469 // external symbols most go through the PLT in PIC mode. If the symbol
2470 // has hidden or protected visibility, or if it is static or local, then
2471 // we don't need to use the PLT - we can directly call it.
2472 if (Subtarget->isTargetELF() &&
2473 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2474 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2475 OpFlags = X86II::MO_PLT;
2476 } else if (Subtarget->isPICStyleStubAny() &&
2477 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2478 (!Subtarget->getTargetTriple().isMacOSX() ||
2479 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2480 // PC-relative references to external symbols should go through $stub,
2481 // unless we're building with the leopard linker or later, which
2482 // automatically synthesizes these stubs.
2483 OpFlags = X86II::MO_DARWIN_STUB;
2484 } else if (Subtarget->isPICStyleRIPRel() &&
2485 isa<Function>(GV) &&
2486 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2487 // If the function is marked as non-lazy, generate an indirect call
2488 // which loads from the GOT directly. This avoids runtime overhead
2489 // at the cost of eager binding (and one extra byte of encoding).
2490 OpFlags = X86II::MO_GOTPCREL;
2491 WrapperKind = X86ISD::WrapperRIP;
2495 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2496 G->getOffset(), OpFlags);
2498 // Add a wrapper if needed.
2499 if (WrapperKind != ISD::DELETED_NODE)
2500 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2501 // Add extra indirection if needed.
2503 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2504 MachinePointerInfo::getGOT(),
2505 false, false, false, 0);
2507 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2508 unsigned char OpFlags = 0;
2510 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2511 // external symbols should go through the PLT.
2512 if (Subtarget->isTargetELF() &&
2513 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2514 OpFlags = X86II::MO_PLT;
2515 } else if (Subtarget->isPICStyleStubAny() &&
2516 (!Subtarget->getTargetTriple().isMacOSX() ||
2517 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2518 // PC-relative references to external symbols should go through $stub,
2519 // unless we're building with the leopard linker or later, which
2520 // automatically synthesizes these stubs.
2521 OpFlags = X86II::MO_DARWIN_STUB;
2524 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2528 // Returns a chain & a flag for retval copy to use.
2529 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2530 SmallVector<SDValue, 8> Ops;
2532 if (!IsSibcall && isTailCall) {
2533 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2534 DAG.getIntPtrConstant(0, true), InFlag);
2535 InFlag = Chain.getValue(1);
2538 Ops.push_back(Chain);
2539 Ops.push_back(Callee);
2542 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2544 // Add argument registers to the end of the list so that they are known live
2546 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2547 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2548 RegsToPass[i].second.getValueType()));
2550 // Add a register mask operand representing the call-preserved registers.
2551 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2552 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2553 assert(Mask && "Missing call preserved mask for calling convention");
2554 Ops.push_back(DAG.getRegisterMask(Mask));
2556 if (InFlag.getNode())
2557 Ops.push_back(InFlag);
2561 //// If this is the first return lowered for this function, add the regs
2562 //// to the liveout set for the function.
2563 // This isn't right, although it's probably harmless on x86; liveouts
2564 // should be computed from returns not tail calls. Consider a void
2565 // function making a tail call to a function returning int.
2566 return DAG.getNode(X86ISD::TC_RETURN, dl,
2567 NodeTys, &Ops[0], Ops.size());
2570 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2571 InFlag = Chain.getValue(1);
2573 // Create the CALLSEQ_END node.
2574 unsigned NumBytesForCalleeToPush;
2575 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2576 getTargetMachine().Options.GuaranteedTailCallOpt))
2577 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2578 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2579 SR == StackStructReturn)
2580 // If this is a call to a struct-return function, the callee
2581 // pops the hidden struct pointer, so we have to push it back.
2582 // This is common for Darwin/X86, Linux & Mingw32 targets.
2583 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2584 NumBytesForCalleeToPush = 4;
2586 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2588 // Returns a flag for retval copy to use.
2590 Chain = DAG.getCALLSEQ_END(Chain,
2591 DAG.getIntPtrConstant(NumBytes, true),
2592 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2595 InFlag = Chain.getValue(1);
2598 // Handle result values, copying them out of physregs into vregs that we
2600 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2601 Ins, dl, DAG, InVals);
2605 //===----------------------------------------------------------------------===//
2606 // Fast Calling Convention (tail call) implementation
2607 //===----------------------------------------------------------------------===//
2609 // Like std call, callee cleans arguments, convention except that ECX is
2610 // reserved for storing the tail called function address. Only 2 registers are
2611 // free for argument passing (inreg). Tail call optimization is performed
2613 // * tailcallopt is enabled
2614 // * caller/callee are fastcc
2615 // On X86_64 architecture with GOT-style position independent code only local
2616 // (within module) calls are supported at the moment.
2617 // To keep the stack aligned according to platform abi the function
2618 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2619 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2620 // If a tail called function callee has more arguments than the caller the
2621 // caller needs to make sure that there is room to move the RETADDR to. This is
2622 // achieved by reserving an area the size of the argument delta right after the
2623 // original REtADDR, but before the saved framepointer or the spilled registers
2624 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2636 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2637 /// for a 16 byte align requirement.
2639 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2640 SelectionDAG& DAG) const {
2641 MachineFunction &MF = DAG.getMachineFunction();
2642 const TargetMachine &TM = MF.getTarget();
2643 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2644 unsigned StackAlignment = TFI.getStackAlignment();
2645 uint64_t AlignMask = StackAlignment - 1;
2646 int64_t Offset = StackSize;
2647 uint64_t SlotSize = TD->getPointerSize();
2648 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2649 // Number smaller than 12 so just add the difference.
2650 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2652 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2653 Offset = ((~AlignMask) & Offset) + StackAlignment +
2654 (StackAlignment-SlotSize);
2659 /// MatchingStackOffset - Return true if the given stack call argument is
2660 /// already available in the same position (relatively) of the caller's
2661 /// incoming argument stack.
2663 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2664 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2665 const X86InstrInfo *TII) {
2666 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2668 if (Arg.getOpcode() == ISD::CopyFromReg) {
2669 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2670 if (!TargetRegisterInfo::isVirtualRegister(VR))
2672 MachineInstr *Def = MRI->getVRegDef(VR);
2675 if (!Flags.isByVal()) {
2676 if (!TII->isLoadFromStackSlot(Def, FI))
2679 unsigned Opcode = Def->getOpcode();
2680 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2681 Def->getOperand(1).isFI()) {
2682 FI = Def->getOperand(1).getIndex();
2683 Bytes = Flags.getByValSize();
2687 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2688 if (Flags.isByVal())
2689 // ByVal argument is passed in as a pointer but it's now being
2690 // dereferenced. e.g.
2691 // define @foo(%struct.X* %A) {
2692 // tail call @bar(%struct.X* byval %A)
2695 SDValue Ptr = Ld->getBasePtr();
2696 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2699 FI = FINode->getIndex();
2700 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2701 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2702 FI = FINode->getIndex();
2703 Bytes = Flags.getByValSize();
2707 assert(FI != INT_MAX);
2708 if (!MFI->isFixedObjectIndex(FI))
2710 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2713 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2714 /// for tail call optimization. Targets which want to do tail call
2715 /// optimization should implement this function.
2717 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2718 CallingConv::ID CalleeCC,
2720 bool isCalleeStructRet,
2721 bool isCallerStructRet,
2722 const SmallVectorImpl<ISD::OutputArg> &Outs,
2723 const SmallVectorImpl<SDValue> &OutVals,
2724 const SmallVectorImpl<ISD::InputArg> &Ins,
2725 SelectionDAG& DAG) const {
2726 if (!IsTailCallConvention(CalleeCC) &&
2727 CalleeCC != CallingConv::C)
2730 // If -tailcallopt is specified, make fastcc functions tail-callable.
2731 const MachineFunction &MF = DAG.getMachineFunction();
2732 const Function *CallerF = DAG.getMachineFunction().getFunction();
2733 CallingConv::ID CallerCC = CallerF->getCallingConv();
2734 bool CCMatch = CallerCC == CalleeCC;
2736 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2737 if (IsTailCallConvention(CalleeCC) && CCMatch)
2742 // Look for obvious safe cases to perform tail call optimization that do not
2743 // require ABI changes. This is what gcc calls sibcall.
2745 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2746 // emit a special epilogue.
2747 if (RegInfo->needsStackRealignment(MF))
2750 // Also avoid sibcall optimization if either caller or callee uses struct
2751 // return semantics.
2752 if (isCalleeStructRet || isCallerStructRet)
2755 // An stdcall caller is expected to clean up its arguments; the callee
2756 // isn't going to do that.
2757 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2760 // Do not sibcall optimize vararg calls unless all arguments are passed via
2762 if (isVarArg && !Outs.empty()) {
2764 // Optimizing for varargs on Win64 is unlikely to be safe without
2765 // additional testing.
2766 if (Subtarget->isTargetWin64())
2769 SmallVector<CCValAssign, 16> ArgLocs;
2770 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2771 getTargetMachine(), ArgLocs, *DAG.getContext());
2773 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2774 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2775 if (!ArgLocs[i].isRegLoc())
2779 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2780 // stack. Therefore, if it's not used by the call it is not safe to optimize
2781 // this into a sibcall.
2782 bool Unused = false;
2783 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2790 SmallVector<CCValAssign, 16> RVLocs;
2791 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2792 getTargetMachine(), RVLocs, *DAG.getContext());
2793 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2794 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2795 CCValAssign &VA = RVLocs[i];
2796 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2801 // If the calling conventions do not match, then we'd better make sure the
2802 // results are returned in the same way as what the caller expects.
2804 SmallVector<CCValAssign, 16> RVLocs1;
2805 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2806 getTargetMachine(), RVLocs1, *DAG.getContext());
2807 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2809 SmallVector<CCValAssign, 16> RVLocs2;
2810 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2811 getTargetMachine(), RVLocs2, *DAG.getContext());
2812 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2814 if (RVLocs1.size() != RVLocs2.size())
2816 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2817 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2819 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2821 if (RVLocs1[i].isRegLoc()) {
2822 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2825 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2831 // If the callee takes no arguments then go on to check the results of the
2833 if (!Outs.empty()) {
2834 // Check if stack adjustment is needed. For now, do not do this if any
2835 // argument is passed on the stack.
2836 SmallVector<CCValAssign, 16> ArgLocs;
2837 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2838 getTargetMachine(), ArgLocs, *DAG.getContext());
2840 // Allocate shadow area for Win64
2841 if (Subtarget->isTargetWin64()) {
2842 CCInfo.AllocateStack(32, 8);
2845 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2846 if (CCInfo.getNextStackOffset()) {
2847 MachineFunction &MF = DAG.getMachineFunction();
2848 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2851 // Check if the arguments are already laid out in the right way as
2852 // the caller's fixed stack objects.
2853 MachineFrameInfo *MFI = MF.getFrameInfo();
2854 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2855 const X86InstrInfo *TII =
2856 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2857 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2858 CCValAssign &VA = ArgLocs[i];
2859 SDValue Arg = OutVals[i];
2860 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2861 if (VA.getLocInfo() == CCValAssign::Indirect)
2863 if (!VA.isRegLoc()) {
2864 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2871 // If the tailcall address may be in a register, then make sure it's
2872 // possible to register allocate for it. In 32-bit, the call address can
2873 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2874 // callee-saved registers are restored. These happen to be the same
2875 // registers used to pass 'inreg' arguments so watch out for those.
2876 if (!Subtarget->is64Bit() &&
2877 !isa<GlobalAddressSDNode>(Callee) &&
2878 !isa<ExternalSymbolSDNode>(Callee)) {
2879 unsigned NumInRegs = 0;
2880 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2881 CCValAssign &VA = ArgLocs[i];
2884 unsigned Reg = VA.getLocReg();
2887 case X86::EAX: case X86::EDX: case X86::ECX:
2888 if (++NumInRegs == 3)
2900 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2901 const TargetLibraryInfo *libInfo) const {
2902 return X86::createFastISel(funcInfo, libInfo);
2906 //===----------------------------------------------------------------------===//
2907 // Other Lowering Hooks
2908 //===----------------------------------------------------------------------===//
2910 static bool MayFoldLoad(SDValue Op) {
2911 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2914 static bool MayFoldIntoStore(SDValue Op) {
2915 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2918 static bool isTargetShuffle(unsigned Opcode) {
2920 default: return false;
2921 case X86ISD::PSHUFD:
2922 case X86ISD::PSHUFHW:
2923 case X86ISD::PSHUFLW:
2925 case X86ISD::PALIGN:
2926 case X86ISD::MOVLHPS:
2927 case X86ISD::MOVLHPD:
2928 case X86ISD::MOVHLPS:
2929 case X86ISD::MOVLPS:
2930 case X86ISD::MOVLPD:
2931 case X86ISD::MOVSHDUP:
2932 case X86ISD::MOVSLDUP:
2933 case X86ISD::MOVDDUP:
2936 case X86ISD::UNPCKL:
2937 case X86ISD::UNPCKH:
2938 case X86ISD::VPERMILP:
2939 case X86ISD::VPERM2X128:
2940 case X86ISD::VPERMI:
2945 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2946 SDValue V1, SelectionDAG &DAG) {
2948 default: llvm_unreachable("Unknown x86 shuffle node");
2949 case X86ISD::MOVSHDUP:
2950 case X86ISD::MOVSLDUP:
2951 case X86ISD::MOVDDUP:
2952 return DAG.getNode(Opc, dl, VT, V1);
2956 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2957 SDValue V1, unsigned TargetMask,
2958 SelectionDAG &DAG) {
2960 default: llvm_unreachable("Unknown x86 shuffle node");
2961 case X86ISD::PSHUFD:
2962 case X86ISD::PSHUFHW:
2963 case X86ISD::PSHUFLW:
2964 case X86ISD::VPERMILP:
2965 case X86ISD::VPERMI:
2966 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2970 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2971 SDValue V1, SDValue V2, unsigned TargetMask,
2972 SelectionDAG &DAG) {
2974 default: llvm_unreachable("Unknown x86 shuffle node");
2975 case X86ISD::PALIGN:
2977 case X86ISD::VPERM2X128:
2978 return DAG.getNode(Opc, dl, VT, V1, V2,
2979 DAG.getConstant(TargetMask, MVT::i8));
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2986 default: llvm_unreachable("Unknown x86 shuffle node");
2987 case X86ISD::MOVLHPS:
2988 case X86ISD::MOVLHPD:
2989 case X86ISD::MOVHLPS:
2990 case X86ISD::MOVLPS:
2991 case X86ISD::MOVLPD:
2994 case X86ISD::UNPCKL:
2995 case X86ISD::UNPCKH:
2996 return DAG.getNode(Opc, dl, VT, V1, V2);
3000 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3001 MachineFunction &MF = DAG.getMachineFunction();
3002 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3003 int ReturnAddrIndex = FuncInfo->getRAIndex();
3005 if (ReturnAddrIndex == 0) {
3006 // Set up a frame object for the return address.
3007 uint64_t SlotSize = TD->getPointerSize();
3008 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3010 FuncInfo->setRAIndex(ReturnAddrIndex);
3013 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3017 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3018 bool hasSymbolicDisplacement) {
3019 // Offset should fit into 32 bit immediate field.
3020 if (!isInt<32>(Offset))
3023 // If we don't have a symbolic displacement - we don't have any extra
3025 if (!hasSymbolicDisplacement)
3028 // FIXME: Some tweaks might be needed for medium code model.
3029 if (M != CodeModel::Small && M != CodeModel::Kernel)
3032 // For small code model we assume that latest object is 16MB before end of 31
3033 // bits boundary. We may also accept pretty large negative constants knowing
3034 // that all objects are in the positive half of address space.
3035 if (M == CodeModel::Small && Offset < 16*1024*1024)
3038 // For kernel code model we know that all object resist in the negative half
3039 // of 32bits address space. We may not accept negative offsets, since they may
3040 // be just off and we may accept pretty large positive ones.
3041 if (M == CodeModel::Kernel && Offset > 0)
3047 /// isCalleePop - Determines whether the callee is required to pop its
3048 /// own arguments. Callee pop is necessary to support tail calls.
3049 bool X86::isCalleePop(CallingConv::ID CallingConv,
3050 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3054 switch (CallingConv) {
3057 case CallingConv::X86_StdCall:
3059 case CallingConv::X86_FastCall:
3061 case CallingConv::X86_ThisCall:
3063 case CallingConv::Fast:
3065 case CallingConv::GHC:
3070 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3071 /// specific condition code, returning the condition code and the LHS/RHS of the
3072 /// comparison to make.
3073 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3074 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3076 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3077 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3078 // X > -1 -> X == 0, jump !sign.
3079 RHS = DAG.getConstant(0, RHS.getValueType());
3080 return X86::COND_NS;
3082 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3083 // X < 0 -> X == 0, jump on sign.
3086 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3088 RHS = DAG.getConstant(0, RHS.getValueType());
3089 return X86::COND_LE;
3093 switch (SetCCOpcode) {
3094 default: llvm_unreachable("Invalid integer condition!");
3095 case ISD::SETEQ: return X86::COND_E;
3096 case ISD::SETGT: return X86::COND_G;
3097 case ISD::SETGE: return X86::COND_GE;
3098 case ISD::SETLT: return X86::COND_L;
3099 case ISD::SETLE: return X86::COND_LE;
3100 case ISD::SETNE: return X86::COND_NE;
3101 case ISD::SETULT: return X86::COND_B;
3102 case ISD::SETUGT: return X86::COND_A;
3103 case ISD::SETULE: return X86::COND_BE;
3104 case ISD::SETUGE: return X86::COND_AE;
3108 // First determine if it is required or is profitable to flip the operands.
3110 // If LHS is a foldable load, but RHS is not, flip the condition.
3111 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3112 !ISD::isNON_EXTLoad(RHS.getNode())) {
3113 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3114 std::swap(LHS, RHS);
3117 switch (SetCCOpcode) {
3123 std::swap(LHS, RHS);
3127 // On a floating point condition, the flags are set as follows:
3129 // 0 | 0 | 0 | X > Y
3130 // 0 | 0 | 1 | X < Y
3131 // 1 | 0 | 0 | X == Y
3132 // 1 | 1 | 1 | unordered
3133 switch (SetCCOpcode) {
3134 default: llvm_unreachable("Condcode should be pre-legalized away");
3136 case ISD::SETEQ: return X86::COND_E;
3137 case ISD::SETOLT: // flipped
3139 case ISD::SETGT: return X86::COND_A;
3140 case ISD::SETOLE: // flipped
3142 case ISD::SETGE: return X86::COND_AE;
3143 case ISD::SETUGT: // flipped
3145 case ISD::SETLT: return X86::COND_B;
3146 case ISD::SETUGE: // flipped
3148 case ISD::SETLE: return X86::COND_BE;
3150 case ISD::SETNE: return X86::COND_NE;
3151 case ISD::SETUO: return X86::COND_P;
3152 case ISD::SETO: return X86::COND_NP;
3154 case ISD::SETUNE: return X86::COND_INVALID;
3158 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3159 /// code. Current x86 isa includes the following FP cmov instructions:
3160 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3161 static bool hasFPCMov(unsigned X86CC) {
3177 /// isFPImmLegal - Returns true if the target can instruction select the
3178 /// specified FP immediate natively. If false, the legalizer will
3179 /// materialize the FP immediate as a load from a constant pool.
3180 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3181 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3182 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3188 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3189 /// the specified range (L, H].
3190 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3191 return (Val < 0) || (Val >= Low && Val < Hi);
3194 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3195 /// specified value.
3196 static bool isUndefOrEqual(int Val, int CmpVal) {
3197 if (Val < 0 || Val == CmpVal)
3202 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3203 /// from position Pos and ending in Pos+Size, falls within the specified
3204 /// sequential range (L, L+Pos]. or is undef.
3205 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3206 unsigned Pos, unsigned Size, int Low) {
3207 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3208 if (!isUndefOrEqual(Mask[i], Low))
3213 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3214 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3215 /// the second operand.
3216 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3217 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3218 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3219 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3220 return (Mask[0] < 2 && Mask[1] < 2);
3224 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3225 /// is suitable for input to PSHUFHW.
3226 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3227 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3230 // Lower quadword copied in order or undef.
3231 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3234 // Upper quadword shuffled.
3235 for (unsigned i = 4; i != 8; ++i)
3236 if (!isUndefOrInRange(Mask[i], 4, 8))
3239 if (VT == MVT::v16i16) {
3240 // Lower quadword copied in order or undef.
3241 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3244 // Upper quadword shuffled.
3245 for (unsigned i = 12; i != 16; ++i)
3246 if (!isUndefOrInRange(Mask[i], 12, 16))
3253 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3254 /// is suitable for input to PSHUFLW.
3255 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3256 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3259 // Upper quadword copied in order.
3260 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3263 // Lower quadword shuffled.
3264 for (unsigned i = 0; i != 4; ++i)
3265 if (!isUndefOrInRange(Mask[i], 0, 4))
3268 if (VT == MVT::v16i16) {
3269 // Upper quadword copied in order.
3270 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3273 // Lower quadword shuffled.
3274 for (unsigned i = 8; i != 12; ++i)
3275 if (!isUndefOrInRange(Mask[i], 8, 12))
3282 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3283 /// is suitable for input to PALIGNR.
3284 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3285 const X86Subtarget *Subtarget) {
3286 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3287 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3290 unsigned NumElts = VT.getVectorNumElements();
3291 unsigned NumLanes = VT.getSizeInBits()/128;
3292 unsigned NumLaneElts = NumElts/NumLanes;
3294 // Do not handle 64-bit element shuffles with palignr.
3295 if (NumLaneElts == 2)
3298 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3300 for (i = 0; i != NumLaneElts; ++i) {
3305 // Lane is all undef, go to next lane
3306 if (i == NumLaneElts)
3309 int Start = Mask[i+l];
3311 // Make sure its in this lane in one of the sources
3312 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3313 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3316 // If not lane 0, then we must match lane 0
3317 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3320 // Correct second source to be contiguous with first source
3321 if (Start >= (int)NumElts)
3322 Start -= NumElts - NumLaneElts;
3324 // Make sure we're shifting in the right direction.
3325 if (Start <= (int)(i+l))
3330 // Check the rest of the elements to see if they are consecutive.
3331 for (++i; i != NumLaneElts; ++i) {
3332 int Idx = Mask[i+l];
3334 // Make sure its in this lane
3335 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3336 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3339 // If not lane 0, then we must match lane 0
3340 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3343 if (Idx >= (int)NumElts)
3344 Idx -= NumElts - NumLaneElts;
3346 if (!isUndefOrEqual(Idx, Start+i))
3355 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3356 /// the two vector operands have swapped position.
3357 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3358 unsigned NumElems) {
3359 for (unsigned i = 0; i != NumElems; ++i) {
3363 else if (idx < (int)NumElems)
3364 Mask[i] = idx + NumElems;
3366 Mask[i] = idx - NumElems;
3370 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3371 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3372 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3373 /// reverse of what x86 shuffles want.
3374 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3375 bool Commuted = false) {
3376 if (!HasAVX && VT.getSizeInBits() == 256)
3379 unsigned NumElems = VT.getVectorNumElements();
3380 unsigned NumLanes = VT.getSizeInBits()/128;
3381 unsigned NumLaneElems = NumElems/NumLanes;
3383 if (NumLaneElems != 2 && NumLaneElems != 4)
3386 // VSHUFPSY divides the resulting vector into 4 chunks.
3387 // The sources are also splitted into 4 chunks, and each destination
3388 // chunk must come from a different source chunk.
3390 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3391 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3393 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3394 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3396 // VSHUFPDY divides the resulting vector into 4 chunks.
3397 // The sources are also splitted into 4 chunks, and each destination
3398 // chunk must come from a different source chunk.
3400 // SRC1 => X3 X2 X1 X0
3401 // SRC2 => Y3 Y2 Y1 Y0
3403 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3405 unsigned HalfLaneElems = NumLaneElems/2;
3406 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3407 for (unsigned i = 0; i != NumLaneElems; ++i) {
3408 int Idx = Mask[i+l];
3409 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3410 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3412 // For VSHUFPSY, the mask of the second half must be the same as the
3413 // first but with the appropriate offsets. This works in the same way as
3414 // VPERMILPS works with masks.
3415 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3417 if (!isUndefOrEqual(Idx, Mask[i]+l))
3425 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3426 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3427 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3428 unsigned NumElems = VT.getVectorNumElements();
3430 if (VT.getSizeInBits() != 128)
3436 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3437 return isUndefOrEqual(Mask[0], 6) &&
3438 isUndefOrEqual(Mask[1], 7) &&
3439 isUndefOrEqual(Mask[2], 2) &&
3440 isUndefOrEqual(Mask[3], 3);
3443 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3444 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3446 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3447 unsigned NumElems = VT.getVectorNumElements();
3449 if (VT.getSizeInBits() != 128)
3455 return isUndefOrEqual(Mask[0], 2) &&
3456 isUndefOrEqual(Mask[1], 3) &&
3457 isUndefOrEqual(Mask[2], 2) &&
3458 isUndefOrEqual(Mask[3], 3);
3461 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3462 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3463 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3464 if (VT.getSizeInBits() != 128)
3467 unsigned NumElems = VT.getVectorNumElements();
3469 if (NumElems != 2 && NumElems != 4)
3472 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3473 if (!isUndefOrEqual(Mask[i], i + NumElems))
3476 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3477 if (!isUndefOrEqual(Mask[i], i))
3483 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3484 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3485 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3486 unsigned NumElems = VT.getVectorNumElements();
3488 if ((NumElems != 2 && NumElems != 4)
3489 || VT.getSizeInBits() > 128)
3492 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3493 if (!isUndefOrEqual(Mask[i], i))
3496 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3497 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3504 // Some special combinations that can be optimized.
3507 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3508 SelectionDAG &DAG) {
3509 EVT VT = SVOp->getValueType(0);
3510 DebugLoc dl = SVOp->getDebugLoc();
3512 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3515 ArrayRef<int> Mask = SVOp->getMask();
3517 // These are the special masks that may be optimized.
3518 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3519 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3520 bool MatchEvenMask = true;
3521 bool MatchOddMask = true;
3522 for (int i=0; i<8; ++i) {
3523 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3524 MatchEvenMask = false;
3525 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3526 MatchOddMask = false;
3528 static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3529 static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3531 const int *CompactionMask;
3533 CompactionMask = CompactionMaskEven;
3534 else if (MatchOddMask)
3535 CompactionMask = CompactionMaskOdd;
3539 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3541 SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3542 UndefNode, CompactionMask);
3543 SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3544 UndefNode, CompactionMask);
3545 static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3546 return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3549 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3550 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3551 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3552 bool HasAVX2, bool V2IsSplat = false) {
3553 unsigned NumElts = VT.getVectorNumElements();
3555 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3556 "Unsupported vector type for unpckh");
3558 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3559 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3562 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3563 // independently on 128-bit lanes.
3564 unsigned NumLanes = VT.getSizeInBits()/128;
3565 unsigned NumLaneElts = NumElts/NumLanes;
3567 for (unsigned l = 0; l != NumLanes; ++l) {
3568 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3569 i != (l+1)*NumLaneElts;
3572 int BitI1 = Mask[i+1];
3573 if (!isUndefOrEqual(BitI, j))
3576 if (!isUndefOrEqual(BitI1, NumElts))
3579 if (!isUndefOrEqual(BitI1, j + NumElts))
3588 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3589 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3590 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3591 bool HasAVX2, bool V2IsSplat = false) {
3592 unsigned NumElts = VT.getVectorNumElements();
3594 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3595 "Unsupported vector type for unpckh");
3597 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3598 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3601 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3602 // independently on 128-bit lanes.
3603 unsigned NumLanes = VT.getSizeInBits()/128;
3604 unsigned NumLaneElts = NumElts/NumLanes;
3606 for (unsigned l = 0; l != NumLanes; ++l) {
3607 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3608 i != (l+1)*NumLaneElts; i += 2, ++j) {
3610 int BitI1 = Mask[i+1];
3611 if (!isUndefOrEqual(BitI, j))
3614 if (isUndefOrEqual(BitI1, NumElts))
3617 if (!isUndefOrEqual(BitI1, j+NumElts))
3625 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3626 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3628 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3630 unsigned NumElts = VT.getVectorNumElements();
3632 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3633 "Unsupported vector type for unpckh");
3635 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3636 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3639 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3640 // FIXME: Need a better way to get rid of this, there's no latency difference
3641 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3642 // the former later. We should also remove the "_undef" special mask.
3643 if (NumElts == 4 && VT.getSizeInBits() == 256)
3646 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3647 // independently on 128-bit lanes.
3648 unsigned NumLanes = VT.getSizeInBits()/128;
3649 unsigned NumLaneElts = NumElts/NumLanes;
3651 for (unsigned l = 0; l != NumLanes; ++l) {
3652 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3653 i != (l+1)*NumLaneElts;
3656 int BitI1 = Mask[i+1];
3658 if (!isUndefOrEqual(BitI, j))
3660 if (!isUndefOrEqual(BitI1, j))
3668 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3669 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3671 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3672 unsigned NumElts = VT.getVectorNumElements();
3674 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3675 "Unsupported vector type for unpckh");
3677 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3678 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3681 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3682 // independently on 128-bit lanes.
3683 unsigned NumLanes = VT.getSizeInBits()/128;
3684 unsigned NumLaneElts = NumElts/NumLanes;
3686 for (unsigned l = 0; l != NumLanes; ++l) {
3687 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3688 i != (l+1)*NumLaneElts; i += 2, ++j) {
3690 int BitI1 = Mask[i+1];
3691 if (!isUndefOrEqual(BitI, j))
3693 if (!isUndefOrEqual(BitI1, j))
3700 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3701 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3702 /// MOVSD, and MOVD, i.e. setting the lowest element.
3703 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3704 if (VT.getVectorElementType().getSizeInBits() < 32)
3706 if (VT.getSizeInBits() == 256)
3709 unsigned NumElts = VT.getVectorNumElements();
3711 if (!isUndefOrEqual(Mask[0], NumElts))
3714 for (unsigned i = 1; i != NumElts; ++i)
3715 if (!isUndefOrEqual(Mask[i], i))
3721 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3722 /// as permutations between 128-bit chunks or halves. As an example: this
3724 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3725 /// The first half comes from the second half of V1 and the second half from the
3726 /// the second half of V2.
3727 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3728 if (!HasAVX || VT.getSizeInBits() != 256)
3731 // The shuffle result is divided into half A and half B. In total the two
3732 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3733 // B must come from C, D, E or F.
3734 unsigned HalfSize = VT.getVectorNumElements()/2;
3735 bool MatchA = false, MatchB = false;
3737 // Check if A comes from one of C, D, E, F.
3738 for (unsigned Half = 0; Half != 4; ++Half) {
3739 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3745 // Check if B comes from one of C, D, E, F.
3746 for (unsigned Half = 0; Half != 4; ++Half) {
3747 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3753 return MatchA && MatchB;
3756 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3757 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3758 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3759 EVT VT = SVOp->getValueType(0);
3761 unsigned HalfSize = VT.getVectorNumElements()/2;
3763 unsigned FstHalf = 0, SndHalf = 0;
3764 for (unsigned i = 0; i < HalfSize; ++i) {
3765 if (SVOp->getMaskElt(i) > 0) {
3766 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3770 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3771 if (SVOp->getMaskElt(i) > 0) {
3772 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3777 return (FstHalf | (SndHalf << 4));
3780 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3782 /// Note that VPERMIL mask matching is different depending whether theunderlying
3783 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3784 /// to the same elements of the low, but to the higher half of the source.
3785 /// In VPERMILPD the two lanes could be shuffled independently of each other
3786 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3787 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3791 unsigned NumElts = VT.getVectorNumElements();
3792 // Only match 256-bit with 32/64-bit types
3793 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3796 unsigned NumLanes = VT.getSizeInBits()/128;
3797 unsigned LaneSize = NumElts/NumLanes;
3798 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3799 for (unsigned i = 0; i != LaneSize; ++i) {
3800 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3802 if (NumElts != 8 || l == 0)
3804 // VPERMILPS handling
3807 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3815 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3816 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3817 /// element of vector 2 and the other elements to come from vector 1 in order.
3818 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3819 bool V2IsSplat = false, bool V2IsUndef = false) {
3820 unsigned NumOps = VT.getVectorNumElements();
3821 if (VT.getSizeInBits() == 256)
3823 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3826 if (!isUndefOrEqual(Mask[0], 0))
3829 for (unsigned i = 1; i != NumOps; ++i)
3830 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3831 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3832 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3838 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3839 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3840 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3841 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3842 const X86Subtarget *Subtarget) {
3843 if (!Subtarget->hasSSE3())
3846 unsigned NumElems = VT.getVectorNumElements();
3848 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3849 (VT.getSizeInBits() == 256 && NumElems != 8))
3852 // "i+1" is the value the indexed mask element must have
3853 for (unsigned i = 0; i != NumElems; i += 2)
3854 if (!isUndefOrEqual(Mask[i], i+1) ||
3855 !isUndefOrEqual(Mask[i+1], i+1))
3861 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3862 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3863 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3864 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3865 const X86Subtarget *Subtarget) {
3866 if (!Subtarget->hasSSE3())
3869 unsigned NumElems = VT.getVectorNumElements();
3871 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3872 (VT.getSizeInBits() == 256 && NumElems != 8))
3875 // "i" is the value the indexed mask element must have
3876 for (unsigned i = 0; i != NumElems; i += 2)
3877 if (!isUndefOrEqual(Mask[i], i) ||
3878 !isUndefOrEqual(Mask[i+1], i))
3884 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3885 /// specifies a shuffle of elements that is suitable for input to 256-bit
3886 /// version of MOVDDUP.
3887 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3888 unsigned NumElts = VT.getVectorNumElements();
3890 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3893 for (unsigned i = 0; i != NumElts/2; ++i)
3894 if (!isUndefOrEqual(Mask[i], 0))
3896 for (unsigned i = NumElts/2; i != NumElts; ++i)
3897 if (!isUndefOrEqual(Mask[i], NumElts/2))
3902 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3903 /// specifies a shuffle of elements that is suitable for input to 128-bit
3904 /// version of MOVDDUP.
3905 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3906 if (VT.getSizeInBits() != 128)
3909 unsigned e = VT.getVectorNumElements() / 2;
3910 for (unsigned i = 0; i != e; ++i)
3911 if (!isUndefOrEqual(Mask[i], i))
3913 for (unsigned i = 0; i != e; ++i)
3914 if (!isUndefOrEqual(Mask[e+i], i))
3919 /// isVEXTRACTF128Index - Return true if the specified
3920 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3921 /// suitable for input to VEXTRACTF128.
3922 bool X86::isVEXTRACTF128Index(SDNode *N) {
3923 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3926 // The index should be aligned on a 128-bit boundary.
3928 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3930 unsigned VL = N->getValueType(0).getVectorNumElements();
3931 unsigned VBits = N->getValueType(0).getSizeInBits();
3932 unsigned ElSize = VBits / VL;
3933 bool Result = (Index * ElSize) % 128 == 0;
3938 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3939 /// operand specifies a subvector insert that is suitable for input to
3941 bool X86::isVINSERTF128Index(SDNode *N) {
3942 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3945 // The index should be aligned on a 128-bit boundary.
3947 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3949 unsigned VL = N->getValueType(0).getVectorNumElements();
3950 unsigned VBits = N->getValueType(0).getSizeInBits();
3951 unsigned ElSize = VBits / VL;
3952 bool Result = (Index * ElSize) % 128 == 0;
3957 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3958 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3959 /// Handles 128-bit and 256-bit.
3960 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3961 EVT VT = N->getValueType(0);
3963 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3964 "Unsupported vector type for PSHUF/SHUFP");
3966 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3967 // independently on 128-bit lanes.
3968 unsigned NumElts = VT.getVectorNumElements();
3969 unsigned NumLanes = VT.getSizeInBits()/128;
3970 unsigned NumLaneElts = NumElts/NumLanes;
3972 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3973 "Only supports 2 or 4 elements per lane");
3975 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3977 for (unsigned i = 0; i != NumElts; ++i) {
3978 int Elt = N->getMaskElt(i);
3979 if (Elt < 0) continue;
3980 Elt &= NumLaneElts - 1;
3981 unsigned ShAmt = (i << Shift) % 8;
3982 Mask |= Elt << ShAmt;
3988 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3989 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3990 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3991 EVT VT = N->getValueType(0);
3993 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3994 "Unsupported vector type for PSHUFHW");
3996 unsigned NumElts = VT.getVectorNumElements();
3999 for (unsigned l = 0; l != NumElts; l += 8) {
4000 // 8 nodes per lane, but we only care about the last 4.
4001 for (unsigned i = 0; i < 4; ++i) {
4002 int Elt = N->getMaskElt(l+i+4);
4003 if (Elt < 0) continue;
4004 Elt &= 0x3; // only 2-bits.
4005 Mask |= Elt << (i * 2);
4012 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4013 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4014 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4015 EVT VT = N->getValueType(0);
4017 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4018 "Unsupported vector type for PSHUFHW");
4020 unsigned NumElts = VT.getVectorNumElements();
4023 for (unsigned l = 0; l != NumElts; l += 8) {
4024 // 8 nodes per lane, but we only care about the first 4.
4025 for (unsigned i = 0; i < 4; ++i) {
4026 int Elt = N->getMaskElt(l+i);
4027 if (Elt < 0) continue;
4028 Elt &= 0x3; // only 2-bits
4029 Mask |= Elt << (i * 2);
4036 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4037 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4038 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4039 EVT VT = SVOp->getValueType(0);
4040 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4042 unsigned NumElts = VT.getVectorNumElements();
4043 unsigned NumLanes = VT.getSizeInBits()/128;
4044 unsigned NumLaneElts = NumElts/NumLanes;
4048 for (i = 0; i != NumElts; ++i) {
4049 Val = SVOp->getMaskElt(i);
4053 if (Val >= (int)NumElts)
4054 Val -= NumElts - NumLaneElts;
4056 assert(Val - i > 0 && "PALIGNR imm should be positive");
4057 return (Val - i) * EltSize;
4060 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4061 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4063 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4064 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4065 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4068 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4070 EVT VecVT = N->getOperand(0).getValueType();
4071 EVT ElVT = VecVT.getVectorElementType();
4073 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4074 return Index / NumElemsPerChunk;
4077 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4078 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4080 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4081 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4082 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4085 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4087 EVT VecVT = N->getValueType(0);
4088 EVT ElVT = VecVT.getVectorElementType();
4090 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4091 return Index / NumElemsPerChunk;
4094 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4095 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4096 /// Handles 256-bit.
4097 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4098 EVT VT = N->getValueType(0);
4100 unsigned NumElts = VT.getVectorNumElements();
4102 assert((VT.is256BitVector() && NumElts == 4) &&
4103 "Unsupported vector type for VPERMQ/VPERMPD");
4106 for (unsigned i = 0; i != NumElts; ++i) {
4107 int Elt = N->getMaskElt(i);
4110 Mask |= Elt << (i*2);
4115 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4117 bool X86::isZeroNode(SDValue Elt) {
4118 return ((isa<ConstantSDNode>(Elt) &&
4119 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4120 (isa<ConstantFPSDNode>(Elt) &&
4121 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4124 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4125 /// their permute mask.
4126 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4127 SelectionDAG &DAG) {
4128 EVT VT = SVOp->getValueType(0);
4129 unsigned NumElems = VT.getVectorNumElements();
4130 SmallVector<int, 8> MaskVec;
4132 for (unsigned i = 0; i != NumElems; ++i) {
4133 int Idx = SVOp->getMaskElt(i);
4135 if (Idx < (int)NumElems)
4140 MaskVec.push_back(Idx);
4142 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4143 SVOp->getOperand(0), &MaskVec[0]);
4146 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4147 /// match movhlps. The lower half elements should come from upper half of
4148 /// V1 (and in order), and the upper half elements should come from the upper
4149 /// half of V2 (and in order).
4150 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4151 if (VT.getSizeInBits() != 128)
4153 if (VT.getVectorNumElements() != 4)
4155 for (unsigned i = 0, e = 2; i != e; ++i)
4156 if (!isUndefOrEqual(Mask[i], i+2))
4158 for (unsigned i = 2; i != 4; ++i)
4159 if (!isUndefOrEqual(Mask[i], i+4))
4164 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4165 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4167 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4168 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4170 N = N->getOperand(0).getNode();
4171 if (!ISD::isNON_EXTLoad(N))
4174 *LD = cast<LoadSDNode>(N);
4178 // Test whether the given value is a vector value which will be legalized
4180 static bool WillBeConstantPoolLoad(SDNode *N) {
4181 if (N->getOpcode() != ISD::BUILD_VECTOR)
4184 // Check for any non-constant elements.
4185 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4186 switch (N->getOperand(i).getNode()->getOpcode()) {
4188 case ISD::ConstantFP:
4195 // Vectors of all-zeros and all-ones are materialized with special
4196 // instructions rather than being loaded.
4197 return !ISD::isBuildVectorAllZeros(N) &&
4198 !ISD::isBuildVectorAllOnes(N);
4201 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4202 /// match movlp{s|d}. The lower half elements should come from lower half of
4203 /// V1 (and in order), and the upper half elements should come from the upper
4204 /// half of V2 (and in order). And since V1 will become the source of the
4205 /// MOVLP, it must be either a vector load or a scalar load to vector.
4206 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4207 ArrayRef<int> Mask, EVT VT) {
4208 if (VT.getSizeInBits() != 128)
4211 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4213 // Is V2 is a vector load, don't do this transformation. We will try to use
4214 // load folding shufps op.
4215 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4218 unsigned NumElems = VT.getVectorNumElements();
4220 if (NumElems != 2 && NumElems != 4)
4222 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4223 if (!isUndefOrEqual(Mask[i], i))
4225 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4226 if (!isUndefOrEqual(Mask[i], i+NumElems))
4231 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4233 static bool isSplatVector(SDNode *N) {
4234 if (N->getOpcode() != ISD::BUILD_VECTOR)
4237 SDValue SplatValue = N->getOperand(0);
4238 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4239 if (N->getOperand(i) != SplatValue)
4244 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4245 /// to an zero vector.
4246 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4247 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4248 SDValue V1 = N->getOperand(0);
4249 SDValue V2 = N->getOperand(1);
4250 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4251 for (unsigned i = 0; i != NumElems; ++i) {
4252 int Idx = N->getMaskElt(i);
4253 if (Idx >= (int)NumElems) {
4254 unsigned Opc = V2.getOpcode();
4255 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4257 if (Opc != ISD::BUILD_VECTOR ||
4258 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4260 } else if (Idx >= 0) {
4261 unsigned Opc = V1.getOpcode();
4262 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4264 if (Opc != ISD::BUILD_VECTOR ||
4265 !X86::isZeroNode(V1.getOperand(Idx)))
4272 /// getZeroVector - Returns a vector of specified type with all zero elements.
4274 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4275 SelectionDAG &DAG, DebugLoc dl) {
4276 assert(VT.isVector() && "Expected a vector type");
4277 unsigned Size = VT.getSizeInBits();
4279 // Always build SSE zero vectors as <4 x i32> bitcasted
4280 // to their dest type. This ensures they get CSE'd.
4282 if (Size == 128) { // SSE
4283 if (Subtarget->hasSSE2()) { // SSE2
4284 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4285 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4287 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4288 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4290 } else if (Size == 256) { // AVX
4291 if (Subtarget->hasAVX2()) { // AVX2
4292 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4293 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4294 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4296 // 256-bit logic and arithmetic instructions in AVX are all
4297 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4298 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4299 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4300 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4303 llvm_unreachable("Unexpected vector type");
4305 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4308 /// getOnesVector - Returns a vector of specified type with all bits set.
4309 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4310 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4311 /// Then bitcast to their original type, ensuring they get CSE'd.
4312 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4314 assert(VT.isVector() && "Expected a vector type");
4315 unsigned Size = VT.getSizeInBits();
4317 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4320 if (HasAVX2) { // AVX2
4321 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4322 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4324 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4325 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4327 } else if (Size == 128) {
4328 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4330 llvm_unreachable("Unexpected vector type");
4332 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4335 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4336 /// that point to V2 points to its first element.
4337 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4338 for (unsigned i = 0; i != NumElems; ++i) {
4339 if (Mask[i] > (int)NumElems) {
4345 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4346 /// operation of specified width.
4347 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4349 unsigned NumElems = VT.getVectorNumElements();
4350 SmallVector<int, 8> Mask;
4351 Mask.push_back(NumElems);
4352 for (unsigned i = 1; i != NumElems; ++i)
4354 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4357 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4358 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4360 unsigned NumElems = VT.getVectorNumElements();
4361 SmallVector<int, 8> Mask;
4362 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4364 Mask.push_back(i + NumElems);
4366 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4369 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4370 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4372 unsigned NumElems = VT.getVectorNumElements();
4373 SmallVector<int, 8> Mask;
4374 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4375 Mask.push_back(i + Half);
4376 Mask.push_back(i + NumElems + Half);
4378 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4381 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4382 // a generic shuffle instruction because the target has no such instructions.
4383 // Generate shuffles which repeat i16 and i8 several times until they can be
4384 // represented by v4f32 and then be manipulated by target suported shuffles.
4385 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4386 EVT VT = V.getValueType();
4387 int NumElems = VT.getVectorNumElements();
4388 DebugLoc dl = V.getDebugLoc();
4390 while (NumElems > 4) {
4391 if (EltNo < NumElems/2) {
4392 V = getUnpackl(DAG, dl, VT, V, V);
4394 V = getUnpackh(DAG, dl, VT, V, V);
4395 EltNo -= NumElems/2;
4402 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4403 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4404 EVT VT = V.getValueType();
4405 DebugLoc dl = V.getDebugLoc();
4406 unsigned Size = VT.getSizeInBits();
4409 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4410 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4411 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4413 } else if (Size == 256) {
4414 // To use VPERMILPS to splat scalars, the second half of indicies must
4415 // refer to the higher part, which is a duplication of the lower one,
4416 // because VPERMILPS can only handle in-lane permutations.
4417 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4418 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4420 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4421 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4424 llvm_unreachable("Vector size not supported");
4426 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4429 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4430 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4431 EVT SrcVT = SV->getValueType(0);
4432 SDValue V1 = SV->getOperand(0);
4433 DebugLoc dl = SV->getDebugLoc();
4435 int EltNo = SV->getSplatIndex();
4436 int NumElems = SrcVT.getVectorNumElements();
4437 unsigned Size = SrcVT.getSizeInBits();
4439 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4440 "Unknown how to promote splat for type");
4442 // Extract the 128-bit part containing the splat element and update
4443 // the splat element index when it refers to the higher register.
4445 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4446 if (EltNo >= NumElems/2)
4447 EltNo -= NumElems/2;
4450 // All i16 and i8 vector types can't be used directly by a generic shuffle
4451 // instruction because the target has no such instruction. Generate shuffles
4452 // which repeat i16 and i8 several times until they fit in i32, and then can
4453 // be manipulated by target suported shuffles.
4454 EVT EltVT = SrcVT.getVectorElementType();
4455 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4456 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4458 // Recreate the 256-bit vector and place the same 128-bit vector
4459 // into the low and high part. This is necessary because we want
4460 // to use VPERM* to shuffle the vectors
4462 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4465 return getLegalSplat(DAG, V1, EltNo);
4468 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4469 /// vector of zero or undef vector. This produces a shuffle where the low
4470 /// element of V2 is swizzled into the zero/undef vector, landing at element
4471 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4472 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4474 const X86Subtarget *Subtarget,
4475 SelectionDAG &DAG) {
4476 EVT VT = V2.getValueType();
4478 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4479 unsigned NumElems = VT.getVectorNumElements();
4480 SmallVector<int, 16> MaskVec;
4481 for (unsigned i = 0; i != NumElems; ++i)
4482 // If this is the insertion idx, put the low elt of V2 here.
4483 MaskVec.push_back(i == Idx ? NumElems : i);
4484 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4487 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4488 /// target specific opcode. Returns true if the Mask could be calculated.
4489 /// Sets IsUnary to true if only uses one source.
4490 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4491 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4492 unsigned NumElems = VT.getVectorNumElements();
4496 switch(N->getOpcode()) {
4498 ImmN = N->getOperand(N->getNumOperands()-1);
4499 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4501 case X86ISD::UNPCKH:
4502 DecodeUNPCKHMask(VT, Mask);
4504 case X86ISD::UNPCKL:
4505 DecodeUNPCKLMask(VT, Mask);
4507 case X86ISD::MOVHLPS:
4508 DecodeMOVHLPSMask(NumElems, Mask);
4510 case X86ISD::MOVLHPS:
4511 DecodeMOVLHPSMask(NumElems, Mask);
4513 case X86ISD::PSHUFD:
4514 case X86ISD::VPERMILP:
4515 ImmN = N->getOperand(N->getNumOperands()-1);
4516 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519 case X86ISD::PSHUFHW:
4520 ImmN = N->getOperand(N->getNumOperands()-1);
4521 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524 case X86ISD::PSHUFLW:
4525 ImmN = N->getOperand(N->getNumOperands()-1);
4526 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529 case X86ISD::VPERMI:
4530 ImmN = N->getOperand(N->getNumOperands()-1);
4531 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4535 case X86ISD::MOVSD: {
4536 // The index 0 always comes from the first element of the second source,
4537 // this is why MOVSS and MOVSD are used in the first place. The other
4538 // elements come from the other positions of the first source vector
4539 Mask.push_back(NumElems);
4540 for (unsigned i = 1; i != NumElems; ++i) {
4545 case X86ISD::VPERM2X128:
4546 ImmN = N->getOperand(N->getNumOperands()-1);
4547 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4548 if (Mask.empty()) return false;
4550 case X86ISD::MOVDDUP:
4551 case X86ISD::MOVLHPD:
4552 case X86ISD::MOVLPD:
4553 case X86ISD::MOVLPS:
4554 case X86ISD::MOVSHDUP:
4555 case X86ISD::MOVSLDUP:
4556 case X86ISD::PALIGN:
4557 // Not yet implemented
4559 default: llvm_unreachable("unknown target shuffle node");
4565 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4566 /// element of the result of the vector shuffle.
4567 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4570 return SDValue(); // Limit search depth.
4572 SDValue V = SDValue(N, 0);
4573 EVT VT = V.getValueType();
4574 unsigned Opcode = V.getOpcode();
4576 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4577 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4578 int Elt = SV->getMaskElt(Index);
4581 return DAG.getUNDEF(VT.getVectorElementType());
4583 unsigned NumElems = VT.getVectorNumElements();
4584 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4585 : SV->getOperand(1);
4586 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4589 // Recurse into target specific vector shuffles to find scalars.
4590 if (isTargetShuffle(Opcode)) {
4591 MVT ShufVT = V.getValueType().getSimpleVT();
4592 unsigned NumElems = ShufVT.getVectorNumElements();
4593 SmallVector<int, 16> ShuffleMask;
4597 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4600 int Elt = ShuffleMask[Index];
4602 return DAG.getUNDEF(ShufVT.getVectorElementType());
4604 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4606 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4610 // Actual nodes that may contain scalar elements
4611 if (Opcode == ISD::BITCAST) {
4612 V = V.getOperand(0);
4613 EVT SrcVT = V.getValueType();
4614 unsigned NumElems = VT.getVectorNumElements();
4616 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4620 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4621 return (Index == 0) ? V.getOperand(0)
4622 : DAG.getUNDEF(VT.getVectorElementType());
4624 if (V.getOpcode() == ISD::BUILD_VECTOR)
4625 return V.getOperand(Index);
4630 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4631 /// shuffle operation which come from a consecutively from a zero. The
4632 /// search can start in two different directions, from left or right.
4634 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4635 bool ZerosFromLeft, SelectionDAG &DAG) {
4637 for (i = 0; i != NumElems; ++i) {
4638 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4639 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4640 if (!(Elt.getNode() &&
4641 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4648 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4649 /// correspond consecutively to elements from one of the vector operands,
4650 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4652 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4653 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4654 unsigned NumElems, unsigned &OpNum) {
4655 bool SeenV1 = false;
4656 bool SeenV2 = false;
4658 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4659 int Idx = SVOp->getMaskElt(i);
4660 // Ignore undef indicies
4664 if (Idx < (int)NumElems)
4669 // Only accept consecutive elements from the same vector
4670 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4674 OpNum = SeenV1 ? 0 : 1;
4678 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4679 /// logical left shift of a vector.
4680 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4681 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4682 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4683 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4684 false /* check zeros from right */, DAG);
4690 // Considering the elements in the mask that are not consecutive zeros,
4691 // check if they consecutively come from only one of the source vectors.
4693 // V1 = {X, A, B, C} 0
4695 // vector_shuffle V1, V2 <1, 2, 3, X>
4697 if (!isShuffleMaskConsecutive(SVOp,
4698 0, // Mask Start Index
4699 NumElems-NumZeros, // Mask End Index(exclusive)
4700 NumZeros, // Where to start looking in the src vector
4701 NumElems, // Number of elements in vector
4702 OpSrc)) // Which source operand ?
4707 ShVal = SVOp->getOperand(OpSrc);
4711 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4712 /// logical left shift of a vector.
4713 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4714 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4715 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4716 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4717 true /* check zeros from left */, DAG);
4723 // Considering the elements in the mask that are not consecutive zeros,
4724 // check if they consecutively come from only one of the source vectors.
4726 // 0 { A, B, X, X } = V2
4728 // vector_shuffle V1, V2 <X, X, 4, 5>
4730 if (!isShuffleMaskConsecutive(SVOp,
4731 NumZeros, // Mask Start Index
4732 NumElems, // Mask End Index(exclusive)
4733 0, // Where to start looking in the src vector
4734 NumElems, // Number of elements in vector
4735 OpSrc)) // Which source operand ?
4740 ShVal = SVOp->getOperand(OpSrc);
4744 /// isVectorShift - Returns true if the shuffle can be implemented as a
4745 /// logical left or right shift of a vector.
4746 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4747 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4748 // Although the logic below support any bitwidth size, there are no
4749 // shift instructions which handle more than 128-bit vectors.
4750 if (SVOp->getValueType(0).getSizeInBits() > 128)
4753 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4754 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4760 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4762 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4763 unsigned NumNonZero, unsigned NumZero,
4765 const X86Subtarget* Subtarget,
4766 const TargetLowering &TLI) {
4770 DebugLoc dl = Op.getDebugLoc();
4773 for (unsigned i = 0; i < 16; ++i) {
4774 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4775 if (ThisIsNonZero && First) {
4777 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4779 V = DAG.getUNDEF(MVT::v8i16);
4784 SDValue ThisElt(0, 0), LastElt(0, 0);
4785 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4786 if (LastIsNonZero) {
4787 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4788 MVT::i16, Op.getOperand(i-1));
4790 if (ThisIsNonZero) {
4791 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4792 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4793 ThisElt, DAG.getConstant(8, MVT::i8));
4795 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4799 if (ThisElt.getNode())
4800 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4801 DAG.getIntPtrConstant(i/2));
4805 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4808 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4810 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4811 unsigned NumNonZero, unsigned NumZero,
4813 const X86Subtarget* Subtarget,
4814 const TargetLowering &TLI) {
4818 DebugLoc dl = Op.getDebugLoc();
4821 for (unsigned i = 0; i < 8; ++i) {
4822 bool isNonZero = (NonZeros & (1 << i)) != 0;
4826 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4828 V = DAG.getUNDEF(MVT::v8i16);
4831 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4832 MVT::v8i16, V, Op.getOperand(i),
4833 DAG.getIntPtrConstant(i));
4840 /// getVShift - Return a vector logical shift node.
4842 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4843 unsigned NumBits, SelectionDAG &DAG,
4844 const TargetLowering &TLI, DebugLoc dl) {
4845 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4846 EVT ShVT = MVT::v2i64;
4847 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4848 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4849 return DAG.getNode(ISD::BITCAST, dl, VT,
4850 DAG.getNode(Opc, dl, ShVT, SrcOp,
4851 DAG.getConstant(NumBits,
4852 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4856 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4857 SelectionDAG &DAG) const {
4859 // Check if the scalar load can be widened into a vector load. And if
4860 // the address is "base + cst" see if the cst can be "absorbed" into
4861 // the shuffle mask.
4862 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4863 SDValue Ptr = LD->getBasePtr();
4864 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4866 EVT PVT = LD->getValueType(0);
4867 if (PVT != MVT::i32 && PVT != MVT::f32)
4872 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4873 FI = FINode->getIndex();
4875 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4876 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4877 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4878 Offset = Ptr.getConstantOperandVal(1);
4879 Ptr = Ptr.getOperand(0);
4884 // FIXME: 256-bit vector instructions don't require a strict alignment,
4885 // improve this code to support it better.
4886 unsigned RequiredAlign = VT.getSizeInBits()/8;
4887 SDValue Chain = LD->getChain();
4888 // Make sure the stack object alignment is at least 16 or 32.
4889 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4890 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4891 if (MFI->isFixedObjectIndex(FI)) {
4892 // Can't change the alignment. FIXME: It's possible to compute
4893 // the exact stack offset and reference FI + adjust offset instead.
4894 // If someone *really* cares about this. That's the way to implement it.
4897 MFI->setObjectAlignment(FI, RequiredAlign);
4901 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4902 // Ptr + (Offset & ~15).
4905 if ((Offset % RequiredAlign) & 3)
4907 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4909 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4910 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4912 int EltNo = (Offset - StartOffset) >> 2;
4913 unsigned NumElems = VT.getVectorNumElements();
4915 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4916 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4917 LD->getPointerInfo().getWithOffset(StartOffset),
4918 false, false, false, 0);
4920 SmallVector<int, 8> Mask;
4921 for (unsigned i = 0; i != NumElems; ++i)
4922 Mask.push_back(EltNo);
4924 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4930 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4931 /// vector of type 'VT', see if the elements can be replaced by a single large
4932 /// load which has the same value as a build_vector whose operands are 'elts'.
4934 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4936 /// FIXME: we'd also like to handle the case where the last elements are zero
4937 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4938 /// There's even a handy isZeroNode for that purpose.
4939 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4940 DebugLoc &DL, SelectionDAG &DAG) {
4941 EVT EltVT = VT.getVectorElementType();
4942 unsigned NumElems = Elts.size();
4944 LoadSDNode *LDBase = NULL;
4945 unsigned LastLoadedElt = -1U;
4947 // For each element in the initializer, see if we've found a load or an undef.
4948 // If we don't find an initial load element, or later load elements are
4949 // non-consecutive, bail out.
4950 for (unsigned i = 0; i < NumElems; ++i) {
4951 SDValue Elt = Elts[i];
4953 if (!Elt.getNode() ||
4954 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4957 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4959 LDBase = cast<LoadSDNode>(Elt.getNode());
4963 if (Elt.getOpcode() == ISD::UNDEF)
4966 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4967 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4972 // If we have found an entire vector of loads and undefs, then return a large
4973 // load of the entire vector width starting at the base pointer. If we found
4974 // consecutive loads for the low half, generate a vzext_load node.
4975 if (LastLoadedElt == NumElems - 1) {
4976 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4977 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4978 LDBase->getPointerInfo(),
4979 LDBase->isVolatile(), LDBase->isNonTemporal(),
4980 LDBase->isInvariant(), 0);
4981 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4982 LDBase->getPointerInfo(),
4983 LDBase->isVolatile(), LDBase->isNonTemporal(),
4984 LDBase->isInvariant(), LDBase->getAlignment());
4986 if (NumElems == 4 && LastLoadedElt == 1 &&
4987 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4988 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4989 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4991 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4992 LDBase->getPointerInfo(),
4993 LDBase->getAlignment(),
4994 false/*isVolatile*/, true/*ReadMem*/,
4996 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5001 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5002 /// to generate a splat value for the following cases:
5003 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5004 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5005 /// a scalar load, or a constant.
5006 /// The VBROADCAST node is returned when a pattern is found,
5007 /// or SDValue() otherwise.
5009 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5010 if (!Subtarget->hasAVX())
5013 EVT VT = Op.getValueType();
5014 DebugLoc dl = Op.getDebugLoc();
5016 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5017 "Unsupported vector type for broadcast.");
5022 switch (Op.getOpcode()) {
5024 // Unknown pattern found.
5027 case ISD::BUILD_VECTOR: {
5028 // The BUILD_VECTOR node must be a splat.
5029 if (!isSplatVector(Op.getNode()))
5032 Ld = Op.getOperand(0);
5033 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5034 Ld.getOpcode() == ISD::ConstantFP);
5036 // The suspected load node has several users. Make sure that all
5037 // of its users are from the BUILD_VECTOR node.
5038 // Constants may have multiple users.
5039 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5044 case ISD::VECTOR_SHUFFLE: {
5045 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5047 // Shuffles must have a splat mask where the first element is
5049 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5052 SDValue Sc = Op.getOperand(0);
5053 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5054 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5056 if (!Subtarget->hasAVX2())
5059 // Use the register form of the broadcast instruction available on AVX2.
5060 if (VT.is256BitVector())
5061 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5062 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5065 Ld = Sc.getOperand(0);
5066 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5067 Ld.getOpcode() == ISD::ConstantFP);
5069 // The scalar_to_vector node and the suspected
5070 // load node must have exactly one user.
5071 // Constants may have multiple users.
5072 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5078 bool Is256 = VT.getSizeInBits() == 256;
5080 // Handle the broadcasting a single constant scalar from the constant pool
5081 // into a vector. On Sandybridge it is still better to load a constant vector
5082 // from the constant pool and not to broadcast it from a scalar.
5083 if (ConstSplatVal && Subtarget->hasAVX2()) {
5084 EVT CVT = Ld.getValueType();
5085 assert(!CVT.isVector() && "Must not broadcast a vector type");
5086 unsigned ScalarSize = CVT.getSizeInBits();
5088 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5089 const Constant *C = 0;
5090 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5091 C = CI->getConstantIntValue();
5092 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5093 C = CF->getConstantFPValue();
5095 assert(C && "Invalid constant type");
5097 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5098 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5099 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5100 MachinePointerInfo::getConstantPool(),
5101 false, false, false, Alignment);
5103 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5107 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5108 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5110 // Handle AVX2 in-register broadcasts.
5111 if (!IsLoad && Subtarget->hasAVX2() &&
5112 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5113 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5115 // The scalar source must be a normal load.
5119 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5120 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5122 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5123 // double since there is no vbroadcastsd xmm
5124 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5125 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5126 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5129 // Unsupported broadcast.
5134 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5135 DebugLoc dl = Op.getDebugLoc();
5137 EVT VT = Op.getValueType();
5138 EVT ExtVT = VT.getVectorElementType();
5139 unsigned NumElems = Op.getNumOperands();
5141 // Vectors containing all zeros can be matched by pxor and xorps later
5142 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5143 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5144 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5145 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5148 return getZeroVector(VT, Subtarget, DAG, dl);
5151 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5152 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5153 // vpcmpeqd on 256-bit vectors.
5154 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5155 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5158 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5161 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5162 if (Broadcast.getNode())
5165 unsigned EVTBits = ExtVT.getSizeInBits();
5167 unsigned NumZero = 0;
5168 unsigned NumNonZero = 0;
5169 unsigned NonZeros = 0;
5170 bool IsAllConstants = true;
5171 SmallSet<SDValue, 8> Values;
5172 for (unsigned i = 0; i < NumElems; ++i) {
5173 SDValue Elt = Op.getOperand(i);
5174 if (Elt.getOpcode() == ISD::UNDEF)
5177 if (Elt.getOpcode() != ISD::Constant &&
5178 Elt.getOpcode() != ISD::ConstantFP)
5179 IsAllConstants = false;
5180 if (X86::isZeroNode(Elt))
5183 NonZeros |= (1 << i);
5188 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5189 if (NumNonZero == 0)
5190 return DAG.getUNDEF(VT);
5192 // Special case for single non-zero, non-undef, element.
5193 if (NumNonZero == 1) {
5194 unsigned Idx = CountTrailingZeros_32(NonZeros);
5195 SDValue Item = Op.getOperand(Idx);
5197 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5198 // the value are obviously zero, truncate the value to i32 and do the
5199 // insertion that way. Only do this if the value is non-constant or if the
5200 // value is a constant being inserted into element 0. It is cheaper to do
5201 // a constant pool load than it is to do a movd + shuffle.
5202 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5203 (!IsAllConstants || Idx == 0)) {
5204 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5206 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5207 EVT VecVT = MVT::v4i32;
5208 unsigned VecElts = 4;
5210 // Truncate the value (which may itself be a constant) to i32, and
5211 // convert it to a vector with movd (S2V+shuffle to zero extend).
5212 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5213 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5214 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5216 // Now we have our 32-bit value zero extended in the low element of
5217 // a vector. If Idx != 0, swizzle it into place.
5219 SmallVector<int, 4> Mask;
5220 Mask.push_back(Idx);
5221 for (unsigned i = 1; i != VecElts; ++i)
5223 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5226 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5230 // If we have a constant or non-constant insertion into the low element of
5231 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5232 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5233 // depending on what the source datatype is.
5236 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5238 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5239 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5240 if (VT.getSizeInBits() == 256) {
5241 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5242 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5243 Item, DAG.getIntPtrConstant(0));
5245 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5246 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5247 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5248 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5251 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5252 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5253 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5254 if (VT.getSizeInBits() == 256) {
5255 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5256 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5258 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5259 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5261 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5265 // Is it a vector logical left shift?
5266 if (NumElems == 2 && Idx == 1 &&
5267 X86::isZeroNode(Op.getOperand(0)) &&
5268 !X86::isZeroNode(Op.getOperand(1))) {
5269 unsigned NumBits = VT.getSizeInBits();
5270 return getVShift(true, VT,
5271 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5272 VT, Op.getOperand(1)),
5273 NumBits/2, DAG, *this, dl);
5276 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5279 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5280 // is a non-constant being inserted into an element other than the low one,
5281 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5282 // movd/movss) to move this into the low element, then shuffle it into
5284 if (EVTBits == 32) {
5285 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5287 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5288 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5289 SmallVector<int, 8> MaskVec;
5290 for (unsigned i = 0; i != NumElems; ++i)
5291 MaskVec.push_back(i == Idx ? 0 : 1);
5292 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5296 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5297 if (Values.size() == 1) {
5298 if (EVTBits == 32) {
5299 // Instead of a shuffle like this:
5300 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5301 // Check if it's possible to issue this instead.
5302 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5303 unsigned Idx = CountTrailingZeros_32(NonZeros);
5304 SDValue Item = Op.getOperand(Idx);
5305 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5306 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5311 // A vector full of immediates; various special cases are already
5312 // handled, so this is best done with a single constant-pool load.
5316 // For AVX-length vectors, build the individual 128-bit pieces and use
5317 // shuffles to put them in place.
5318 if (VT.getSizeInBits() == 256) {
5319 SmallVector<SDValue, 32> V;
5320 for (unsigned i = 0; i != NumElems; ++i)
5321 V.push_back(Op.getOperand(i));
5323 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5325 // Build both the lower and upper subvector.
5326 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5327 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5330 // Recreate the wider vector with the lower and upper part.
5331 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5334 // Let legalizer expand 2-wide build_vectors.
5335 if (EVTBits == 64) {
5336 if (NumNonZero == 1) {
5337 // One half is zero or undef.
5338 unsigned Idx = CountTrailingZeros_32(NonZeros);
5339 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5340 Op.getOperand(Idx));
5341 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5346 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5347 if (EVTBits == 8 && NumElems == 16) {
5348 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5350 if (V.getNode()) return V;
5353 if (EVTBits == 16 && NumElems == 8) {
5354 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5356 if (V.getNode()) return V;
5359 // If element VT is == 32 bits, turn it into a number of shuffles.
5360 SmallVector<SDValue, 8> V(NumElems);
5361 if (NumElems == 4 && NumZero > 0) {
5362 for (unsigned i = 0; i < 4; ++i) {
5363 bool isZero = !(NonZeros & (1 << i));
5365 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5367 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5370 for (unsigned i = 0; i < 2; ++i) {
5371 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5374 V[i] = V[i*2]; // Must be a zero vector.
5377 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5380 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5383 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5388 bool Reverse1 = (NonZeros & 0x3) == 2;
5389 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5393 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5394 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5396 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5399 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5400 // Check for a build vector of consecutive loads.
5401 for (unsigned i = 0; i < NumElems; ++i)
5402 V[i] = Op.getOperand(i);
5404 // Check for elements which are consecutive loads.
5405 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5409 // For SSE 4.1, use insertps to put the high elements into the low element.
5410 if (getSubtarget()->hasSSE41()) {
5412 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5413 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5415 Result = DAG.getUNDEF(VT);
5417 for (unsigned i = 1; i < NumElems; ++i) {
5418 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5419 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5420 Op.getOperand(i), DAG.getIntPtrConstant(i));
5425 // Otherwise, expand into a number of unpckl*, start by extending each of
5426 // our (non-undef) elements to the full vector width with the element in the
5427 // bottom slot of the vector (which generates no code for SSE).
5428 for (unsigned i = 0; i < NumElems; ++i) {
5429 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5430 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5432 V[i] = DAG.getUNDEF(VT);
5435 // Next, we iteratively mix elements, e.g. for v4f32:
5436 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5437 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5438 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5439 unsigned EltStride = NumElems >> 1;
5440 while (EltStride != 0) {
5441 for (unsigned i = 0; i < EltStride; ++i) {
5442 // If V[i+EltStride] is undef and this is the first round of mixing,
5443 // then it is safe to just drop this shuffle: V[i] is already in the
5444 // right place, the one element (since it's the first round) being
5445 // inserted as undef can be dropped. This isn't safe for successive
5446 // rounds because they will permute elements within both vectors.
5447 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5448 EltStride == NumElems/2)
5451 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5460 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5461 // them in a MMX register. This is better than doing a stack convert.
5462 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5463 DebugLoc dl = Op.getDebugLoc();
5464 EVT ResVT = Op.getValueType();
5466 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5467 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5469 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5470 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5471 InVec = Op.getOperand(1);
5472 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5473 unsigned NumElts = ResVT.getVectorNumElements();
5474 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5475 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5476 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5478 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5479 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5480 Mask[0] = 0; Mask[1] = 2;
5481 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5483 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5486 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5487 // to create 256-bit vectors from two other 128-bit ones.
5488 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5489 DebugLoc dl = Op.getDebugLoc();
5490 EVT ResVT = Op.getValueType();
5492 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5494 SDValue V1 = Op.getOperand(0);
5495 SDValue V2 = Op.getOperand(1);
5496 unsigned NumElems = ResVT.getVectorNumElements();
5498 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5502 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5503 EVT ResVT = Op.getValueType();
5505 assert(Op.getNumOperands() == 2);
5506 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5507 "Unsupported CONCAT_VECTORS for value type");
5509 // We support concatenate two MMX registers and place them in a MMX register.
5510 // This is better than doing a stack convert.
5511 if (ResVT.is128BitVector())
5512 return LowerMMXCONCAT_VECTORS(Op, DAG);
5514 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5515 // from two other 128-bit ones.
5516 return LowerAVXCONCAT_VECTORS(Op, DAG);
5519 // Try to lower a shuffle node into a simple blend instruction.
5520 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5521 const X86Subtarget *Subtarget,
5522 SelectionDAG &DAG) {
5523 SDValue V1 = SVOp->getOperand(0);
5524 SDValue V2 = SVOp->getOperand(1);
5525 DebugLoc dl = SVOp->getDebugLoc();
5526 MVT VT = SVOp->getValueType(0).getSimpleVT();
5527 unsigned NumElems = VT.getVectorNumElements();
5529 if (!Subtarget->hasSSE41())
5535 switch (VT.SimpleTy) {
5536 default: return SDValue();
5538 ISDNo = X86ISD::BLENDPW;
5543 ISDNo = X86ISD::BLENDPS;
5548 ISDNo = X86ISD::BLENDPD;
5553 if (!Subtarget->hasAVX())
5555 ISDNo = X86ISD::BLENDPS;
5560 if (!Subtarget->hasAVX())
5562 ISDNo = X86ISD::BLENDPD;
5566 assert(ISDNo && "Invalid Op Number");
5568 unsigned MaskVals = 0;
5570 for (unsigned i = 0; i != NumElems; ++i) {
5571 int EltIdx = SVOp->getMaskElt(i);
5572 if (EltIdx == (int)i || EltIdx < 0)
5574 else if (EltIdx == (int)(i + NumElems))
5575 continue; // Bit is set to zero;
5580 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5581 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5582 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5583 DAG.getConstant(MaskVals, MVT::i32));
5584 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5587 // v8i16 shuffles - Prefer shuffles in the following order:
5588 // 1. [all] pshuflw, pshufhw, optional move
5589 // 2. [ssse3] 1 x pshufb
5590 // 3. [ssse3] 2 x pshufb + 1 x por
5591 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5593 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5594 SelectionDAG &DAG) const {
5595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5596 SDValue V1 = SVOp->getOperand(0);
5597 SDValue V2 = SVOp->getOperand(1);
5598 DebugLoc dl = SVOp->getDebugLoc();
5599 SmallVector<int, 8> MaskVals;
5601 // Determine if more than 1 of the words in each of the low and high quadwords
5602 // of the result come from the same quadword of one of the two inputs. Undef
5603 // mask values count as coming from any quadword, for better codegen.
5604 unsigned LoQuad[] = { 0, 0, 0, 0 };
5605 unsigned HiQuad[] = { 0, 0, 0, 0 };
5606 std::bitset<4> InputQuads;
5607 for (unsigned i = 0; i < 8; ++i) {
5608 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5609 int EltIdx = SVOp->getMaskElt(i);
5610 MaskVals.push_back(EltIdx);
5619 InputQuads.set(EltIdx / 4);
5622 int BestLoQuad = -1;
5623 unsigned MaxQuad = 1;
5624 for (unsigned i = 0; i < 4; ++i) {
5625 if (LoQuad[i] > MaxQuad) {
5627 MaxQuad = LoQuad[i];
5631 int BestHiQuad = -1;
5633 for (unsigned i = 0; i < 4; ++i) {
5634 if (HiQuad[i] > MaxQuad) {
5636 MaxQuad = HiQuad[i];
5640 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5641 // of the two input vectors, shuffle them into one input vector so only a
5642 // single pshufb instruction is necessary. If There are more than 2 input
5643 // quads, disable the next transformation since it does not help SSSE3.
5644 bool V1Used = InputQuads[0] || InputQuads[1];
5645 bool V2Used = InputQuads[2] || InputQuads[3];
5646 if (Subtarget->hasSSSE3()) {
5647 if (InputQuads.count() == 2 && V1Used && V2Used) {
5648 BestLoQuad = InputQuads[0] ? 0 : 1;
5649 BestHiQuad = InputQuads[2] ? 2 : 3;
5651 if (InputQuads.count() > 2) {
5657 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5658 // the shuffle mask. If a quad is scored as -1, that means that it contains
5659 // words from all 4 input quadwords.
5661 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5663 BestLoQuad < 0 ? 0 : BestLoQuad,
5664 BestHiQuad < 0 ? 1 : BestHiQuad
5666 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5667 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5668 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5669 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5671 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5672 // source words for the shuffle, to aid later transformations.
5673 bool AllWordsInNewV = true;
5674 bool InOrder[2] = { true, true };
5675 for (unsigned i = 0; i != 8; ++i) {
5676 int idx = MaskVals[i];
5678 InOrder[i/4] = false;
5679 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5681 AllWordsInNewV = false;
5685 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5686 if (AllWordsInNewV) {
5687 for (int i = 0; i != 8; ++i) {
5688 int idx = MaskVals[i];
5691 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5692 if ((idx != i) && idx < 4)
5694 if ((idx != i) && idx > 3)
5703 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5704 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5705 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5706 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5707 unsigned TargetMask = 0;
5708 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5709 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5710 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5711 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5712 getShufflePSHUFLWImmediate(SVOp);
5713 V1 = NewV.getOperand(0);
5714 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5718 // If we have SSSE3, and all words of the result are from 1 input vector,
5719 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5720 // is present, fall back to case 4.
5721 if (Subtarget->hasSSSE3()) {
5722 SmallVector<SDValue,16> pshufbMask;
5724 // If we have elements from both input vectors, set the high bit of the
5725 // shuffle mask element to zero out elements that come from V2 in the V1
5726 // mask, and elements that come from V1 in the V2 mask, so that the two
5727 // results can be OR'd together.
5728 bool TwoInputs = V1Used && V2Used;
5729 for (unsigned i = 0; i != 8; ++i) {
5730 int EltIdx = MaskVals[i] * 2;
5731 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5732 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5733 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5734 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5736 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5737 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5738 DAG.getNode(ISD::BUILD_VECTOR, dl,
5739 MVT::v16i8, &pshufbMask[0], 16));
5741 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5743 // Calculate the shuffle mask for the second input, shuffle it, and
5744 // OR it with the first shuffled input.
5746 for (unsigned i = 0; i != 8; ++i) {
5747 int EltIdx = MaskVals[i] * 2;
5748 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5749 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5750 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5751 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5753 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5754 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5755 DAG.getNode(ISD::BUILD_VECTOR, dl,
5756 MVT::v16i8, &pshufbMask[0], 16));
5757 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5758 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5761 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5762 // and update MaskVals with new element order.
5763 std::bitset<8> InOrder;
5764 if (BestLoQuad >= 0) {
5765 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5766 for (int i = 0; i != 4; ++i) {
5767 int idx = MaskVals[i];
5770 } else if ((idx / 4) == BestLoQuad) {
5775 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5778 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5779 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5780 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5782 getShufflePSHUFLWImmediate(SVOp), DAG);
5786 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5787 // and update MaskVals with the new element order.
5788 if (BestHiQuad >= 0) {
5789 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5790 for (unsigned i = 4; i != 8; ++i) {
5791 int idx = MaskVals[i];
5794 } else if ((idx / 4) == BestHiQuad) {
5795 MaskV[i] = (idx & 3) + 4;
5799 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5802 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5803 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5804 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5806 getShufflePSHUFHWImmediate(SVOp), DAG);
5810 // In case BestHi & BestLo were both -1, which means each quadword has a word
5811 // from each of the four input quadwords, calculate the InOrder bitvector now
5812 // before falling through to the insert/extract cleanup.
5813 if (BestLoQuad == -1 && BestHiQuad == -1) {
5815 for (int i = 0; i != 8; ++i)
5816 if (MaskVals[i] < 0 || MaskVals[i] == i)
5820 // The other elements are put in the right place using pextrw and pinsrw.
5821 for (unsigned i = 0; i != 8; ++i) {
5824 int EltIdx = MaskVals[i];
5827 SDValue ExtOp = (EltIdx < 8) ?
5828 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5829 DAG.getIntPtrConstant(EltIdx)) :
5830 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5831 DAG.getIntPtrConstant(EltIdx - 8));
5832 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5833 DAG.getIntPtrConstant(i));
5838 // v16i8 shuffles - Prefer shuffles in the following order:
5839 // 1. [ssse3] 1 x pshufb
5840 // 2. [ssse3] 2 x pshufb + 1 x por
5841 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5843 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5845 const X86TargetLowering &TLI) {
5846 SDValue V1 = SVOp->getOperand(0);
5847 SDValue V2 = SVOp->getOperand(1);
5848 DebugLoc dl = SVOp->getDebugLoc();
5849 ArrayRef<int> MaskVals = SVOp->getMask();
5851 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5853 // If we have SSSE3, case 1 is generated when all result bytes come from
5854 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5855 // present, fall back to case 3.
5857 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5858 if (TLI.getSubtarget()->hasSSSE3()) {
5859 SmallVector<SDValue,16> pshufbMask;
5861 // If all result elements are from one input vector, then only translate
5862 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5864 // Otherwise, we have elements from both input vectors, and must zero out
5865 // elements that come from V2 in the first mask, and V1 in the second mask
5866 // so that we can OR them together.
5867 for (unsigned i = 0; i != 16; ++i) {
5868 int EltIdx = MaskVals[i];
5869 if (EltIdx < 0 || EltIdx >= 16)
5871 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5873 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5874 DAG.getNode(ISD::BUILD_VECTOR, dl,
5875 MVT::v16i8, &pshufbMask[0], 16));
5879 // Calculate the shuffle mask for the second input, shuffle it, and
5880 // OR it with the first shuffled input.
5882 for (unsigned i = 0; i != 16; ++i) {
5883 int EltIdx = MaskVals[i];
5884 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5885 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5887 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5888 DAG.getNode(ISD::BUILD_VECTOR, dl,
5889 MVT::v16i8, &pshufbMask[0], 16));
5890 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5893 // No SSSE3 - Calculate in place words and then fix all out of place words
5894 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5895 // the 16 different words that comprise the two doublequadword input vectors.
5896 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5897 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5899 for (int i = 0; i != 8; ++i) {
5900 int Elt0 = MaskVals[i*2];
5901 int Elt1 = MaskVals[i*2+1];
5903 // This word of the result is all undef, skip it.
5904 if (Elt0 < 0 && Elt1 < 0)
5907 // This word of the result is already in the correct place, skip it.
5908 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5911 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5912 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5915 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5916 // using a single extract together, load it and store it.
5917 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5918 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5919 DAG.getIntPtrConstant(Elt1 / 2));
5920 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5921 DAG.getIntPtrConstant(i));
5925 // If Elt1 is defined, extract it from the appropriate source. If the
5926 // source byte is not also odd, shift the extracted word left 8 bits
5927 // otherwise clear the bottom 8 bits if we need to do an or.
5929 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5930 DAG.getIntPtrConstant(Elt1 / 2));
5931 if ((Elt1 & 1) == 0)
5932 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5934 TLI.getShiftAmountTy(InsElt.getValueType())));
5936 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5937 DAG.getConstant(0xFF00, MVT::i16));
5939 // If Elt0 is defined, extract it from the appropriate source. If the
5940 // source byte is not also even, shift the extracted word right 8 bits. If
5941 // Elt1 was also defined, OR the extracted values together before
5942 // inserting them in the result.
5944 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5945 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5946 if ((Elt0 & 1) != 0)
5947 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5949 TLI.getShiftAmountTy(InsElt0.getValueType())));
5951 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5952 DAG.getConstant(0x00FF, MVT::i16));
5953 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5956 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5957 DAG.getIntPtrConstant(i));
5959 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5962 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5963 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5964 /// done when every pair / quad of shuffle mask elements point to elements in
5965 /// the right sequence. e.g.
5966 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5968 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5969 SelectionDAG &DAG, DebugLoc dl) {
5970 MVT VT = SVOp->getValueType(0).getSimpleVT();
5971 unsigned NumElems = VT.getVectorNumElements();
5974 switch (VT.SimpleTy) {
5975 default: llvm_unreachable("Unexpected!");
5976 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
5977 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
5978 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
5979 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
5980 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5981 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
5984 SmallVector<int, 8> MaskVec;
5985 for (unsigned i = 0; i != NumElems; i += Scale) {
5987 for (unsigned j = 0; j != Scale; ++j) {
5988 int EltIdx = SVOp->getMaskElt(i+j);
5992 StartIdx = (EltIdx / Scale);
5993 if (EltIdx != (int)(StartIdx*Scale + j))
5996 MaskVec.push_back(StartIdx);
5999 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6000 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6001 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6004 /// getVZextMovL - Return a zero-extending vector move low node.
6006 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6007 SDValue SrcOp, SelectionDAG &DAG,
6008 const X86Subtarget *Subtarget, DebugLoc dl) {
6009 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6010 LoadSDNode *LD = NULL;
6011 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6012 LD = dyn_cast<LoadSDNode>(SrcOp);
6014 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6016 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6017 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6018 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6019 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6020 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6022 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6023 return DAG.getNode(ISD::BITCAST, dl, VT,
6024 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6025 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6033 return DAG.getNode(ISD::BITCAST, dl, VT,
6034 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6035 DAG.getNode(ISD::BITCAST, dl,
6039 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6040 /// which could not be matched by any known target speficic shuffle
6042 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6044 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6045 if (NewOp.getNode())
6048 EVT VT = SVOp->getValueType(0);
6050 unsigned NumElems = VT.getVectorNumElements();
6051 unsigned NumLaneElems = NumElems / 2;
6053 DebugLoc dl = SVOp->getDebugLoc();
6054 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6055 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6058 SmallVector<int, 16> Mask;
6059 for (unsigned l = 0; l < 2; ++l) {
6060 // Build a shuffle mask for the output, discovering on the fly which
6061 // input vectors to use as shuffle operands (recorded in InputUsed).
6062 // If building a suitable shuffle vector proves too hard, then bail
6063 // out with UseBuildVector set.
6064 bool UseBuildVector = false;
6065 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6066 unsigned LaneStart = l * NumLaneElems;
6067 for (unsigned i = 0; i != NumLaneElems; ++i) {
6068 // The mask element. This indexes into the input.
6069 int Idx = SVOp->getMaskElt(i+LaneStart);
6071 // the mask element does not index into any input vector.
6076 // The input vector this mask element indexes into.
6077 int Input = Idx / NumLaneElems;
6079 // Turn the index into an offset from the start of the input vector.
6080 Idx -= Input * NumLaneElems;
6082 // Find or create a shuffle vector operand to hold this input.
6084 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6085 if (InputUsed[OpNo] == Input)
6086 // This input vector is already an operand.
6088 if (InputUsed[OpNo] < 0) {
6089 // Create a new operand for this input vector.
6090 InputUsed[OpNo] = Input;
6095 if (OpNo >= array_lengthof(InputUsed)) {
6096 // More than two input vectors used! Give up on trying to create a
6097 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6098 UseBuildVector = true;
6102 // Add the mask index for the new shuffle vector.
6103 Mask.push_back(Idx + OpNo * NumLaneElems);
6106 if (UseBuildVector) {
6107 SmallVector<SDValue, 16> SVOps;
6108 for (unsigned i = 0; i != NumLaneElems; ++i) {
6109 // The mask element. This indexes into the input.
6110 int Idx = SVOp->getMaskElt(i+LaneStart);
6112 SVOps.push_back(DAG.getUNDEF(EltVT));
6116 // The input vector this mask element indexes into.
6117 int Input = Idx / NumElems;
6119 // Turn the index into an offset from the start of the input vector.
6120 Idx -= Input * NumElems;
6122 // Extract the vector element by hand.
6123 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6124 SVOp->getOperand(Input),
6125 DAG.getIntPtrConstant(Idx)));
6128 // Construct the output using a BUILD_VECTOR.
6129 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6131 } else if (InputUsed[0] < 0) {
6132 // No input vectors were used! The result is undefined.
6133 Output[l] = DAG.getUNDEF(NVT);
6135 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6136 (InputUsed[0] % 2) * NumLaneElems,
6138 // If only one input was used, use an undefined vector for the other.
6139 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6140 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6141 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6142 // At least one input vector was used. Create a new shuffle vector.
6143 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6149 // Concatenate the result back
6150 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6153 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6154 /// 4 elements, and match them with several different shuffle types.
6156 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6157 SDValue V1 = SVOp->getOperand(0);
6158 SDValue V2 = SVOp->getOperand(1);
6159 DebugLoc dl = SVOp->getDebugLoc();
6160 EVT VT = SVOp->getValueType(0);
6162 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6164 std::pair<int, int> Locs[4];
6165 int Mask1[] = { -1, -1, -1, -1 };
6166 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6170 for (unsigned i = 0; i != 4; ++i) {
6171 int Idx = PermMask[i];
6173 Locs[i] = std::make_pair(-1, -1);
6175 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6177 Locs[i] = std::make_pair(0, NumLo);
6181 Locs[i] = std::make_pair(1, NumHi);
6183 Mask1[2+NumHi] = Idx;
6189 if (NumLo <= 2 && NumHi <= 2) {
6190 // If no more than two elements come from either vector. This can be
6191 // implemented with two shuffles. First shuffle gather the elements.
6192 // The second shuffle, which takes the first shuffle as both of its
6193 // vector operands, put the elements into the right order.
6194 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6196 int Mask2[] = { -1, -1, -1, -1 };
6198 for (unsigned i = 0; i != 4; ++i)
6199 if (Locs[i].first != -1) {
6200 unsigned Idx = (i < 2) ? 0 : 4;
6201 Idx += Locs[i].first * 2 + Locs[i].second;
6205 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6208 if (NumLo == 3 || NumHi == 3) {
6209 // Otherwise, we must have three elements from one vector, call it X, and
6210 // one element from the other, call it Y. First, use a shufps to build an
6211 // intermediate vector with the one element from Y and the element from X
6212 // that will be in the same half in the final destination (the indexes don't
6213 // matter). Then, use a shufps to build the final vector, taking the half
6214 // containing the element from Y from the intermediate, and the other half
6217 // Normalize it so the 3 elements come from V1.
6218 CommuteVectorShuffleMask(PermMask, 4);
6222 // Find the element from V2.
6224 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6225 int Val = PermMask[HiIndex];
6232 Mask1[0] = PermMask[HiIndex];
6234 Mask1[2] = PermMask[HiIndex^1];
6236 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6239 Mask1[0] = PermMask[0];
6240 Mask1[1] = PermMask[1];
6241 Mask1[2] = HiIndex & 1 ? 6 : 4;
6242 Mask1[3] = HiIndex & 1 ? 4 : 6;
6243 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6246 Mask1[0] = HiIndex & 1 ? 2 : 0;
6247 Mask1[1] = HiIndex & 1 ? 0 : 2;
6248 Mask1[2] = PermMask[2];
6249 Mask1[3] = PermMask[3];
6254 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6257 // Break it into (shuffle shuffle_hi, shuffle_lo).
6258 int LoMask[] = { -1, -1, -1, -1 };
6259 int HiMask[] = { -1, -1, -1, -1 };
6261 int *MaskPtr = LoMask;
6262 unsigned MaskIdx = 0;
6265 for (unsigned i = 0; i != 4; ++i) {
6272 int Idx = PermMask[i];
6274 Locs[i] = std::make_pair(-1, -1);
6275 } else if (Idx < 4) {
6276 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6277 MaskPtr[LoIdx] = Idx;
6280 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6281 MaskPtr[HiIdx] = Idx;
6286 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6287 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6288 int MaskOps[] = { -1, -1, -1, -1 };
6289 for (unsigned i = 0; i != 4; ++i)
6290 if (Locs[i].first != -1)
6291 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6292 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6295 static bool MayFoldVectorLoad(SDValue V) {
6296 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6297 V = V.getOperand(0);
6298 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6299 V = V.getOperand(0);
6300 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6301 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6302 // BUILD_VECTOR (load), undef
6303 V = V.getOperand(0);
6309 // FIXME: the version above should always be used. Since there's
6310 // a bug where several vector shuffles can't be folded because the
6311 // DAG is not updated during lowering and a node claims to have two
6312 // uses while it only has one, use this version, and let isel match
6313 // another instruction if the load really happens to have more than
6314 // one use. Remove this version after this bug get fixed.
6315 // rdar://8434668, PR8156
6316 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6317 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6318 V = V.getOperand(0);
6319 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6320 V = V.getOperand(0);
6321 if (ISD::isNormalLoad(V.getNode()))
6327 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6328 EVT VT = Op.getValueType();
6330 // Canonizalize to v2f64.
6331 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6332 return DAG.getNode(ISD::BITCAST, dl, VT,
6333 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6338 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6340 SDValue V1 = Op.getOperand(0);
6341 SDValue V2 = Op.getOperand(1);
6342 EVT VT = Op.getValueType();
6344 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6346 if (HasSSE2 && VT == MVT::v2f64)
6347 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6349 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6350 return DAG.getNode(ISD::BITCAST, dl, VT,
6351 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6352 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6353 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6357 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6358 SDValue V1 = Op.getOperand(0);
6359 SDValue V2 = Op.getOperand(1);
6360 EVT VT = Op.getValueType();
6362 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6363 "unsupported shuffle type");
6365 if (V2.getOpcode() == ISD::UNDEF)
6369 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6373 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6374 SDValue V1 = Op.getOperand(0);
6375 SDValue V2 = Op.getOperand(1);
6376 EVT VT = Op.getValueType();
6377 unsigned NumElems = VT.getVectorNumElements();
6379 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6380 // operand of these instructions is only memory, so check if there's a
6381 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6383 bool CanFoldLoad = false;
6385 // Trivial case, when V2 comes from a load.
6386 if (MayFoldVectorLoad(V2))
6389 // When V1 is a load, it can be folded later into a store in isel, example:
6390 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6392 // (MOVLPSmr addr:$src1, VR128:$src2)
6393 // So, recognize this potential and also use MOVLPS or MOVLPD
6394 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6397 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6399 if (HasSSE2 && NumElems == 2)
6400 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6403 // If we don't care about the second element, proceed to use movss.
6404 if (SVOp->getMaskElt(1) != -1)
6405 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6408 // movl and movlp will both match v2i64, but v2i64 is never matched by
6409 // movl earlier because we make it strict to avoid messing with the movlp load
6410 // folding logic (see the code above getMOVLP call). Match it here then,
6411 // this is horrible, but will stay like this until we move all shuffle
6412 // matching to x86 specific nodes. Note that for the 1st condition all
6413 // types are matched with movsd.
6415 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6416 // as to remove this logic from here, as much as possible
6417 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6418 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6419 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6422 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6424 // Invert the operand order and use SHUFPS to match it.
6425 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6426 getShuffleSHUFImmediate(SVOp), DAG);
6430 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6431 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6432 EVT VT = Op.getValueType();
6433 DebugLoc dl = Op.getDebugLoc();
6434 SDValue V1 = Op.getOperand(0);
6435 SDValue V2 = Op.getOperand(1);
6437 if (isZeroShuffle(SVOp))
6438 return getZeroVector(VT, Subtarget, DAG, dl);
6440 // Handle splat operations
6441 if (SVOp->isSplat()) {
6442 unsigned NumElem = VT.getVectorNumElements();
6443 int Size = VT.getSizeInBits();
6445 // Use vbroadcast whenever the splat comes from a foldable load
6446 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6447 if (Broadcast.getNode())
6450 // Handle splats by matching through known shuffle masks
6451 if ((Size == 128 && NumElem <= 4) ||
6452 (Size == 256 && NumElem < 8))
6455 // All remaning splats are promoted to target supported vector shuffles.
6456 return PromoteSplat(SVOp, DAG);
6459 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6461 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6462 VT == MVT::v16i16 || VT == MVT::v32i8) {
6463 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6464 if (NewOp.getNode())
6465 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6466 } else if ((VT == MVT::v4i32 ||
6467 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6468 // FIXME: Figure out a cleaner way to do this.
6469 // Try to make use of movq to zero out the top part.
6470 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6471 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6472 if (NewOp.getNode()) {
6473 EVT NewVT = NewOp.getValueType();
6474 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6475 NewVT, true, false))
6476 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6477 DAG, Subtarget, dl);
6479 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6480 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6481 if (NewOp.getNode()) {
6482 EVT NewVT = NewOp.getValueType();
6483 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6484 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6485 DAG, Subtarget, dl);
6493 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6494 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6495 SDValue V1 = Op.getOperand(0);
6496 SDValue V2 = Op.getOperand(1);
6497 EVT VT = Op.getValueType();
6498 DebugLoc dl = Op.getDebugLoc();
6499 unsigned NumElems = VT.getVectorNumElements();
6500 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6501 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6502 bool V1IsSplat = false;
6503 bool V2IsSplat = false;
6504 bool HasSSE2 = Subtarget->hasSSE2();
6505 bool HasAVX = Subtarget->hasAVX();
6506 bool HasAVX2 = Subtarget->hasAVX2();
6507 MachineFunction &MF = DAG.getMachineFunction();
6508 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6510 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6512 if (V1IsUndef && V2IsUndef)
6513 return DAG.getUNDEF(VT);
6515 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6517 // Vector shuffle lowering takes 3 steps:
6519 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6520 // narrowing and commutation of operands should be handled.
6521 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6523 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6524 // so the shuffle can be broken into other shuffles and the legalizer can
6525 // try the lowering again.
6527 // The general idea is that no vector_shuffle operation should be left to
6528 // be matched during isel, all of them must be converted to a target specific
6531 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6532 // narrowing and commutation of operands should be handled. The actual code
6533 // doesn't include all of those, work in progress...
6534 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6535 if (NewOp.getNode())
6538 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6540 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6541 // unpckh_undef). Only use pshufd if speed is more important than size.
6542 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6543 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6544 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6545 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6547 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6548 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6549 return getMOVDDup(Op, dl, V1, DAG);
6551 if (isMOVHLPS_v_undef_Mask(M, VT))
6552 return getMOVHighToLow(Op, dl, DAG);
6554 // Use to match splats
6555 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6556 (VT == MVT::v2f64 || VT == MVT::v2i64))
6557 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6559 if (isPSHUFDMask(M, VT)) {
6560 // The actual implementation will match the mask in the if above and then
6561 // during isel it can match several different instructions, not only pshufd
6562 // as its name says, sad but true, emulate the behavior for now...
6563 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6564 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6566 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6568 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6569 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6571 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6572 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6574 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6578 // Check if this can be converted into a logical shift.
6579 bool isLeft = false;
6582 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6583 if (isShift && ShVal.hasOneUse()) {
6584 // If the shifted value has multiple uses, it may be cheaper to use
6585 // v_set0 + movlhps or movhlps, etc.
6586 EVT EltVT = VT.getVectorElementType();
6587 ShAmt *= EltVT.getSizeInBits();
6588 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6591 if (isMOVLMask(M, VT)) {
6592 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6593 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6594 if (!isMOVLPMask(M, VT)) {
6595 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6596 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6598 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6599 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6603 // FIXME: fold these into legal mask.
6604 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6605 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6607 if (isMOVHLPSMask(M, VT))
6608 return getMOVHighToLow(Op, dl, DAG);
6610 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6611 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6613 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6614 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6616 if (isMOVLPMask(M, VT))
6617 return getMOVLP(Op, dl, DAG, HasSSE2);
6619 if (ShouldXformToMOVHLPS(M, VT) ||
6620 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6621 return CommuteVectorShuffle(SVOp, DAG);
6624 // No better options. Use a vshldq / vsrldq.
6625 EVT EltVT = VT.getVectorElementType();
6626 ShAmt *= EltVT.getSizeInBits();
6627 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6630 bool Commuted = false;
6631 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6632 // 1,1,1,1 -> v8i16 though.
6633 V1IsSplat = isSplatVector(V1.getNode());
6634 V2IsSplat = isSplatVector(V2.getNode());
6636 // Canonicalize the splat or undef, if present, to be on the RHS.
6637 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6638 CommuteVectorShuffleMask(M, NumElems);
6640 std::swap(V1IsSplat, V2IsSplat);
6644 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6645 // Shuffling low element of v1 into undef, just return v1.
6648 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6649 // the instruction selector will not match, so get a canonical MOVL with
6650 // swapped operands to undo the commute.
6651 return getMOVL(DAG, dl, VT, V2, V1);
6654 if (isUNPCKLMask(M, VT, HasAVX2))
6655 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6657 if (isUNPCKHMask(M, VT, HasAVX2))
6658 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6661 // Normalize mask so all entries that point to V2 points to its first
6662 // element then try to match unpck{h|l} again. If match, return a
6663 // new vector_shuffle with the corrected mask.p
6664 SmallVector<int, 8> NewMask(M.begin(), M.end());
6665 NormalizeMask(NewMask, NumElems);
6666 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6667 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6668 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6669 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6673 // Commute is back and try unpck* again.
6674 // FIXME: this seems wrong.
6675 CommuteVectorShuffleMask(M, NumElems);
6677 std::swap(V1IsSplat, V2IsSplat);
6680 if (isUNPCKLMask(M, VT, HasAVX2))
6681 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6683 if (isUNPCKHMask(M, VT, HasAVX2))
6684 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6687 // Normalize the node to match x86 shuffle ops if needed
6688 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6689 return CommuteVectorShuffle(SVOp, DAG);
6691 // The checks below are all present in isShuffleMaskLegal, but they are
6692 // inlined here right now to enable us to directly emit target specific
6693 // nodes, and remove one by one until they don't return Op anymore.
6695 if (isPALIGNRMask(M, VT, Subtarget))
6696 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6697 getShufflePALIGNRImmediate(SVOp),
6700 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6701 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6702 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6703 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6706 if (isPSHUFHWMask(M, VT, HasAVX2))
6707 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6708 getShufflePSHUFHWImmediate(SVOp),
6711 if (isPSHUFLWMask(M, VT, HasAVX2))
6712 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6713 getShufflePSHUFLWImmediate(SVOp),
6716 if (isSHUFPMask(M, VT, HasAVX))
6717 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6718 getShuffleSHUFImmediate(SVOp), DAG);
6720 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6721 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6722 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6723 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6725 //===--------------------------------------------------------------------===//
6726 // Generate target specific nodes for 128 or 256-bit shuffles only
6727 // supported in the AVX instruction set.
6730 // Handle VMOVDDUPY permutations
6731 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6732 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6734 // Handle VPERMILPS/D* permutations
6735 if (isVPERMILPMask(M, VT, HasAVX)) {
6736 if (HasAVX2 && VT == MVT::v8i32)
6737 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6738 getShuffleSHUFImmediate(SVOp), DAG);
6739 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6740 getShuffleSHUFImmediate(SVOp), DAG);
6743 // Handle VPERM2F128/VPERM2I128 permutations
6744 if (isVPERM2X128Mask(M, VT, HasAVX))
6745 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6746 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6748 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6749 if (BlendOp.getNode())
6752 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6753 SmallVector<SDValue, 8> permclMask;
6754 for (unsigned i = 0; i != 8; ++i) {
6755 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6757 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6759 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6760 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6761 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6764 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6765 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6766 getShuffleCLImmediate(SVOp), DAG);
6769 //===--------------------------------------------------------------------===//
6770 // Since no target specific shuffle was selected for this generic one,
6771 // lower it into other known shuffles. FIXME: this isn't true yet, but
6772 // this is the plan.
6775 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6776 if (VT == MVT::v8i16) {
6777 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6778 if (NewOp.getNode())
6782 if (VT == MVT::v16i8) {
6783 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6784 if (NewOp.getNode())
6788 // Handle all 128-bit wide vectors with 4 elements, and match them with
6789 // several different shuffle types.
6790 if (NumElems == 4 && VT.getSizeInBits() == 128)
6791 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6793 // Handle general 256-bit shuffles
6794 if (VT.is256BitVector())
6795 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6801 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6802 SelectionDAG &DAG) const {
6803 EVT VT = Op.getValueType();
6804 DebugLoc dl = Op.getDebugLoc();
6806 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6809 if (VT.getSizeInBits() == 8) {
6810 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6811 Op.getOperand(0), Op.getOperand(1));
6812 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6813 DAG.getValueType(VT));
6814 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6817 if (VT.getSizeInBits() == 16) {
6818 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6819 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6821 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6822 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6823 DAG.getNode(ISD::BITCAST, dl,
6827 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6828 Op.getOperand(0), Op.getOperand(1));
6829 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6830 DAG.getValueType(VT));
6831 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6834 if (VT == MVT::f32) {
6835 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6836 // the result back to FR32 register. It's only worth matching if the
6837 // result has a single use which is a store or a bitcast to i32. And in
6838 // the case of a store, it's not worth it if the index is a constant 0,
6839 // because a MOVSSmr can be used instead, which is smaller and faster.
6840 if (!Op.hasOneUse())
6842 SDNode *User = *Op.getNode()->use_begin();
6843 if ((User->getOpcode() != ISD::STORE ||
6844 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6845 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6846 (User->getOpcode() != ISD::BITCAST ||
6847 User->getValueType(0) != MVT::i32))
6849 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6850 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6853 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6856 if (VT == MVT::i32 || VT == MVT::i64) {
6857 // ExtractPS/pextrq works with constant index.
6858 if (isa<ConstantSDNode>(Op.getOperand(1)))
6866 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6867 SelectionDAG &DAG) const {
6868 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6871 SDValue Vec = Op.getOperand(0);
6872 EVT VecVT = Vec.getValueType();
6874 // If this is a 256-bit vector result, first extract the 128-bit vector and
6875 // then extract the element from the 128-bit vector.
6876 if (VecVT.getSizeInBits() == 256) {
6877 DebugLoc dl = Op.getNode()->getDebugLoc();
6878 unsigned NumElems = VecVT.getVectorNumElements();
6879 SDValue Idx = Op.getOperand(1);
6880 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6882 // Get the 128-bit vector.
6883 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6885 if (IdxVal >= NumElems/2)
6886 IdxVal -= NumElems/2;
6887 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6888 DAG.getConstant(IdxVal, MVT::i32));
6891 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6893 if (Subtarget->hasSSE41()) {
6894 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6899 EVT VT = Op.getValueType();
6900 DebugLoc dl = Op.getDebugLoc();
6901 // TODO: handle v16i8.
6902 if (VT.getSizeInBits() == 16) {
6903 SDValue Vec = Op.getOperand(0);
6904 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6906 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6907 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6908 DAG.getNode(ISD::BITCAST, dl,
6911 // Transform it so it match pextrw which produces a 32-bit result.
6912 EVT EltVT = MVT::i32;
6913 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6914 Op.getOperand(0), Op.getOperand(1));
6915 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6916 DAG.getValueType(VT));
6917 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6920 if (VT.getSizeInBits() == 32) {
6921 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6925 // SHUFPS the element to the lowest double word, then movss.
6926 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6927 EVT VVT = Op.getOperand(0).getValueType();
6928 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6929 DAG.getUNDEF(VVT), Mask);
6930 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6931 DAG.getIntPtrConstant(0));
6934 if (VT.getSizeInBits() == 64) {
6935 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6936 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6937 // to match extract_elt for f64.
6938 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6942 // UNPCKHPD the element to the lowest double word, then movsd.
6943 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6944 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6945 int Mask[2] = { 1, -1 };
6946 EVT VVT = Op.getOperand(0).getValueType();
6947 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6948 DAG.getUNDEF(VVT), Mask);
6949 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6950 DAG.getIntPtrConstant(0));
6957 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6958 SelectionDAG &DAG) const {
6959 EVT VT = Op.getValueType();
6960 EVT EltVT = VT.getVectorElementType();
6961 DebugLoc dl = Op.getDebugLoc();
6963 SDValue N0 = Op.getOperand(0);
6964 SDValue N1 = Op.getOperand(1);
6965 SDValue N2 = Op.getOperand(2);
6967 if (VT.getSizeInBits() == 256)
6970 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6971 isa<ConstantSDNode>(N2)) {
6973 if (VT == MVT::v8i16)
6974 Opc = X86ISD::PINSRW;
6975 else if (VT == MVT::v16i8)
6976 Opc = X86ISD::PINSRB;
6978 Opc = X86ISD::PINSRB;
6980 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6982 if (N1.getValueType() != MVT::i32)
6983 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6984 if (N2.getValueType() != MVT::i32)
6985 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6986 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6989 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6990 // Bits [7:6] of the constant are the source select. This will always be
6991 // zero here. The DAG Combiner may combine an extract_elt index into these
6992 // bits. For example (insert (extract, 3), 2) could be matched by putting
6993 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6994 // Bits [5:4] of the constant are the destination select. This is the
6995 // value of the incoming immediate.
6996 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6997 // combine either bitwise AND or insert of float 0.0 to set these bits.
6998 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6999 // Create this as a scalar to vector..
7000 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7001 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7004 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7005 // PINSR* works with constant index.
7012 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7013 EVT VT = Op.getValueType();
7014 EVT EltVT = VT.getVectorElementType();
7016 DebugLoc dl = Op.getDebugLoc();
7017 SDValue N0 = Op.getOperand(0);
7018 SDValue N1 = Op.getOperand(1);
7019 SDValue N2 = Op.getOperand(2);
7021 // If this is a 256-bit vector result, first extract the 128-bit vector,
7022 // insert the element into the extracted half and then place it back.
7023 if (VT.getSizeInBits() == 256) {
7024 if (!isa<ConstantSDNode>(N2))
7027 // Get the desired 128-bit vector half.
7028 unsigned NumElems = VT.getVectorNumElements();
7029 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7030 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7032 // Insert the element into the desired half.
7033 bool Upper = IdxVal >= NumElems/2;
7034 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7035 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7037 // Insert the changed part back to the 256-bit vector
7038 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7041 if (Subtarget->hasSSE41())
7042 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7044 if (EltVT == MVT::i8)
7047 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7048 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7049 // as its second argument.
7050 if (N1.getValueType() != MVT::i32)
7051 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7052 if (N2.getValueType() != MVT::i32)
7053 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7054 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7060 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7061 LLVMContext *Context = DAG.getContext();
7062 DebugLoc dl = Op.getDebugLoc();
7063 EVT OpVT = Op.getValueType();
7065 // If this is a 256-bit vector result, first insert into a 128-bit
7066 // vector and then insert into the 256-bit vector.
7067 if (OpVT.getSizeInBits() > 128) {
7068 // Insert into a 128-bit vector.
7069 EVT VT128 = EVT::getVectorVT(*Context,
7070 OpVT.getVectorElementType(),
7071 OpVT.getVectorNumElements() / 2);
7073 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7075 // Insert the 128-bit vector.
7076 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7079 if (OpVT == MVT::v1i64 &&
7080 Op.getOperand(0).getValueType() == MVT::i64)
7081 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7083 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7084 assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7085 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7086 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7089 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7090 // a simple subregister reference or explicit instructions to grab
7091 // upper bits of a vector.
7093 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7094 if (Subtarget->hasAVX()) {
7095 DebugLoc dl = Op.getNode()->getDebugLoc();
7096 SDValue Vec = Op.getNode()->getOperand(0);
7097 SDValue Idx = Op.getNode()->getOperand(1);
7099 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7100 Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7101 isa<ConstantSDNode>(Idx)) {
7102 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7103 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7109 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7110 // simple superregister reference or explicit instructions to insert
7111 // the upper bits of a vector.
7113 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7114 if (Subtarget->hasAVX()) {
7115 DebugLoc dl = Op.getNode()->getDebugLoc();
7116 SDValue Vec = Op.getNode()->getOperand(0);
7117 SDValue SubVec = Op.getNode()->getOperand(1);
7118 SDValue Idx = Op.getNode()->getOperand(2);
7120 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7121 SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7122 isa<ConstantSDNode>(Idx)) {
7123 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7124 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7130 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7131 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7132 // one of the above mentioned nodes. It has to be wrapped because otherwise
7133 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7134 // be used to form addressing mode. These wrapped nodes will be selected
7137 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7138 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7140 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7142 unsigned char OpFlag = 0;
7143 unsigned WrapperKind = X86ISD::Wrapper;
7144 CodeModel::Model M = getTargetMachine().getCodeModel();
7146 if (Subtarget->isPICStyleRIPRel() &&
7147 (M == CodeModel::Small || M == CodeModel::Kernel))
7148 WrapperKind = X86ISD::WrapperRIP;
7149 else if (Subtarget->isPICStyleGOT())
7150 OpFlag = X86II::MO_GOTOFF;
7151 else if (Subtarget->isPICStyleStubPIC())
7152 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7154 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7156 CP->getOffset(), OpFlag);
7157 DebugLoc DL = CP->getDebugLoc();
7158 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7159 // With PIC, the address is actually $g + Offset.
7161 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7162 DAG.getNode(X86ISD::GlobalBaseReg,
7163 DebugLoc(), getPointerTy()),
7170 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7171 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7173 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7175 unsigned char OpFlag = 0;
7176 unsigned WrapperKind = X86ISD::Wrapper;
7177 CodeModel::Model M = getTargetMachine().getCodeModel();
7179 if (Subtarget->isPICStyleRIPRel() &&
7180 (M == CodeModel::Small || M == CodeModel::Kernel))
7181 WrapperKind = X86ISD::WrapperRIP;
7182 else if (Subtarget->isPICStyleGOT())
7183 OpFlag = X86II::MO_GOTOFF;
7184 else if (Subtarget->isPICStyleStubPIC())
7185 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7187 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7189 DebugLoc DL = JT->getDebugLoc();
7190 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7192 // With PIC, the address is actually $g + Offset.
7194 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7195 DAG.getNode(X86ISD::GlobalBaseReg,
7196 DebugLoc(), getPointerTy()),
7203 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7204 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7206 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7208 unsigned char OpFlag = 0;
7209 unsigned WrapperKind = X86ISD::Wrapper;
7210 CodeModel::Model M = getTargetMachine().getCodeModel();
7212 if (Subtarget->isPICStyleRIPRel() &&
7213 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7214 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7215 OpFlag = X86II::MO_GOTPCREL;
7216 WrapperKind = X86ISD::WrapperRIP;
7217 } else if (Subtarget->isPICStyleGOT()) {
7218 OpFlag = X86II::MO_GOT;
7219 } else if (Subtarget->isPICStyleStubPIC()) {
7220 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7221 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7222 OpFlag = X86II::MO_DARWIN_NONLAZY;
7225 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7227 DebugLoc DL = Op.getDebugLoc();
7228 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7231 // With PIC, the address is actually $g + Offset.
7232 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7233 !Subtarget->is64Bit()) {
7234 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7235 DAG.getNode(X86ISD::GlobalBaseReg,
7236 DebugLoc(), getPointerTy()),
7240 // For symbols that require a load from a stub to get the address, emit the
7242 if (isGlobalStubReference(OpFlag))
7243 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7244 MachinePointerInfo::getGOT(), false, false, false, 0);
7250 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7251 // Create the TargetBlockAddressAddress node.
7252 unsigned char OpFlags =
7253 Subtarget->ClassifyBlockAddressReference();
7254 CodeModel::Model M = getTargetMachine().getCodeModel();
7255 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7256 DebugLoc dl = Op.getDebugLoc();
7257 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7258 /*isTarget=*/true, OpFlags);
7260 if (Subtarget->isPICStyleRIPRel() &&
7261 (M == CodeModel::Small || M == CodeModel::Kernel))
7262 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7264 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7266 // With PIC, the address is actually $g + Offset.
7267 if (isGlobalRelativeToPICBase(OpFlags)) {
7268 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7269 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7277 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7279 SelectionDAG &DAG) const {
7280 // Create the TargetGlobalAddress node, folding in the constant
7281 // offset if it is legal.
7282 unsigned char OpFlags =
7283 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7284 CodeModel::Model M = getTargetMachine().getCodeModel();
7286 if (OpFlags == X86II::MO_NO_FLAG &&
7287 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7288 // A direct static reference to a global.
7289 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7292 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, 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()),
7308 // For globals that require a load from a stub to get the address, emit the
7310 if (isGlobalStubReference(OpFlags))
7311 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7312 MachinePointerInfo::getGOT(), false, false, false, 0);
7314 // If there was a non-zero offset that we didn't fold, create an explicit
7317 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7318 DAG.getConstant(Offset, getPointerTy()));
7324 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7325 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7326 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7327 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7331 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7332 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7333 unsigned char OperandFlags, bool LocalDynamic = false) {
7334 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7335 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7336 DebugLoc dl = GA->getDebugLoc();
7337 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7338 GA->getValueType(0),
7342 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7346 SDValue Ops[] = { Chain, TGA, *InFlag };
7347 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7349 SDValue Ops[] = { Chain, TGA };
7350 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7353 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7354 MFI->setAdjustsStack(true);
7356 SDValue Flag = Chain.getValue(1);
7357 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7360 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7362 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7365 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7366 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7367 DAG.getNode(X86ISD::GlobalBaseReg,
7368 DebugLoc(), PtrVT), InFlag);
7369 InFlag = Chain.getValue(1);
7371 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7374 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7376 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7378 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7379 X86::RAX, X86II::MO_TLSGD);
7382 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7386 DebugLoc dl = GA->getDebugLoc();
7388 // Get the start address of the TLS block for this module.
7389 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7390 .getInfo<X86MachineFunctionInfo>();
7391 MFI->incNumLocalDynamicTLSAccesses();
7395 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7396 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7399 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7400 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7401 InFlag = Chain.getValue(1);
7402 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7403 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7406 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7410 unsigned char OperandFlags = X86II::MO_DTPOFF;
7411 unsigned WrapperKind = X86ISD::Wrapper;
7412 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7413 GA->getValueType(0),
7414 GA->getOffset(), OperandFlags);
7415 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7417 // Add x@dtpoff with the base.
7418 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7421 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7422 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7423 const EVT PtrVT, TLSModel::Model model,
7424 bool is64Bit, bool isPIC) {
7425 DebugLoc dl = GA->getDebugLoc();
7427 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7428 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7429 is64Bit ? 257 : 256));
7431 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7432 DAG.getIntPtrConstant(0),
7433 MachinePointerInfo(Ptr),
7434 false, false, false, 0);
7436 unsigned char OperandFlags = 0;
7437 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7439 unsigned WrapperKind = X86ISD::Wrapper;
7440 if (model == TLSModel::LocalExec) {
7441 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7442 } else if (model == TLSModel::InitialExec) {
7444 OperandFlags = X86II::MO_GOTTPOFF;
7445 WrapperKind = X86ISD::WrapperRIP;
7447 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7450 llvm_unreachable("Unexpected model");
7453 // emit "addl x@ntpoff,%eax" (local exec)
7454 // or "addl x@indntpoff,%eax" (initial exec)
7455 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7456 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7457 GA->getValueType(0),
7458 GA->getOffset(), OperandFlags);
7459 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7461 if (model == TLSModel::InitialExec) {
7462 if (isPIC && !is64Bit) {
7463 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7464 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7468 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7469 MachinePointerInfo::getGOT(), false, false, false,
7473 // The address of the thread local variable is the add of the thread
7474 // pointer with the offset of the variable.
7475 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7479 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7481 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7482 const GlobalValue *GV = GA->getGlobal();
7484 if (Subtarget->isTargetELF()) {
7485 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7488 case TLSModel::GeneralDynamic:
7489 if (Subtarget->is64Bit())
7490 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7491 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7492 case TLSModel::LocalDynamic:
7493 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7494 Subtarget->is64Bit());
7495 case TLSModel::InitialExec:
7496 case TLSModel::LocalExec:
7497 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7498 Subtarget->is64Bit(),
7499 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7501 llvm_unreachable("Unknown TLS model.");
7504 if (Subtarget->isTargetDarwin()) {
7505 // Darwin only has one model of TLS. Lower to that.
7506 unsigned char OpFlag = 0;
7507 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7508 X86ISD::WrapperRIP : X86ISD::Wrapper;
7510 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7512 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7513 !Subtarget->is64Bit();
7515 OpFlag = X86II::MO_TLVP_PIC_BASE;
7517 OpFlag = X86II::MO_TLVP;
7518 DebugLoc DL = Op.getDebugLoc();
7519 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7520 GA->getValueType(0),
7521 GA->getOffset(), OpFlag);
7522 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7524 // With PIC32, the address is actually $g + Offset.
7526 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7527 DAG.getNode(X86ISD::GlobalBaseReg,
7528 DebugLoc(), getPointerTy()),
7531 // Lowering the machine isd will make sure everything is in the right
7533 SDValue Chain = DAG.getEntryNode();
7534 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7535 SDValue Args[] = { Chain, Offset };
7536 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7538 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7539 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7540 MFI->setAdjustsStack(true);
7542 // And our return value (tls address) is in the standard call return value
7544 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7545 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7549 if (Subtarget->isTargetWindows()) {
7550 // Just use the implicit TLS architecture
7551 // Need to generate someting similar to:
7552 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7554 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7555 // mov rcx, qword [rdx+rcx*8]
7556 // mov eax, .tls$:tlsvar
7557 // [rax+rcx] contains the address
7558 // Windows 64bit: gs:0x58
7559 // Windows 32bit: fs:__tls_array
7561 // If GV is an alias then use the aliasee for determining
7562 // thread-localness.
7563 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7564 GV = GA->resolveAliasedGlobal(false);
7565 DebugLoc dl = GA->getDebugLoc();
7566 SDValue Chain = DAG.getEntryNode();
7568 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7569 // %gs:0x58 (64-bit).
7570 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7571 ? Type::getInt8PtrTy(*DAG.getContext(),
7573 : Type::getInt32PtrTy(*DAG.getContext(),
7576 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7577 Subtarget->is64Bit()
7578 ? DAG.getIntPtrConstant(0x58)
7579 : DAG.getExternalSymbol("_tls_array",
7581 MachinePointerInfo(Ptr),
7582 false, false, false, 0);
7584 // Load the _tls_index variable
7585 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7586 if (Subtarget->is64Bit())
7587 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7588 IDX, MachinePointerInfo(), MVT::i32,
7591 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7592 false, false, false, 0);
7594 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7596 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7598 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7599 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7600 false, false, false, 0);
7602 // Get the offset of start of .tls section
7603 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7604 GA->getValueType(0),
7605 GA->getOffset(), X86II::MO_SECREL);
7606 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7608 // The address of the thread local variable is the add of the thread
7609 // pointer with the offset of the variable.
7610 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7613 llvm_unreachable("TLS not implemented for this target.");
7617 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7618 /// and take a 2 x i32 value to shift plus a shift amount.
7619 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7620 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7621 EVT VT = Op.getValueType();
7622 unsigned VTBits = VT.getSizeInBits();
7623 DebugLoc dl = Op.getDebugLoc();
7624 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7625 SDValue ShOpLo = Op.getOperand(0);
7626 SDValue ShOpHi = Op.getOperand(1);
7627 SDValue ShAmt = Op.getOperand(2);
7628 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7629 DAG.getConstant(VTBits - 1, MVT::i8))
7630 : DAG.getConstant(0, VT);
7633 if (Op.getOpcode() == ISD::SHL_PARTS) {
7634 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7635 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7637 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7638 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7641 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7642 DAG.getConstant(VTBits, MVT::i8));
7643 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7644 AndNode, DAG.getConstant(0, MVT::i8));
7647 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7648 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7649 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7651 if (Op.getOpcode() == ISD::SHL_PARTS) {
7652 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7653 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7655 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7656 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7659 SDValue Ops[2] = { Lo, Hi };
7660 return DAG.getMergeValues(Ops, 2, dl);
7663 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7664 SelectionDAG &DAG) const {
7665 EVT SrcVT = Op.getOperand(0).getValueType();
7667 if (SrcVT.isVector())
7670 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7671 "Unknown SINT_TO_FP to lower!");
7673 // These are really Legal; return the operand so the caller accepts it as
7675 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7677 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7678 Subtarget->is64Bit()) {
7682 DebugLoc dl = Op.getDebugLoc();
7683 unsigned Size = SrcVT.getSizeInBits()/8;
7684 MachineFunction &MF = DAG.getMachineFunction();
7685 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7686 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7687 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7689 MachinePointerInfo::getFixedStack(SSFI),
7691 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7694 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7696 SelectionDAG &DAG) const {
7698 DebugLoc DL = Op.getDebugLoc();
7700 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7702 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7704 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7706 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7708 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7709 MachineMemOperand *MMO;
7711 int SSFI = FI->getIndex();
7713 DAG.getMachineFunction()
7714 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7715 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7717 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7718 StackSlot = StackSlot.getOperand(1);
7720 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7721 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7723 Tys, Ops, array_lengthof(Ops),
7727 Chain = Result.getValue(1);
7728 SDValue InFlag = Result.getValue(2);
7730 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7731 // shouldn't be necessary except that RFP cannot be live across
7732 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7733 MachineFunction &MF = DAG.getMachineFunction();
7734 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7735 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7736 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7737 Tys = DAG.getVTList(MVT::Other);
7739 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7741 MachineMemOperand *MMO =
7742 DAG.getMachineFunction()
7743 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7744 MachineMemOperand::MOStore, SSFISize, SSFISize);
7746 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7747 Ops, array_lengthof(Ops),
7748 Op.getValueType(), MMO);
7749 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7750 MachinePointerInfo::getFixedStack(SSFI),
7751 false, false, false, 0);
7757 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7758 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7759 SelectionDAG &DAG) const {
7760 // This algorithm is not obvious. Here it is what we're trying to output:
7763 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7764 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7768 pshufd $0x4e, %xmm0, %xmm1
7773 DebugLoc dl = Op.getDebugLoc();
7774 LLVMContext *Context = DAG.getContext();
7776 // Build some magic constants.
7777 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7778 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7779 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7781 SmallVector<Constant*,2> CV1;
7783 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7785 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7786 Constant *C1 = ConstantVector::get(CV1);
7787 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7789 // Load the 64-bit value into an XMM register.
7790 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7792 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7793 MachinePointerInfo::getConstantPool(),
7794 false, false, false, 16);
7795 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7796 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7799 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7800 MachinePointerInfo::getConstantPool(),
7801 false, false, false, 16);
7802 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7803 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7806 if (Subtarget->hasSSE3()) {
7807 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7808 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7810 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7811 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7813 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7814 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7818 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7819 DAG.getIntPtrConstant(0));
7822 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7823 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7824 SelectionDAG &DAG) const {
7825 DebugLoc dl = Op.getDebugLoc();
7826 // FP constant to bias correct the final result.
7827 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7830 // Load the 32-bit value into an XMM register.
7831 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7834 // Zero out the upper parts of the register.
7835 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7837 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7838 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7839 DAG.getIntPtrConstant(0));
7841 // Or the load with the bias.
7842 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7843 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7844 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7846 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7847 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7848 MVT::v2f64, Bias)));
7849 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7850 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7851 DAG.getIntPtrConstant(0));
7853 // Subtract the bias.
7854 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7856 // Handle final rounding.
7857 EVT DestVT = Op.getValueType();
7859 if (DestVT.bitsLT(MVT::f64))
7860 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7861 DAG.getIntPtrConstant(0));
7862 if (DestVT.bitsGT(MVT::f64))
7863 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7865 // Handle final rounding.
7869 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7870 SelectionDAG &DAG) const {
7871 SDValue N0 = Op.getOperand(0);
7872 DebugLoc dl = Op.getDebugLoc();
7874 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7875 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7876 // the optimization here.
7877 if (DAG.SignBitIsZero(N0))
7878 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7880 EVT SrcVT = N0.getValueType();
7881 EVT DstVT = Op.getValueType();
7882 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7883 return LowerUINT_TO_FP_i64(Op, DAG);
7884 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7885 return LowerUINT_TO_FP_i32(Op, DAG);
7886 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7889 // Make a 64-bit buffer, and use it to build an FILD.
7890 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7891 if (SrcVT == MVT::i32) {
7892 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7893 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7894 getPointerTy(), StackSlot, WordOff);
7895 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7896 StackSlot, MachinePointerInfo(),
7898 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7899 OffsetSlot, MachinePointerInfo(),
7901 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7905 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7906 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7907 StackSlot, MachinePointerInfo(),
7909 // For i64 source, we need to add the appropriate power of 2 if the input
7910 // was negative. This is the same as the optimization in
7911 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7912 // we must be careful to do the computation in x87 extended precision, not
7913 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7914 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7915 MachineMemOperand *MMO =
7916 DAG.getMachineFunction()
7917 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7918 MachineMemOperand::MOLoad, 8, 8);
7920 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7921 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7922 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7925 APInt FF(32, 0x5F800000ULL);
7927 // Check whether the sign bit is set.
7928 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7929 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7932 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7933 SDValue FudgePtr = DAG.getConstantPool(
7934 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7937 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7938 SDValue Zero = DAG.getIntPtrConstant(0);
7939 SDValue Four = DAG.getIntPtrConstant(4);
7940 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7942 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7944 // Load the value out, extending it from f32 to f80.
7945 // FIXME: Avoid the extend by constructing the right constant pool?
7946 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7947 FudgePtr, MachinePointerInfo::getConstantPool(),
7948 MVT::f32, false, false, 4);
7949 // Extend everything to 80 bits to force it to be done on x87.
7950 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7951 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7954 std::pair<SDValue,SDValue> X86TargetLowering::
7955 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7956 DebugLoc DL = Op.getDebugLoc();
7958 EVT DstTy = Op.getValueType();
7960 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7961 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7965 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7966 DstTy.getSimpleVT() >= MVT::i16 &&
7967 "Unknown FP_TO_INT to lower!");
7969 // These are really Legal.
7970 if (DstTy == MVT::i32 &&
7971 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7972 return std::make_pair(SDValue(), SDValue());
7973 if (Subtarget->is64Bit() &&
7974 DstTy == MVT::i64 &&
7975 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7976 return std::make_pair(SDValue(), SDValue());
7978 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7979 // stack slot, or into the FTOL runtime function.
7980 MachineFunction &MF = DAG.getMachineFunction();
7981 unsigned MemSize = DstTy.getSizeInBits()/8;
7982 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7983 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7986 if (!IsSigned && isIntegerTypeFTOL(DstTy))
7987 Opc = X86ISD::WIN_FTOL;
7989 switch (DstTy.getSimpleVT().SimpleTy) {
7990 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7991 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7992 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7993 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7996 SDValue Chain = DAG.getEntryNode();
7997 SDValue Value = Op.getOperand(0);
7998 EVT TheVT = Op.getOperand(0).getValueType();
7999 // FIXME This causes a redundant load/store if the SSE-class value is already
8000 // in memory, such as if it is on the callstack.
8001 if (isScalarFPTypeInSSEReg(TheVT)) {
8002 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8003 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8004 MachinePointerInfo::getFixedStack(SSFI),
8006 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8008 Chain, StackSlot, DAG.getValueType(TheVT)
8011 MachineMemOperand *MMO =
8012 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8013 MachineMemOperand::MOLoad, MemSize, MemSize);
8014 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8016 Chain = Value.getValue(1);
8017 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8018 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8021 MachineMemOperand *MMO =
8022 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8023 MachineMemOperand::MOStore, MemSize, MemSize);
8025 if (Opc != X86ISD::WIN_FTOL) {
8026 // Build the FP_TO_INT*_IN_MEM
8027 SDValue Ops[] = { Chain, Value, StackSlot };
8028 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8029 Ops, 3, DstTy, MMO);
8030 return std::make_pair(FIST, StackSlot);
8032 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8033 DAG.getVTList(MVT::Other, MVT::Glue),
8035 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8036 MVT::i32, ftol.getValue(1));
8037 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8038 MVT::i32, eax.getValue(2));
8039 SDValue Ops[] = { eax, edx };
8040 SDValue pair = IsReplace
8041 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8042 : DAG.getMergeValues(Ops, 2, DL);
8043 return std::make_pair(pair, SDValue());
8047 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8048 SelectionDAG &DAG) const {
8049 if (Op.getValueType().isVector())
8052 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8053 /*IsSigned=*/ true, /*IsReplace=*/ false);
8054 SDValue FIST = Vals.first, StackSlot = Vals.second;
8055 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8056 if (FIST.getNode() == 0) return Op;
8058 if (StackSlot.getNode())
8060 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8061 FIST, StackSlot, MachinePointerInfo(),
8062 false, false, false, 0);
8064 // The node is the result.
8068 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8069 SelectionDAG &DAG) const {
8070 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8071 /*IsSigned=*/ false, /*IsReplace=*/ false);
8072 SDValue FIST = Vals.first, StackSlot = Vals.second;
8073 assert(FIST.getNode() && "Unexpected failure");
8075 if (StackSlot.getNode())
8077 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8078 FIST, StackSlot, MachinePointerInfo(),
8079 false, false, false, 0);
8081 // The node is the result.
8085 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8086 SelectionDAG &DAG) const {
8087 LLVMContext *Context = DAG.getContext();
8088 DebugLoc dl = Op.getDebugLoc();
8089 EVT VT = Op.getValueType();
8092 EltVT = VT.getVectorElementType();
8094 if (EltVT == MVT::f64) {
8095 C = ConstantVector::getSplat(2,
8096 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8098 C = ConstantVector::getSplat(4,
8099 ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8101 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8102 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8103 MachinePointerInfo::getConstantPool(),
8104 false, false, false, 16);
8105 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8108 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8109 LLVMContext *Context = DAG.getContext();
8110 DebugLoc dl = Op.getDebugLoc();
8111 EVT VT = Op.getValueType();
8113 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8114 if (VT.isVector()) {
8115 EltVT = VT.getVectorElementType();
8116 NumElts = VT.getVectorNumElements();
8119 if (EltVT == MVT::f64)
8120 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8122 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8123 C = ConstantVector::getSplat(NumElts, C);
8124 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8125 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8126 MachinePointerInfo::getConstantPool(),
8127 false, false, false, 16);
8128 if (VT.isVector()) {
8129 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8130 return DAG.getNode(ISD::BITCAST, dl, VT,
8131 DAG.getNode(ISD::XOR, dl, XORVT,
8132 DAG.getNode(ISD::BITCAST, dl, XORVT,
8134 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8137 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8140 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8141 LLVMContext *Context = DAG.getContext();
8142 SDValue Op0 = Op.getOperand(0);
8143 SDValue Op1 = Op.getOperand(1);
8144 DebugLoc dl = Op.getDebugLoc();
8145 EVT VT = Op.getValueType();
8146 EVT SrcVT = Op1.getValueType();
8148 // If second operand is smaller, extend it first.
8149 if (SrcVT.bitsLT(VT)) {
8150 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8153 // And if it is bigger, shrink it first.
8154 if (SrcVT.bitsGT(VT)) {
8155 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8159 // At this point the operands and the result should have the same
8160 // type, and that won't be f80 since that is not custom lowered.
8162 // First get the sign bit of second operand.
8163 SmallVector<Constant*,4> CV;
8164 if (SrcVT == MVT::f64) {
8165 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8166 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8168 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8169 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8170 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8171 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8173 Constant *C = ConstantVector::get(CV);
8174 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8175 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8176 MachinePointerInfo::getConstantPool(),
8177 false, false, false, 16);
8178 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8180 // Shift sign bit right or left if the two operands have different types.
8181 if (SrcVT.bitsGT(VT)) {
8182 // Op0 is MVT::f32, Op1 is MVT::f64.
8183 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8184 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8185 DAG.getConstant(32, MVT::i32));
8186 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8187 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8188 DAG.getIntPtrConstant(0));
8191 // Clear first operand sign bit.
8193 if (VT == MVT::f64) {
8194 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8195 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8197 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8198 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8199 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8200 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8202 C = ConstantVector::get(CV);
8203 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8204 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8205 MachinePointerInfo::getConstantPool(),
8206 false, false, false, 16);
8207 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8209 // Or the value with the sign bit.
8210 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8213 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8214 SDValue N0 = Op.getOperand(0);
8215 DebugLoc dl = Op.getDebugLoc();
8216 EVT VT = Op.getValueType();
8218 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8219 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8220 DAG.getConstant(1, VT));
8221 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8224 /// Emit nodes that will be selected as "test Op0,Op0", or something
8226 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8227 SelectionDAG &DAG) const {
8228 DebugLoc dl = Op.getDebugLoc();
8230 // CF and OF aren't always set the way we want. Determine which
8231 // of these we need.
8232 bool NeedCF = false;
8233 bool NeedOF = false;
8236 case X86::COND_A: case X86::COND_AE:
8237 case X86::COND_B: case X86::COND_BE:
8240 case X86::COND_G: case X86::COND_GE:
8241 case X86::COND_L: case X86::COND_LE:
8242 case X86::COND_O: case X86::COND_NO:
8247 // See if we can use the EFLAGS value from the operand instead of
8248 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8249 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8250 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8251 // Emit a CMP with 0, which is the TEST pattern.
8252 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8253 DAG.getConstant(0, Op.getValueType()));
8255 unsigned Opcode = 0;
8256 unsigned NumOperands = 0;
8257 switch (Op.getNode()->getOpcode()) {
8259 // Due to an isel shortcoming, be conservative if this add is likely to be
8260 // selected as part of a load-modify-store instruction. When the root node
8261 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8262 // uses of other nodes in the match, such as the ADD in this case. This
8263 // leads to the ADD being left around and reselected, with the result being
8264 // two adds in the output. Alas, even if none our users are stores, that
8265 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8266 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8267 // climbing the DAG back to the root, and it doesn't seem to be worth the
8269 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8270 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8271 if (UI->getOpcode() != ISD::CopyToReg &&
8272 UI->getOpcode() != ISD::SETCC &&
8273 UI->getOpcode() != ISD::STORE)
8276 if (ConstantSDNode *C =
8277 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8278 // An add of one will be selected as an INC.
8279 if (C->getAPIntValue() == 1) {
8280 Opcode = X86ISD::INC;
8285 // An add of negative one (subtract of one) will be selected as a DEC.
8286 if (C->getAPIntValue().isAllOnesValue()) {
8287 Opcode = X86ISD::DEC;
8293 // Otherwise use a regular EFLAGS-setting add.
8294 Opcode = X86ISD::ADD;
8298 // If the primary and result isn't used, don't bother using X86ISD::AND,
8299 // because a TEST instruction will be better.
8300 bool NonFlagUse = false;
8301 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8302 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8304 unsigned UOpNo = UI.getOperandNo();
8305 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8306 // Look pass truncate.
8307 UOpNo = User->use_begin().getOperandNo();
8308 User = *User->use_begin();
8311 if (User->getOpcode() != ISD::BRCOND &&
8312 User->getOpcode() != ISD::SETCC &&
8313 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8326 // Due to the ISEL shortcoming noted above, be conservative if this op is
8327 // likely to be selected as part of a load-modify-store instruction.
8328 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8329 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8330 if (UI->getOpcode() == ISD::STORE)
8333 // Otherwise use a regular EFLAGS-setting instruction.
8334 switch (Op.getNode()->getOpcode()) {
8335 default: llvm_unreachable("unexpected operator!");
8337 Opcode = X86ISD::SUB;
8339 case ISD::OR: Opcode = X86ISD::OR; break;
8340 case ISD::XOR: Opcode = X86ISD::XOR; break;
8341 case ISD::AND: Opcode = X86ISD::AND; break;
8353 return SDValue(Op.getNode(), 1);
8360 // Emit a CMP with 0, which is the TEST pattern.
8361 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8362 DAG.getConstant(0, Op.getValueType()));
8364 if (Opcode == X86ISD::CMP) {
8365 SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8367 // We can't replace usage of SUB with CMP.
8368 // The SUB node will be removed later because there is no use of it.
8369 return SDValue(New.getNode(), 0);
8372 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8373 SmallVector<SDValue, 4> Ops;
8374 for (unsigned i = 0; i != NumOperands; ++i)
8375 Ops.push_back(Op.getOperand(i));
8377 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8378 DAG.ReplaceAllUsesWith(Op, New);
8379 return SDValue(New.getNode(), 1);
8382 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8384 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8385 SelectionDAG &DAG) const {
8386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8387 if (C->getAPIntValue() == 0)
8388 return EmitTest(Op0, X86CC, DAG);
8390 DebugLoc dl = Op0.getDebugLoc();
8391 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8392 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8393 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8394 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8395 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8397 return SDValue(Sub.getNode(), 1);
8399 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8402 /// Convert a comparison if required by the subtarget.
8403 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8404 SelectionDAG &DAG) const {
8405 // If the subtarget does not support the FUCOMI instruction, floating-point
8406 // comparisons have to be converted.
8407 if (Subtarget->hasCMov() ||
8408 Cmp.getOpcode() != X86ISD::CMP ||
8409 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8410 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8413 // The instruction selector will select an FUCOM instruction instead of
8414 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8415 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8416 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8417 DebugLoc dl = Cmp.getDebugLoc();
8418 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8419 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8420 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8421 DAG.getConstant(8, MVT::i8));
8422 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8423 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8426 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8427 /// if it's possible.
8428 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8429 DebugLoc dl, SelectionDAG &DAG) const {
8430 SDValue Op0 = And.getOperand(0);
8431 SDValue Op1 = And.getOperand(1);
8432 if (Op0.getOpcode() == ISD::TRUNCATE)
8433 Op0 = Op0.getOperand(0);
8434 if (Op1.getOpcode() == ISD::TRUNCATE)
8435 Op1 = Op1.getOperand(0);
8438 if (Op1.getOpcode() == ISD::SHL)
8439 std::swap(Op0, Op1);
8440 if (Op0.getOpcode() == ISD::SHL) {
8441 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8442 if (And00C->getZExtValue() == 1) {
8443 // If we looked past a truncate, check that it's only truncating away
8445 unsigned BitWidth = Op0.getValueSizeInBits();
8446 unsigned AndBitWidth = And.getValueSizeInBits();
8447 if (BitWidth > AndBitWidth) {
8449 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8450 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8454 RHS = Op0.getOperand(1);
8456 } else if (Op1.getOpcode() == ISD::Constant) {
8457 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8458 uint64_t AndRHSVal = AndRHS->getZExtValue();
8459 SDValue AndLHS = Op0;
8461 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8462 LHS = AndLHS.getOperand(0);
8463 RHS = AndLHS.getOperand(1);
8466 // Use BT if the immediate can't be encoded in a TEST instruction.
8467 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8469 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8473 if (LHS.getNode()) {
8474 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8475 // instruction. Since the shift amount is in-range-or-undefined, we know
8476 // that doing a bittest on the i32 value is ok. We extend to i32 because
8477 // the encoding for the i16 version is larger than the i32 version.
8478 // Also promote i16 to i32 for performance / code size reason.
8479 if (LHS.getValueType() == MVT::i8 ||
8480 LHS.getValueType() == MVT::i16)
8481 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8483 // If the operand types disagree, extend the shift amount to match. Since
8484 // BT ignores high bits (like shifts) we can use anyextend.
8485 if (LHS.getValueType() != RHS.getValueType())
8486 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8488 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8489 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8490 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8491 DAG.getConstant(Cond, MVT::i8), BT);
8497 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8499 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8501 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8502 SDValue Op0 = Op.getOperand(0);
8503 SDValue Op1 = Op.getOperand(1);
8504 DebugLoc dl = Op.getDebugLoc();
8505 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8507 // Optimize to BT if possible.
8508 // Lower (X & (1 << N)) == 0 to BT(X, N).
8509 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8510 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8511 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8512 Op1.getOpcode() == ISD::Constant &&
8513 cast<ConstantSDNode>(Op1)->isNullValue() &&
8514 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8515 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8516 if (NewSetCC.getNode())
8520 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8522 if (Op1.getOpcode() == ISD::Constant &&
8523 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8524 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8525 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8527 // If the input is a setcc, then reuse the input setcc or use a new one with
8528 // the inverted condition.
8529 if (Op0.getOpcode() == X86ISD::SETCC) {
8530 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8531 bool Invert = (CC == ISD::SETNE) ^
8532 cast<ConstantSDNode>(Op1)->isNullValue();
8533 if (!Invert) return Op0;
8535 CCode = X86::GetOppositeBranchCondition(CCode);
8536 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8537 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8541 bool isFP = Op1.getValueType().isFloatingPoint();
8542 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8543 if (X86CC == X86::COND_INVALID)
8546 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8547 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8548 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8549 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8552 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8553 // ones, and then concatenate the result back.
8554 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8555 EVT VT = Op.getValueType();
8557 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8558 "Unsupported value type for operation");
8560 unsigned NumElems = VT.getVectorNumElements();
8561 DebugLoc dl = Op.getDebugLoc();
8562 SDValue CC = Op.getOperand(2);
8564 // Extract the LHS vectors
8565 SDValue LHS = Op.getOperand(0);
8566 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8567 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8569 // Extract the RHS vectors
8570 SDValue RHS = Op.getOperand(1);
8571 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8572 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8574 // Issue the operation on the smaller types and concatenate the result back
8575 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8576 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8577 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8578 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8579 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8583 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8585 SDValue Op0 = Op.getOperand(0);
8586 SDValue Op1 = Op.getOperand(1);
8587 SDValue CC = Op.getOperand(2);
8588 EVT VT = Op.getValueType();
8589 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8590 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8591 DebugLoc dl = Op.getDebugLoc();
8595 EVT EltVT = Op0.getValueType().getVectorElementType();
8596 assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8600 // SSE Condition code mapping:
8609 switch (SetCCOpcode) {
8612 case ISD::SETEQ: SSECC = 0; break;
8614 case ISD::SETGT: Swap = true; // Fallthrough
8616 case ISD::SETOLT: SSECC = 1; break;
8618 case ISD::SETGE: Swap = true; // Fallthrough
8620 case ISD::SETOLE: SSECC = 2; break;
8621 case ISD::SETUO: SSECC = 3; break;
8623 case ISD::SETNE: SSECC = 4; break;
8624 case ISD::SETULE: Swap = true;
8625 case ISD::SETUGE: SSECC = 5; break;
8626 case ISD::SETULT: Swap = true;
8627 case ISD::SETUGT: SSECC = 6; break;
8628 case ISD::SETO: SSECC = 7; break;
8631 std::swap(Op0, Op1);
8633 // In the two special cases we can't handle, emit two comparisons.
8635 if (SetCCOpcode == ISD::SETUEQ) {
8637 UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8638 DAG.getConstant(3, MVT::i8));
8639 EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8640 DAG.getConstant(0, MVT::i8));
8641 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8643 if (SetCCOpcode == ISD::SETONE) {
8645 ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8646 DAG.getConstant(7, MVT::i8));
8647 NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8648 DAG.getConstant(4, MVT::i8));
8649 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8651 llvm_unreachable("Illegal FP comparison");
8653 // Handle all other FP comparisons here.
8654 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8655 DAG.getConstant(SSECC, MVT::i8));
8658 // Break 256-bit integer vector compare into smaller ones.
8659 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8660 return Lower256IntVSETCC(Op, DAG);
8662 // We are handling one of the integer comparisons here. Since SSE only has
8663 // GT and EQ comparisons for integer, swapping operands and multiple
8664 // operations may be required for some comparisons.
8666 bool Swap = false, Invert = false, FlipSigns = false;
8668 switch (SetCCOpcode) {
8670 case ISD::SETNE: Invert = true;
8671 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8672 case ISD::SETLT: Swap = true;
8673 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8674 case ISD::SETGE: Swap = true;
8675 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8676 case ISD::SETULT: Swap = true;
8677 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8678 case ISD::SETUGE: Swap = true;
8679 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8682 std::swap(Op0, Op1);
8684 // Check that the operation in question is available (most are plain SSE2,
8685 // but PCMPGTQ and PCMPEQQ have different requirements).
8686 if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8688 if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8691 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8692 // bits of the inputs before performing those operations.
8694 EVT EltVT = VT.getVectorElementType();
8695 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8697 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8698 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8700 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8701 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8704 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8706 // If the logical-not of the result is required, perform that now.
8708 Result = DAG.getNOT(dl, Result, VT);
8713 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8714 static bool isX86LogicalCmp(SDValue Op) {
8715 unsigned Opc = Op.getNode()->getOpcode();
8716 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8717 Opc == X86ISD::SAHF)
8719 if (Op.getResNo() == 1 &&
8720 (Opc == X86ISD::ADD ||
8721 Opc == X86ISD::SUB ||
8722 Opc == X86ISD::ADC ||
8723 Opc == X86ISD::SBB ||
8724 Opc == X86ISD::SMUL ||
8725 Opc == X86ISD::UMUL ||
8726 Opc == X86ISD::INC ||
8727 Opc == X86ISD::DEC ||
8728 Opc == X86ISD::OR ||
8729 Opc == X86ISD::XOR ||
8730 Opc == X86ISD::AND))
8733 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8739 static bool isZero(SDValue V) {
8740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8741 return C && C->isNullValue();
8744 static bool isAllOnes(SDValue V) {
8745 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8746 return C && C->isAllOnesValue();
8749 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8750 if (V.getOpcode() != ISD::TRUNCATE)
8753 SDValue VOp0 = V.getOperand(0);
8754 unsigned InBits = VOp0.getValueSizeInBits();
8755 unsigned Bits = V.getValueSizeInBits();
8756 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8759 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8760 bool addTest = true;
8761 SDValue Cond = Op.getOperand(0);
8762 SDValue Op1 = Op.getOperand(1);
8763 SDValue Op2 = Op.getOperand(2);
8764 DebugLoc DL = Op.getDebugLoc();
8767 if (Cond.getOpcode() == ISD::SETCC) {
8768 SDValue NewCond = LowerSETCC(Cond, DAG);
8769 if (NewCond.getNode())
8773 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8774 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8775 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8776 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8777 if (Cond.getOpcode() == X86ISD::SETCC &&
8778 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8779 isZero(Cond.getOperand(1).getOperand(1))) {
8780 SDValue Cmp = Cond.getOperand(1);
8782 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8784 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8785 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8786 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8788 SDValue CmpOp0 = Cmp.getOperand(0);
8789 // Apply further optimizations for special cases
8790 // (select (x != 0), -1, 0) -> neg & sbb
8791 // (select (x == 0), 0, -1) -> neg & sbb
8792 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8793 if (YC->isNullValue() &&
8794 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8795 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8796 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8797 DAG.getConstant(0, CmpOp0.getValueType()),
8799 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8800 DAG.getConstant(X86::COND_B, MVT::i8),
8801 SDValue(Neg.getNode(), 1));
8805 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8806 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8807 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8809 SDValue Res = // Res = 0 or -1.
8810 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8811 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8813 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8814 Res = DAG.getNOT(DL, Res, Res.getValueType());
8816 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8817 if (N2C == 0 || !N2C->isNullValue())
8818 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8823 // Look past (and (setcc_carry (cmp ...)), 1).
8824 if (Cond.getOpcode() == ISD::AND &&
8825 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8826 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8827 if (C && C->getAPIntValue() == 1)
8828 Cond = Cond.getOperand(0);
8831 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8832 // setting operand in place of the X86ISD::SETCC.
8833 unsigned CondOpcode = Cond.getOpcode();
8834 if (CondOpcode == X86ISD::SETCC ||
8835 CondOpcode == X86ISD::SETCC_CARRY) {
8836 CC = Cond.getOperand(0);
8838 SDValue Cmp = Cond.getOperand(1);
8839 unsigned Opc = Cmp.getOpcode();
8840 EVT VT = Op.getValueType();
8842 bool IllegalFPCMov = false;
8843 if (VT.isFloatingPoint() && !VT.isVector() &&
8844 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8845 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8847 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8848 Opc == X86ISD::BT) { // FIXME
8852 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8853 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8854 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8855 Cond.getOperand(0).getValueType() != MVT::i8)) {
8856 SDValue LHS = Cond.getOperand(0);
8857 SDValue RHS = Cond.getOperand(1);
8861 switch (CondOpcode) {
8862 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8863 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8864 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8865 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8866 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8867 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8868 default: llvm_unreachable("unexpected overflowing operator");
8870 if (CondOpcode == ISD::UMULO)
8871 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8874 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8876 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8878 if (CondOpcode == ISD::UMULO)
8879 Cond = X86Op.getValue(2);
8881 Cond = X86Op.getValue(1);
8883 CC = DAG.getConstant(X86Cond, MVT::i8);
8888 // Look pass the truncate if the high bits are known zero.
8889 if (isTruncWithZeroHighBitsInput(Cond, DAG))
8890 Cond = Cond.getOperand(0);
8892 // We know the result of AND is compared against zero. Try to match
8894 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8895 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8896 if (NewSetCC.getNode()) {
8897 CC = NewSetCC.getOperand(0);
8898 Cond = NewSetCC.getOperand(1);
8905 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8906 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8909 // a < b ? -1 : 0 -> RES = ~setcc_carry
8910 // a < b ? 0 : -1 -> RES = setcc_carry
8911 // a >= b ? -1 : 0 -> RES = setcc_carry
8912 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8913 if (Cond.getOpcode() == X86ISD::SUB) {
8914 Cond = ConvertCmpIfNecessary(Cond, DAG);
8915 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8917 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8918 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8919 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8920 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8921 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8922 return DAG.getNOT(DL, Res, Res.getValueType());
8927 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8928 // condition is true.
8929 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8930 SDValue Ops[] = { Op2, Op1, CC, Cond };
8931 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8934 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8935 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8936 // from the AND / OR.
8937 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8938 Opc = Op.getOpcode();
8939 if (Opc != ISD::OR && Opc != ISD::AND)
8941 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8942 Op.getOperand(0).hasOneUse() &&
8943 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8944 Op.getOperand(1).hasOneUse());
8947 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8948 // 1 and that the SETCC node has a single use.
8949 static bool isXor1OfSetCC(SDValue Op) {
8950 if (Op.getOpcode() != ISD::XOR)
8952 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8953 if (N1C && N1C->getAPIntValue() == 1) {
8954 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8955 Op.getOperand(0).hasOneUse();
8960 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8961 bool addTest = true;
8962 SDValue Chain = Op.getOperand(0);
8963 SDValue Cond = Op.getOperand(1);
8964 SDValue Dest = Op.getOperand(2);
8965 DebugLoc dl = Op.getDebugLoc();
8967 bool Inverted = false;
8969 if (Cond.getOpcode() == ISD::SETCC) {
8970 // Check for setcc([su]{add,sub,mul}o == 0).
8971 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8972 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8973 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8974 Cond.getOperand(0).getResNo() == 1 &&
8975 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8976 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8977 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8978 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8979 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8980 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8982 Cond = Cond.getOperand(0);
8984 SDValue NewCond = LowerSETCC(Cond, DAG);
8985 if (NewCond.getNode())
8990 // FIXME: LowerXALUO doesn't handle these!!
8991 else if (Cond.getOpcode() == X86ISD::ADD ||
8992 Cond.getOpcode() == X86ISD::SUB ||
8993 Cond.getOpcode() == X86ISD::SMUL ||
8994 Cond.getOpcode() == X86ISD::UMUL)
8995 Cond = LowerXALUO(Cond, DAG);
8998 // Look pass (and (setcc_carry (cmp ...)), 1).
8999 if (Cond.getOpcode() == ISD::AND &&
9000 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9001 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9002 if (C && C->getAPIntValue() == 1)
9003 Cond = Cond.getOperand(0);
9006 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9007 // setting operand in place of the X86ISD::SETCC.
9008 unsigned CondOpcode = Cond.getOpcode();
9009 if (CondOpcode == X86ISD::SETCC ||
9010 CondOpcode == X86ISD::SETCC_CARRY) {
9011 CC = Cond.getOperand(0);
9013 SDValue Cmp = Cond.getOperand(1);
9014 unsigned Opc = Cmp.getOpcode();
9015 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9016 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9020 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9024 // These can only come from an arithmetic instruction with overflow,
9025 // e.g. SADDO, UADDO.
9026 Cond = Cond.getNode()->getOperand(1);
9032 CondOpcode = Cond.getOpcode();
9033 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9034 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9035 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9036 Cond.getOperand(0).getValueType() != MVT::i8)) {
9037 SDValue LHS = Cond.getOperand(0);
9038 SDValue RHS = Cond.getOperand(1);
9042 switch (CondOpcode) {
9043 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9044 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9045 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9046 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9047 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9048 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9049 default: llvm_unreachable("unexpected overflowing operator");
9052 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9053 if (CondOpcode == ISD::UMULO)
9054 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9057 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9059 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9061 if (CondOpcode == ISD::UMULO)
9062 Cond = X86Op.getValue(2);
9064 Cond = X86Op.getValue(1);
9066 CC = DAG.getConstant(X86Cond, MVT::i8);
9070 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9071 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9072 if (CondOpc == ISD::OR) {
9073 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9074 // two branches instead of an explicit OR instruction with a
9076 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9077 isX86LogicalCmp(Cmp)) {
9078 CC = Cond.getOperand(0).getOperand(0);
9079 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9080 Chain, Dest, CC, Cmp);
9081 CC = Cond.getOperand(1).getOperand(0);
9085 } else { // ISD::AND
9086 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9087 // two branches instead of an explicit AND instruction with a
9088 // separate test. However, we only do this if this block doesn't
9089 // have a fall-through edge, because this requires an explicit
9090 // jmp when the condition is false.
9091 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9092 isX86LogicalCmp(Cmp) &&
9093 Op.getNode()->hasOneUse()) {
9094 X86::CondCode CCode =
9095 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9096 CCode = X86::GetOppositeBranchCondition(CCode);
9097 CC = DAG.getConstant(CCode, MVT::i8);
9098 SDNode *User = *Op.getNode()->use_begin();
9099 // Look for an unconditional branch following this conditional branch.
9100 // We need this because we need to reverse the successors in order
9101 // to implement FCMP_OEQ.
9102 if (User->getOpcode() == ISD::BR) {
9103 SDValue FalseBB = User->getOperand(1);
9105 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9106 assert(NewBR == User);
9110 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9111 Chain, Dest, CC, Cmp);
9112 X86::CondCode CCode =
9113 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9114 CCode = X86::GetOppositeBranchCondition(CCode);
9115 CC = DAG.getConstant(CCode, MVT::i8);
9121 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9122 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9123 // It should be transformed during dag combiner except when the condition
9124 // is set by a arithmetics with overflow node.
9125 X86::CondCode CCode =
9126 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9127 CCode = X86::GetOppositeBranchCondition(CCode);
9128 CC = DAG.getConstant(CCode, MVT::i8);
9129 Cond = Cond.getOperand(0).getOperand(1);
9131 } else if (Cond.getOpcode() == ISD::SETCC &&
9132 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9133 // For FCMP_OEQ, we can emit
9134 // two branches instead of an explicit AND instruction with a
9135 // separate test. However, we only do this if this block doesn't
9136 // have a fall-through edge, because this requires an explicit
9137 // jmp when the condition is false.
9138 if (Op.getNode()->hasOneUse()) {
9139 SDNode *User = *Op.getNode()->use_begin();
9140 // Look for an unconditional branch following this conditional branch.
9141 // We need this because we need to reverse the successors in order
9142 // to implement FCMP_OEQ.
9143 if (User->getOpcode() == ISD::BR) {
9144 SDValue FalseBB = User->getOperand(1);
9146 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9147 assert(NewBR == User);
9151 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9152 Cond.getOperand(0), Cond.getOperand(1));
9153 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9154 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9155 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9156 Chain, Dest, CC, Cmp);
9157 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9162 } else if (Cond.getOpcode() == ISD::SETCC &&
9163 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9164 // For FCMP_UNE, we can emit
9165 // two branches instead of an explicit AND instruction with a
9166 // separate test. However, we only do this if this block doesn't
9167 // have a fall-through edge, because this requires an explicit
9168 // jmp when the condition is false.
9169 if (Op.getNode()->hasOneUse()) {
9170 SDNode *User = *Op.getNode()->use_begin();
9171 // Look for an unconditional branch following this conditional branch.
9172 // We need this because we need to reverse the successors in order
9173 // to implement FCMP_UNE.
9174 if (User->getOpcode() == ISD::BR) {
9175 SDValue FalseBB = User->getOperand(1);
9177 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9178 assert(NewBR == User);
9181 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9182 Cond.getOperand(0), Cond.getOperand(1));
9183 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9184 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9185 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9186 Chain, Dest, CC, Cmp);
9187 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9197 // Look pass the truncate if the high bits are known zero.
9198 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9199 Cond = Cond.getOperand(0);
9201 // We know the result of AND is compared against zero. Try to match
9203 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9204 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9205 if (NewSetCC.getNode()) {
9206 CC = NewSetCC.getOperand(0);
9207 Cond = NewSetCC.getOperand(1);
9214 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9215 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9217 Cond = ConvertCmpIfNecessary(Cond, DAG);
9218 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9219 Chain, Dest, CC, Cond);
9223 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9224 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9225 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9226 // that the guard pages used by the OS virtual memory manager are allocated in
9227 // correct sequence.
9229 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9230 SelectionDAG &DAG) const {
9231 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9232 getTargetMachine().Options.EnableSegmentedStacks) &&
9233 "This should be used only on Windows targets or when segmented stacks "
9235 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9236 DebugLoc dl = Op.getDebugLoc();
9239 SDValue Chain = Op.getOperand(0);
9240 SDValue Size = Op.getOperand(1);
9241 // FIXME: Ensure alignment here
9243 bool Is64Bit = Subtarget->is64Bit();
9244 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9246 if (getTargetMachine().Options.EnableSegmentedStacks) {
9247 MachineFunction &MF = DAG.getMachineFunction();
9248 MachineRegisterInfo &MRI = MF.getRegInfo();
9251 // The 64 bit implementation of segmented stacks needs to clobber both r10
9252 // r11. This makes it impossible to use it along with nested parameters.
9253 const Function *F = MF.getFunction();
9255 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9257 if (I->hasNestAttr())
9258 report_fatal_error("Cannot use segmented stacks with functions that "
9259 "have nested arguments.");
9262 const TargetRegisterClass *AddrRegClass =
9263 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9264 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9265 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9266 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9267 DAG.getRegister(Vreg, SPTy));
9268 SDValue Ops1[2] = { Value, Chain };
9269 return DAG.getMergeValues(Ops1, 2, dl);
9272 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9274 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9275 Flag = Chain.getValue(1);
9276 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9278 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9279 Flag = Chain.getValue(1);
9281 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9283 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9284 return DAG.getMergeValues(Ops1, 2, dl);
9288 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9289 MachineFunction &MF = DAG.getMachineFunction();
9290 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9292 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9293 DebugLoc DL = Op.getDebugLoc();
9295 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9296 // vastart just stores the address of the VarArgsFrameIndex slot into the
9297 // memory location argument.
9298 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9300 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9301 MachinePointerInfo(SV), false, false, 0);
9305 // gp_offset (0 - 6 * 8)
9306 // fp_offset (48 - 48 + 8 * 16)
9307 // overflow_arg_area (point to parameters coming in memory).
9309 SmallVector<SDValue, 8> MemOps;
9310 SDValue FIN = Op.getOperand(1);
9312 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9313 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9315 FIN, MachinePointerInfo(SV), false, false, 0);
9316 MemOps.push_back(Store);
9319 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9320 FIN, DAG.getIntPtrConstant(4));
9321 Store = DAG.getStore(Op.getOperand(0), DL,
9322 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9324 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9325 MemOps.push_back(Store);
9327 // Store ptr to overflow_arg_area
9328 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9329 FIN, DAG.getIntPtrConstant(4));
9330 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9332 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9333 MachinePointerInfo(SV, 8),
9335 MemOps.push_back(Store);
9337 // Store ptr to reg_save_area.
9338 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9339 FIN, DAG.getIntPtrConstant(8));
9340 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9342 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9343 MachinePointerInfo(SV, 16), false, false, 0);
9344 MemOps.push_back(Store);
9345 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9346 &MemOps[0], MemOps.size());
9349 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9350 assert(Subtarget->is64Bit() &&
9351 "LowerVAARG only handles 64-bit va_arg!");
9352 assert((Subtarget->isTargetLinux() ||
9353 Subtarget->isTargetDarwin()) &&
9354 "Unhandled target in LowerVAARG");
9355 assert(Op.getNode()->getNumOperands() == 4);
9356 SDValue Chain = Op.getOperand(0);
9357 SDValue SrcPtr = Op.getOperand(1);
9358 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9359 unsigned Align = Op.getConstantOperandVal(3);
9360 DebugLoc dl = Op.getDebugLoc();
9362 EVT ArgVT = Op.getNode()->getValueType(0);
9363 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9364 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9367 // Decide which area this value should be read from.
9368 // TODO: Implement the AMD64 ABI in its entirety. This simple
9369 // selection mechanism works only for the basic types.
9370 if (ArgVT == MVT::f80) {
9371 llvm_unreachable("va_arg for f80 not yet implemented");
9372 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9373 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9374 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9375 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9377 llvm_unreachable("Unhandled argument type in LowerVAARG");
9381 // Sanity Check: Make sure using fp_offset makes sense.
9382 assert(!getTargetMachine().Options.UseSoftFloat &&
9383 !(DAG.getMachineFunction()
9384 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9385 Subtarget->hasSSE1());
9388 // Insert VAARG_64 node into the DAG
9389 // VAARG_64 returns two values: Variable Argument Address, Chain
9390 SmallVector<SDValue, 11> InstOps;
9391 InstOps.push_back(Chain);
9392 InstOps.push_back(SrcPtr);
9393 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9394 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9395 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9396 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9397 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9398 VTs, &InstOps[0], InstOps.size(),
9400 MachinePointerInfo(SV),
9405 Chain = VAARG.getValue(1);
9407 // Load the next argument and return it
9408 return DAG.getLoad(ArgVT, dl,
9411 MachinePointerInfo(),
9412 false, false, false, 0);
9415 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9416 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9417 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9418 SDValue Chain = Op.getOperand(0);
9419 SDValue DstPtr = Op.getOperand(1);
9420 SDValue SrcPtr = Op.getOperand(2);
9421 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9422 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9423 DebugLoc DL = Op.getDebugLoc();
9425 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9426 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9428 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9431 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9432 // may or may not be a constant. Takes immediate version of shift as input.
9433 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9434 SDValue SrcOp, SDValue ShAmt,
9435 SelectionDAG &DAG) {
9436 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9438 if (isa<ConstantSDNode>(ShAmt)) {
9439 // Constant may be a TargetConstant. Use a regular constant.
9440 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9442 default: llvm_unreachable("Unknown target vector shift node");
9446 return DAG.getNode(Opc, dl, VT, SrcOp,
9447 DAG.getConstant(ShiftAmt, MVT::i32));
9451 // Change opcode to non-immediate version
9453 default: llvm_unreachable("Unknown target vector shift node");
9454 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9455 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9456 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9459 // Need to build a vector containing shift amount
9460 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9463 ShOps[1] = DAG.getConstant(0, MVT::i32);
9464 ShOps[2] = DAG.getUNDEF(MVT::i32);
9465 ShOps[3] = DAG.getUNDEF(MVT::i32);
9466 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9468 // The return type has to be a 128-bit type with the same element
9469 // type as the input type.
9470 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9471 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9473 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9474 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9478 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9479 DebugLoc dl = Op.getDebugLoc();
9480 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9482 default: return SDValue(); // Don't custom lower most intrinsics.
9483 // Comparison intrinsics.
9484 case Intrinsic::x86_sse_comieq_ss:
9485 case Intrinsic::x86_sse_comilt_ss:
9486 case Intrinsic::x86_sse_comile_ss:
9487 case Intrinsic::x86_sse_comigt_ss:
9488 case Intrinsic::x86_sse_comige_ss:
9489 case Intrinsic::x86_sse_comineq_ss:
9490 case Intrinsic::x86_sse_ucomieq_ss:
9491 case Intrinsic::x86_sse_ucomilt_ss:
9492 case Intrinsic::x86_sse_ucomile_ss:
9493 case Intrinsic::x86_sse_ucomigt_ss:
9494 case Intrinsic::x86_sse_ucomige_ss:
9495 case Intrinsic::x86_sse_ucomineq_ss:
9496 case Intrinsic::x86_sse2_comieq_sd:
9497 case Intrinsic::x86_sse2_comilt_sd:
9498 case Intrinsic::x86_sse2_comile_sd:
9499 case Intrinsic::x86_sse2_comigt_sd:
9500 case Intrinsic::x86_sse2_comige_sd:
9501 case Intrinsic::x86_sse2_comineq_sd:
9502 case Intrinsic::x86_sse2_ucomieq_sd:
9503 case Intrinsic::x86_sse2_ucomilt_sd:
9504 case Intrinsic::x86_sse2_ucomile_sd:
9505 case Intrinsic::x86_sse2_ucomigt_sd:
9506 case Intrinsic::x86_sse2_ucomige_sd:
9507 case Intrinsic::x86_sse2_ucomineq_sd: {
9509 ISD::CondCode CC = ISD::SETCC_INVALID;
9511 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9512 case Intrinsic::x86_sse_comieq_ss:
9513 case Intrinsic::x86_sse2_comieq_sd:
9517 case Intrinsic::x86_sse_comilt_ss:
9518 case Intrinsic::x86_sse2_comilt_sd:
9522 case Intrinsic::x86_sse_comile_ss:
9523 case Intrinsic::x86_sse2_comile_sd:
9527 case Intrinsic::x86_sse_comigt_ss:
9528 case Intrinsic::x86_sse2_comigt_sd:
9532 case Intrinsic::x86_sse_comige_ss:
9533 case Intrinsic::x86_sse2_comige_sd:
9537 case Intrinsic::x86_sse_comineq_ss:
9538 case Intrinsic::x86_sse2_comineq_sd:
9542 case Intrinsic::x86_sse_ucomieq_ss:
9543 case Intrinsic::x86_sse2_ucomieq_sd:
9544 Opc = X86ISD::UCOMI;
9547 case Intrinsic::x86_sse_ucomilt_ss:
9548 case Intrinsic::x86_sse2_ucomilt_sd:
9549 Opc = X86ISD::UCOMI;
9552 case Intrinsic::x86_sse_ucomile_ss:
9553 case Intrinsic::x86_sse2_ucomile_sd:
9554 Opc = X86ISD::UCOMI;
9557 case Intrinsic::x86_sse_ucomigt_ss:
9558 case Intrinsic::x86_sse2_ucomigt_sd:
9559 Opc = X86ISD::UCOMI;
9562 case Intrinsic::x86_sse_ucomige_ss:
9563 case Intrinsic::x86_sse2_ucomige_sd:
9564 Opc = X86ISD::UCOMI;
9567 case Intrinsic::x86_sse_ucomineq_ss:
9568 case Intrinsic::x86_sse2_ucomineq_sd:
9569 Opc = X86ISD::UCOMI;
9574 SDValue LHS = Op.getOperand(1);
9575 SDValue RHS = Op.getOperand(2);
9576 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9577 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9578 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9579 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9580 DAG.getConstant(X86CC, MVT::i8), Cond);
9581 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9583 // Arithmetic intrinsics.
9584 case Intrinsic::x86_sse2_pmulu_dq:
9585 case Intrinsic::x86_avx2_pmulu_dq:
9586 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9587 Op.getOperand(1), Op.getOperand(2));
9588 case Intrinsic::x86_sse3_hadd_ps:
9589 case Intrinsic::x86_sse3_hadd_pd:
9590 case Intrinsic::x86_avx_hadd_ps_256:
9591 case Intrinsic::x86_avx_hadd_pd_256:
9592 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9593 Op.getOperand(1), Op.getOperand(2));
9594 case Intrinsic::x86_sse3_hsub_ps:
9595 case Intrinsic::x86_sse3_hsub_pd:
9596 case Intrinsic::x86_avx_hsub_ps_256:
9597 case Intrinsic::x86_avx_hsub_pd_256:
9598 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9599 Op.getOperand(1), Op.getOperand(2));
9600 case Intrinsic::x86_ssse3_phadd_w_128:
9601 case Intrinsic::x86_ssse3_phadd_d_128:
9602 case Intrinsic::x86_avx2_phadd_w:
9603 case Intrinsic::x86_avx2_phadd_d:
9604 return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9605 Op.getOperand(1), Op.getOperand(2));
9606 case Intrinsic::x86_ssse3_phsub_w_128:
9607 case Intrinsic::x86_ssse3_phsub_d_128:
9608 case Intrinsic::x86_avx2_phsub_w:
9609 case Intrinsic::x86_avx2_phsub_d:
9610 return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9611 Op.getOperand(1), Op.getOperand(2));
9612 case Intrinsic::x86_avx2_psllv_d:
9613 case Intrinsic::x86_avx2_psllv_q:
9614 case Intrinsic::x86_avx2_psllv_d_256:
9615 case Intrinsic::x86_avx2_psllv_q_256:
9616 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9617 Op.getOperand(1), Op.getOperand(2));
9618 case Intrinsic::x86_avx2_psrlv_d:
9619 case Intrinsic::x86_avx2_psrlv_q:
9620 case Intrinsic::x86_avx2_psrlv_d_256:
9621 case Intrinsic::x86_avx2_psrlv_q_256:
9622 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9623 Op.getOperand(1), Op.getOperand(2));
9624 case Intrinsic::x86_avx2_psrav_d:
9625 case Intrinsic::x86_avx2_psrav_d_256:
9626 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9627 Op.getOperand(1), Op.getOperand(2));
9628 case Intrinsic::x86_ssse3_pshuf_b_128:
9629 case Intrinsic::x86_avx2_pshuf_b:
9630 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9631 Op.getOperand(1), Op.getOperand(2));
9632 case Intrinsic::x86_ssse3_psign_b_128:
9633 case Intrinsic::x86_ssse3_psign_w_128:
9634 case Intrinsic::x86_ssse3_psign_d_128:
9635 case Intrinsic::x86_avx2_psign_b:
9636 case Intrinsic::x86_avx2_psign_w:
9637 case Intrinsic::x86_avx2_psign_d:
9638 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9639 Op.getOperand(1), Op.getOperand(2));
9640 case Intrinsic::x86_sse41_insertps:
9641 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9642 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9643 case Intrinsic::x86_avx_vperm2f128_ps_256:
9644 case Intrinsic::x86_avx_vperm2f128_pd_256:
9645 case Intrinsic::x86_avx_vperm2f128_si_256:
9646 case Intrinsic::x86_avx2_vperm2i128:
9647 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9648 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9649 case Intrinsic::x86_avx2_permd:
9650 case Intrinsic::x86_avx2_permps:
9651 // Operands intentionally swapped. Mask is last operand to intrinsic,
9652 // but second operand for node/intruction.
9653 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9654 Op.getOperand(2), Op.getOperand(1));
9656 // ptest and testp intrinsics. The intrinsic these come from are designed to
9657 // return an integer value, not just an instruction so lower it to the ptest
9658 // or testp pattern and a setcc for the result.
9659 case Intrinsic::x86_sse41_ptestz:
9660 case Intrinsic::x86_sse41_ptestc:
9661 case Intrinsic::x86_sse41_ptestnzc:
9662 case Intrinsic::x86_avx_ptestz_256:
9663 case Intrinsic::x86_avx_ptestc_256:
9664 case Intrinsic::x86_avx_ptestnzc_256:
9665 case Intrinsic::x86_avx_vtestz_ps:
9666 case Intrinsic::x86_avx_vtestc_ps:
9667 case Intrinsic::x86_avx_vtestnzc_ps:
9668 case Intrinsic::x86_avx_vtestz_pd:
9669 case Intrinsic::x86_avx_vtestc_pd:
9670 case Intrinsic::x86_avx_vtestnzc_pd:
9671 case Intrinsic::x86_avx_vtestz_ps_256:
9672 case Intrinsic::x86_avx_vtestc_ps_256:
9673 case Intrinsic::x86_avx_vtestnzc_ps_256:
9674 case Intrinsic::x86_avx_vtestz_pd_256:
9675 case Intrinsic::x86_avx_vtestc_pd_256:
9676 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9677 bool IsTestPacked = false;
9680 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9681 case Intrinsic::x86_avx_vtestz_ps:
9682 case Intrinsic::x86_avx_vtestz_pd:
9683 case Intrinsic::x86_avx_vtestz_ps_256:
9684 case Intrinsic::x86_avx_vtestz_pd_256:
9685 IsTestPacked = true; // Fallthrough
9686 case Intrinsic::x86_sse41_ptestz:
9687 case Intrinsic::x86_avx_ptestz_256:
9689 X86CC = X86::COND_E;
9691 case Intrinsic::x86_avx_vtestc_ps:
9692 case Intrinsic::x86_avx_vtestc_pd:
9693 case Intrinsic::x86_avx_vtestc_ps_256:
9694 case Intrinsic::x86_avx_vtestc_pd_256:
9695 IsTestPacked = true; // Fallthrough
9696 case Intrinsic::x86_sse41_ptestc:
9697 case Intrinsic::x86_avx_ptestc_256:
9699 X86CC = X86::COND_B;
9701 case Intrinsic::x86_avx_vtestnzc_ps:
9702 case Intrinsic::x86_avx_vtestnzc_pd:
9703 case Intrinsic::x86_avx_vtestnzc_ps_256:
9704 case Intrinsic::x86_avx_vtestnzc_pd_256:
9705 IsTestPacked = true; // Fallthrough
9706 case Intrinsic::x86_sse41_ptestnzc:
9707 case Intrinsic::x86_avx_ptestnzc_256:
9709 X86CC = X86::COND_A;
9713 SDValue LHS = Op.getOperand(1);
9714 SDValue RHS = Op.getOperand(2);
9715 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9716 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9717 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9718 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9719 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9722 // SSE/AVX shift intrinsics
9723 case Intrinsic::x86_sse2_psll_w:
9724 case Intrinsic::x86_sse2_psll_d:
9725 case Intrinsic::x86_sse2_psll_q:
9726 case Intrinsic::x86_avx2_psll_w:
9727 case Intrinsic::x86_avx2_psll_d:
9728 case Intrinsic::x86_avx2_psll_q:
9729 return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9730 Op.getOperand(1), Op.getOperand(2));
9731 case Intrinsic::x86_sse2_psrl_w:
9732 case Intrinsic::x86_sse2_psrl_d:
9733 case Intrinsic::x86_sse2_psrl_q:
9734 case Intrinsic::x86_avx2_psrl_w:
9735 case Intrinsic::x86_avx2_psrl_d:
9736 case Intrinsic::x86_avx2_psrl_q:
9737 return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9738 Op.getOperand(1), Op.getOperand(2));
9739 case Intrinsic::x86_sse2_psra_w:
9740 case Intrinsic::x86_sse2_psra_d:
9741 case Intrinsic::x86_avx2_psra_w:
9742 case Intrinsic::x86_avx2_psra_d:
9743 return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9744 Op.getOperand(1), Op.getOperand(2));
9745 case Intrinsic::x86_sse2_pslli_w:
9746 case Intrinsic::x86_sse2_pslli_d:
9747 case Intrinsic::x86_sse2_pslli_q:
9748 case Intrinsic::x86_avx2_pslli_w:
9749 case Intrinsic::x86_avx2_pslli_d:
9750 case Intrinsic::x86_avx2_pslli_q:
9751 return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9752 Op.getOperand(1), Op.getOperand(2), DAG);
9753 case Intrinsic::x86_sse2_psrli_w:
9754 case Intrinsic::x86_sse2_psrli_d:
9755 case Intrinsic::x86_sse2_psrli_q:
9756 case Intrinsic::x86_avx2_psrli_w:
9757 case Intrinsic::x86_avx2_psrli_d:
9758 case Intrinsic::x86_avx2_psrli_q:
9759 return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9760 Op.getOperand(1), Op.getOperand(2), DAG);
9761 case Intrinsic::x86_sse2_psrai_w:
9762 case Intrinsic::x86_sse2_psrai_d:
9763 case Intrinsic::x86_avx2_psrai_w:
9764 case Intrinsic::x86_avx2_psrai_d:
9765 return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9766 Op.getOperand(1), Op.getOperand(2), DAG);
9767 // Fix vector shift instructions where the last operand is a non-immediate
9769 case Intrinsic::x86_mmx_pslli_w:
9770 case Intrinsic::x86_mmx_pslli_d:
9771 case Intrinsic::x86_mmx_pslli_q:
9772 case Intrinsic::x86_mmx_psrli_w:
9773 case Intrinsic::x86_mmx_psrli_d:
9774 case Intrinsic::x86_mmx_psrli_q:
9775 case Intrinsic::x86_mmx_psrai_w:
9776 case Intrinsic::x86_mmx_psrai_d: {
9777 SDValue ShAmt = Op.getOperand(2);
9778 if (isa<ConstantSDNode>(ShAmt))
9781 unsigned NewIntNo = 0;
9783 case Intrinsic::x86_mmx_pslli_w:
9784 NewIntNo = Intrinsic::x86_mmx_psll_w;
9786 case Intrinsic::x86_mmx_pslli_d:
9787 NewIntNo = Intrinsic::x86_mmx_psll_d;
9789 case Intrinsic::x86_mmx_pslli_q:
9790 NewIntNo = Intrinsic::x86_mmx_psll_q;
9792 case Intrinsic::x86_mmx_psrli_w:
9793 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9795 case Intrinsic::x86_mmx_psrli_d:
9796 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9798 case Intrinsic::x86_mmx_psrli_q:
9799 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9801 case Intrinsic::x86_mmx_psrai_w:
9802 NewIntNo = Intrinsic::x86_mmx_psra_w;
9804 case Intrinsic::x86_mmx_psrai_d:
9805 NewIntNo = Intrinsic::x86_mmx_psra_d;
9807 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9810 // The vector shift intrinsics with scalars uses 32b shift amounts but
9811 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9813 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9814 DAG.getConstant(0, MVT::i32));
9815 // FIXME this must be lowered to get rid of the invalid type.
9817 EVT VT = Op.getValueType();
9818 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9819 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9820 DAG.getConstant(NewIntNo, MVT::i32),
9821 Op.getOperand(1), ShAmt);
9823 case Intrinsic::x86_sse42_pcmpistria128:
9824 case Intrinsic::x86_sse42_pcmpestria128:
9825 case Intrinsic::x86_sse42_pcmpistric128:
9826 case Intrinsic::x86_sse42_pcmpestric128:
9827 case Intrinsic::x86_sse42_pcmpistrio128:
9828 case Intrinsic::x86_sse42_pcmpestrio128:
9829 case Intrinsic::x86_sse42_pcmpistris128:
9830 case Intrinsic::x86_sse42_pcmpestris128:
9831 case Intrinsic::x86_sse42_pcmpistriz128:
9832 case Intrinsic::x86_sse42_pcmpestriz128: {
9836 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9837 case Intrinsic::x86_sse42_pcmpistria128:
9838 Opcode = X86ISD::PCMPISTRI;
9839 X86CC = X86::COND_A;
9841 case Intrinsic::x86_sse42_pcmpestria128:
9842 Opcode = X86ISD::PCMPESTRI;
9843 X86CC = X86::COND_A;
9845 case Intrinsic::x86_sse42_pcmpistric128:
9846 Opcode = X86ISD::PCMPISTRI;
9847 X86CC = X86::COND_B;
9849 case Intrinsic::x86_sse42_pcmpestric128:
9850 Opcode = X86ISD::PCMPESTRI;
9851 X86CC = X86::COND_B;
9853 case Intrinsic::x86_sse42_pcmpistrio128:
9854 Opcode = X86ISD::PCMPISTRI;
9855 X86CC = X86::COND_O;
9857 case Intrinsic::x86_sse42_pcmpestrio128:
9858 Opcode = X86ISD::PCMPESTRI;
9859 X86CC = X86::COND_O;
9861 case Intrinsic::x86_sse42_pcmpistris128:
9862 Opcode = X86ISD::PCMPISTRI;
9863 X86CC = X86::COND_S;
9865 case Intrinsic::x86_sse42_pcmpestris128:
9866 Opcode = X86ISD::PCMPESTRI;
9867 X86CC = X86::COND_S;
9869 case Intrinsic::x86_sse42_pcmpistriz128:
9870 Opcode = X86ISD::PCMPISTRI;
9871 X86CC = X86::COND_E;
9873 case Intrinsic::x86_sse42_pcmpestriz128:
9874 Opcode = X86ISD::PCMPESTRI;
9875 X86CC = X86::COND_E;
9878 SmallVector<SDValue, 5> NewOps;
9879 NewOps.append(Op->op_begin()+1, Op->op_end());
9880 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9881 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9882 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9883 DAG.getConstant(X86CC, MVT::i8),
9884 SDValue(PCMP.getNode(), 1));
9885 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9887 case Intrinsic::x86_sse42_pcmpistri128:
9888 case Intrinsic::x86_sse42_pcmpestri128: {
9890 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
9891 Opcode = X86ISD::PCMPISTRI;
9893 Opcode = X86ISD::PCMPESTRI;
9895 SmallVector<SDValue, 5> NewOps;
9896 NewOps.append(Op->op_begin()+1, Op->op_end());
9897 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9898 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9904 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9905 DebugLoc dl = Op.getDebugLoc();
9906 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9908 default: return SDValue(); // Don't custom lower most intrinsics.
9910 // RDRAND intrinsics.
9911 case Intrinsic::x86_rdrand_16:
9912 case Intrinsic::x86_rdrand_32:
9913 case Intrinsic::x86_rdrand_64: {
9914 // Emit the node with the right value type.
9915 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
9916 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
9918 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
9919 // return the value from Rand, which is always 0, casted to i32.
9920 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
9921 DAG.getConstant(1, Op->getValueType(1)),
9922 DAG.getConstant(X86::COND_B, MVT::i32),
9923 SDValue(Result.getNode(), 1) };
9924 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
9925 DAG.getVTList(Op->getValueType(1), MVT::Glue),
9928 // Return { result, isValid, chain }.
9929 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
9930 SDValue(Result.getNode(), 2));
9935 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9936 SelectionDAG &DAG) const {
9937 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9938 MFI->setReturnAddressIsTaken(true);
9940 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9941 DebugLoc dl = Op.getDebugLoc();
9944 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9946 DAG.getConstant(TD->getPointerSize(),
9947 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9948 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9949 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9951 MachinePointerInfo(), false, false, false, 0);
9954 // Just load the return address.
9955 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9956 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9957 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9960 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9961 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9962 MFI->setFrameAddressIsTaken(true);
9964 EVT VT = Op.getValueType();
9965 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9966 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9967 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9968 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9970 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9971 MachinePointerInfo(),
9972 false, false, false, 0);
9976 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9977 SelectionDAG &DAG) const {
9978 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9981 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9982 SDValue Chain = Op.getOperand(0);
9983 SDValue Offset = Op.getOperand(1);
9984 SDValue Handler = Op.getOperand(2);
9985 DebugLoc dl = Op.getDebugLoc();
9987 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9988 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9990 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9992 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9993 DAG.getIntPtrConstant(TD->getPointerSize()));
9994 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9995 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9997 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9999 return DAG.getNode(X86ISD::EH_RETURN, dl,
10001 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10004 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10005 SelectionDAG &DAG) const {
10006 return Op.getOperand(0);
10009 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10010 SelectionDAG &DAG) const {
10011 SDValue Root = Op.getOperand(0);
10012 SDValue Trmp = Op.getOperand(1); // trampoline
10013 SDValue FPtr = Op.getOperand(2); // nested function
10014 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10015 DebugLoc dl = Op.getDebugLoc();
10017 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10019 if (Subtarget->is64Bit()) {
10020 SDValue OutChains[6];
10022 // Large code-model.
10023 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10024 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10026 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10027 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10029 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10031 // Load the pointer to the nested function into R11.
10032 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10033 SDValue Addr = Trmp;
10034 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10035 Addr, MachinePointerInfo(TrmpAddr),
10038 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10039 DAG.getConstant(2, MVT::i64));
10040 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10041 MachinePointerInfo(TrmpAddr, 2),
10044 // Load the 'nest' parameter value into R10.
10045 // R10 is specified in X86CallingConv.td
10046 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10047 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10048 DAG.getConstant(10, MVT::i64));
10049 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10050 Addr, MachinePointerInfo(TrmpAddr, 10),
10053 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10054 DAG.getConstant(12, MVT::i64));
10055 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10056 MachinePointerInfo(TrmpAddr, 12),
10059 // Jump to the nested function.
10060 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10061 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10062 DAG.getConstant(20, MVT::i64));
10063 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10064 Addr, MachinePointerInfo(TrmpAddr, 20),
10067 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10068 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10069 DAG.getConstant(22, MVT::i64));
10070 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10071 MachinePointerInfo(TrmpAddr, 22),
10074 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10076 const Function *Func =
10077 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10078 CallingConv::ID CC = Func->getCallingConv();
10083 llvm_unreachable("Unsupported calling convention");
10084 case CallingConv::C:
10085 case CallingConv::X86_StdCall: {
10086 // Pass 'nest' parameter in ECX.
10087 // Must be kept in sync with X86CallingConv.td
10088 NestReg = X86::ECX;
10090 // Check that ECX wasn't needed by an 'inreg' parameter.
10091 FunctionType *FTy = Func->getFunctionType();
10092 const AttrListPtr &Attrs = Func->getAttributes();
10094 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10095 unsigned InRegCount = 0;
10098 for (FunctionType::param_iterator I = FTy->param_begin(),
10099 E = FTy->param_end(); I != E; ++I, ++Idx)
10100 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10101 // FIXME: should only count parameters that are lowered to integers.
10102 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10104 if (InRegCount > 2) {
10105 report_fatal_error("Nest register in use - reduce number of inreg"
10111 case CallingConv::X86_FastCall:
10112 case CallingConv::X86_ThisCall:
10113 case CallingConv::Fast:
10114 // Pass 'nest' parameter in EAX.
10115 // Must be kept in sync with X86CallingConv.td
10116 NestReg = X86::EAX;
10120 SDValue OutChains[4];
10121 SDValue Addr, Disp;
10123 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10124 DAG.getConstant(10, MVT::i32));
10125 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10127 // This is storing the opcode for MOV32ri.
10128 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10129 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10130 OutChains[0] = DAG.getStore(Root, dl,
10131 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10132 Trmp, MachinePointerInfo(TrmpAddr),
10135 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10136 DAG.getConstant(1, MVT::i32));
10137 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10138 MachinePointerInfo(TrmpAddr, 1),
10141 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10142 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10143 DAG.getConstant(5, MVT::i32));
10144 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10145 MachinePointerInfo(TrmpAddr, 5),
10148 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10149 DAG.getConstant(6, MVT::i32));
10150 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10151 MachinePointerInfo(TrmpAddr, 6),
10154 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10158 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10159 SelectionDAG &DAG) const {
10161 The rounding mode is in bits 11:10 of FPSR, and has the following
10163 00 Round to nearest
10168 FLT_ROUNDS, on the other hand, expects the following:
10175 To perform the conversion, we do:
10176 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10179 MachineFunction &MF = DAG.getMachineFunction();
10180 const TargetMachine &TM = MF.getTarget();
10181 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10182 unsigned StackAlignment = TFI.getStackAlignment();
10183 EVT VT = Op.getValueType();
10184 DebugLoc DL = Op.getDebugLoc();
10186 // Save FP Control Word to stack slot
10187 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10188 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10191 MachineMemOperand *MMO =
10192 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10193 MachineMemOperand::MOStore, 2, 2);
10195 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10196 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10197 DAG.getVTList(MVT::Other),
10198 Ops, 2, MVT::i16, MMO);
10200 // Load FP Control Word from stack slot
10201 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10202 MachinePointerInfo(), false, false, false, 0);
10204 // Transform as necessary
10206 DAG.getNode(ISD::SRL, DL, MVT::i16,
10207 DAG.getNode(ISD::AND, DL, MVT::i16,
10208 CWD, DAG.getConstant(0x800, MVT::i16)),
10209 DAG.getConstant(11, MVT::i8));
10211 DAG.getNode(ISD::SRL, DL, MVT::i16,
10212 DAG.getNode(ISD::AND, DL, MVT::i16,
10213 CWD, DAG.getConstant(0x400, MVT::i16)),
10214 DAG.getConstant(9, MVT::i8));
10217 DAG.getNode(ISD::AND, DL, MVT::i16,
10218 DAG.getNode(ISD::ADD, DL, MVT::i16,
10219 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10220 DAG.getConstant(1, MVT::i16)),
10221 DAG.getConstant(3, MVT::i16));
10224 return DAG.getNode((VT.getSizeInBits() < 16 ?
10225 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10228 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10229 EVT VT = Op.getValueType();
10231 unsigned NumBits = VT.getSizeInBits();
10232 DebugLoc dl = Op.getDebugLoc();
10234 Op = Op.getOperand(0);
10235 if (VT == MVT::i8) {
10236 // Zero extend to i32 since there is not an i8 bsr.
10238 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10241 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10242 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10243 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10245 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10248 DAG.getConstant(NumBits+NumBits-1, OpVT),
10249 DAG.getConstant(X86::COND_E, MVT::i8),
10252 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10254 // Finally xor with NumBits-1.
10255 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10258 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10262 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10263 SelectionDAG &DAG) const {
10264 EVT VT = Op.getValueType();
10266 unsigned NumBits = VT.getSizeInBits();
10267 DebugLoc dl = Op.getDebugLoc();
10269 Op = Op.getOperand(0);
10270 if (VT == MVT::i8) {
10271 // Zero extend to i32 since there is not an i8 bsr.
10273 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10276 // Issue a bsr (scan bits in reverse).
10277 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10278 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10280 // And xor with NumBits-1.
10281 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10284 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10288 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10289 EVT VT = Op.getValueType();
10290 unsigned NumBits = VT.getSizeInBits();
10291 DebugLoc dl = Op.getDebugLoc();
10292 Op = Op.getOperand(0);
10294 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10295 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10296 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10298 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10301 DAG.getConstant(NumBits, VT),
10302 DAG.getConstant(X86::COND_E, MVT::i8),
10305 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10308 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10309 // ones, and then concatenate the result back.
10310 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10311 EVT VT = Op.getValueType();
10313 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10314 "Unsupported value type for operation");
10316 unsigned NumElems = VT.getVectorNumElements();
10317 DebugLoc dl = Op.getDebugLoc();
10319 // Extract the LHS vectors
10320 SDValue LHS = Op.getOperand(0);
10321 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10322 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10324 // Extract the RHS vectors
10325 SDValue RHS = Op.getOperand(1);
10326 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10327 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10329 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10330 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10332 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10333 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10334 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10337 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10338 assert(Op.getValueType().getSizeInBits() == 256 &&
10339 Op.getValueType().isInteger() &&
10340 "Only handle AVX 256-bit vector integer operation");
10341 return Lower256IntArith(Op, DAG);
10344 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10345 assert(Op.getValueType().getSizeInBits() == 256 &&
10346 Op.getValueType().isInteger() &&
10347 "Only handle AVX 256-bit vector integer operation");
10348 return Lower256IntArith(Op, DAG);
10351 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10352 EVT VT = Op.getValueType();
10354 // Decompose 256-bit ops into smaller 128-bit ops.
10355 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10356 return Lower256IntArith(Op, DAG);
10358 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10359 "Only know how to lower V2I64/V4I64 multiply");
10361 DebugLoc dl = Op.getDebugLoc();
10363 // Ahi = psrlqi(a, 32);
10364 // Bhi = psrlqi(b, 32);
10366 // AloBlo = pmuludq(a, b);
10367 // AloBhi = pmuludq(a, Bhi);
10368 // AhiBlo = pmuludq(Ahi, b);
10370 // AloBhi = psllqi(AloBhi, 32);
10371 // AhiBlo = psllqi(AhiBlo, 32);
10372 // return AloBlo + AloBhi + AhiBlo;
10374 SDValue A = Op.getOperand(0);
10375 SDValue B = Op.getOperand(1);
10377 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10379 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10380 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10382 // Bit cast to 32-bit vectors for MULUDQ
10383 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10384 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10385 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10386 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10387 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10389 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10390 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10391 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10393 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10394 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10396 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10397 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10400 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10402 EVT VT = Op.getValueType();
10403 DebugLoc dl = Op.getDebugLoc();
10404 SDValue R = Op.getOperand(0);
10405 SDValue Amt = Op.getOperand(1);
10406 LLVMContext *Context = DAG.getContext();
10408 if (!Subtarget->hasSSE2())
10411 // Optimize shl/srl/sra with constant shift amount.
10412 if (isSplatVector(Amt.getNode())) {
10413 SDValue SclrAmt = Amt->getOperand(0);
10414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10415 uint64_t ShiftAmt = C->getZExtValue();
10417 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10418 (Subtarget->hasAVX2() &&
10419 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10420 if (Op.getOpcode() == ISD::SHL)
10421 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10422 DAG.getConstant(ShiftAmt, MVT::i32));
10423 if (Op.getOpcode() == ISD::SRL)
10424 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10425 DAG.getConstant(ShiftAmt, MVT::i32));
10426 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10427 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10428 DAG.getConstant(ShiftAmt, MVT::i32));
10431 if (VT == MVT::v16i8) {
10432 if (Op.getOpcode() == ISD::SHL) {
10433 // Make a large shift.
10434 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10435 DAG.getConstant(ShiftAmt, MVT::i32));
10436 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10437 // Zero out the rightmost bits.
10438 SmallVector<SDValue, 16> V(16,
10439 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10441 return DAG.getNode(ISD::AND, dl, VT, SHL,
10442 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10444 if (Op.getOpcode() == ISD::SRL) {
10445 // Make a large shift.
10446 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10447 DAG.getConstant(ShiftAmt, MVT::i32));
10448 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10449 // Zero out the leftmost bits.
10450 SmallVector<SDValue, 16> V(16,
10451 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10453 return DAG.getNode(ISD::AND, dl, VT, SRL,
10454 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10456 if (Op.getOpcode() == ISD::SRA) {
10457 if (ShiftAmt == 7) {
10458 // R s>> 7 === R s< 0
10459 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10460 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10463 // R s>> a === ((R u>> a) ^ m) - m
10464 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10465 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10467 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10468 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10469 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10472 llvm_unreachable("Unknown shift opcode.");
10475 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10476 if (Op.getOpcode() == ISD::SHL) {
10477 // Make a large shift.
10478 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10479 DAG.getConstant(ShiftAmt, MVT::i32));
10480 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10481 // Zero out the rightmost bits.
10482 SmallVector<SDValue, 32> V(32,
10483 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10485 return DAG.getNode(ISD::AND, dl, VT, SHL,
10486 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10488 if (Op.getOpcode() == ISD::SRL) {
10489 // Make a large shift.
10490 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10491 DAG.getConstant(ShiftAmt, MVT::i32));
10492 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10493 // Zero out the leftmost bits.
10494 SmallVector<SDValue, 32> V(32,
10495 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10497 return DAG.getNode(ISD::AND, dl, VT, SRL,
10498 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10500 if (Op.getOpcode() == ISD::SRA) {
10501 if (ShiftAmt == 7) {
10502 // R s>> 7 === R s< 0
10503 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10504 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10507 // R s>> a === ((R u>> a) ^ m) - m
10508 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10509 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10511 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10512 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10513 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10516 llvm_unreachable("Unknown shift opcode.");
10521 // Lower SHL with variable shift amount.
10522 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10523 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10524 DAG.getConstant(23, MVT::i32));
10526 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10527 Constant *C = ConstantDataVector::get(*Context, CV);
10528 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10529 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10530 MachinePointerInfo::getConstantPool(),
10531 false, false, false, 16);
10533 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10534 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10535 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10536 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10538 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10539 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10542 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10543 DAG.getConstant(5, MVT::i32));
10544 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10546 // Turn 'a' into a mask suitable for VSELECT
10547 SDValue VSelM = DAG.getConstant(0x80, VT);
10548 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10549 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10551 SDValue CM1 = DAG.getConstant(0x0f, VT);
10552 SDValue CM2 = DAG.getConstant(0x3f, VT);
10554 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10555 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10556 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10557 DAG.getConstant(4, MVT::i32), DAG);
10558 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10559 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10562 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10563 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10564 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10566 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10567 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10568 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10569 DAG.getConstant(2, MVT::i32), DAG);
10570 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10571 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10574 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10575 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10576 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10578 // return VSELECT(r, r+r, a);
10579 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10580 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10584 // Decompose 256-bit shifts into smaller 128-bit shifts.
10585 if (VT.getSizeInBits() == 256) {
10586 unsigned NumElems = VT.getVectorNumElements();
10587 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10588 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10590 // Extract the two vectors
10591 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10592 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10594 // Recreate the shift amount vectors
10595 SDValue Amt1, Amt2;
10596 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10597 // Constant shift amount
10598 SmallVector<SDValue, 4> Amt1Csts;
10599 SmallVector<SDValue, 4> Amt2Csts;
10600 for (unsigned i = 0; i != NumElems/2; ++i)
10601 Amt1Csts.push_back(Amt->getOperand(i));
10602 for (unsigned i = NumElems/2; i != NumElems; ++i)
10603 Amt2Csts.push_back(Amt->getOperand(i));
10605 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10606 &Amt1Csts[0], NumElems/2);
10607 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10608 &Amt2Csts[0], NumElems/2);
10610 // Variable shift amount
10611 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10612 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10615 // Issue new vector shifts for the smaller types
10616 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10617 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10619 // Concatenate the result back
10620 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10626 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10627 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10628 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10629 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10630 // has only one use.
10631 SDNode *N = Op.getNode();
10632 SDValue LHS = N->getOperand(0);
10633 SDValue RHS = N->getOperand(1);
10634 unsigned BaseOp = 0;
10636 DebugLoc DL = Op.getDebugLoc();
10637 switch (Op.getOpcode()) {
10638 default: llvm_unreachable("Unknown ovf instruction!");
10640 // A subtract of one will be selected as a INC. Note that INC doesn't
10641 // set CF, so we can't do this for UADDO.
10642 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10644 BaseOp = X86ISD::INC;
10645 Cond = X86::COND_O;
10648 BaseOp = X86ISD::ADD;
10649 Cond = X86::COND_O;
10652 BaseOp = X86ISD::ADD;
10653 Cond = X86::COND_B;
10656 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10657 // set CF, so we can't do this for USUBO.
10658 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10660 BaseOp = X86ISD::DEC;
10661 Cond = X86::COND_O;
10664 BaseOp = X86ISD::SUB;
10665 Cond = X86::COND_O;
10668 BaseOp = X86ISD::SUB;
10669 Cond = X86::COND_B;
10672 BaseOp = X86ISD::SMUL;
10673 Cond = X86::COND_O;
10675 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10676 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10678 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10681 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10682 DAG.getConstant(X86::COND_O, MVT::i32),
10683 SDValue(Sum.getNode(), 2));
10685 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10689 // Also sets EFLAGS.
10690 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10691 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10694 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10695 DAG.getConstant(Cond, MVT::i32),
10696 SDValue(Sum.getNode(), 1));
10698 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10701 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10702 SelectionDAG &DAG) const {
10703 DebugLoc dl = Op.getDebugLoc();
10704 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10705 EVT VT = Op.getValueType();
10707 if (!Subtarget->hasSSE2() || !VT.isVector())
10710 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10711 ExtraVT.getScalarType().getSizeInBits();
10712 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10714 switch (VT.getSimpleVT().SimpleTy) {
10715 default: return SDValue();
10718 if (!Subtarget->hasAVX())
10720 if (!Subtarget->hasAVX2()) {
10721 // needs to be split
10722 unsigned NumElems = VT.getVectorNumElements();
10724 // Extract the LHS vectors
10725 SDValue LHS = Op.getOperand(0);
10726 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10727 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10729 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10730 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10732 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10733 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10734 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10736 SDValue Extra = DAG.getValueType(ExtraVT);
10738 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10739 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10741 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10746 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10747 Op.getOperand(0), ShAmt, DAG);
10748 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10754 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10755 DebugLoc dl = Op.getDebugLoc();
10757 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10758 // There isn't any reason to disable it if the target processor supports it.
10759 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10760 SDValue Chain = Op.getOperand(0);
10761 SDValue Zero = DAG.getConstant(0, MVT::i32);
10763 DAG.getRegister(X86::ESP, MVT::i32), // Base
10764 DAG.getTargetConstant(1, MVT::i8), // Scale
10765 DAG.getRegister(0, MVT::i32), // Index
10766 DAG.getTargetConstant(0, MVT::i32), // Disp
10767 DAG.getRegister(0, MVT::i32), // Segment.
10772 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10773 array_lengthof(Ops));
10774 return SDValue(Res, 0);
10777 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10779 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10781 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10782 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10783 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10784 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10786 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10787 if (!Op1 && !Op2 && !Op3 && Op4)
10788 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10790 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10791 if (Op1 && !Op2 && !Op3 && !Op4)
10792 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10794 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10796 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10799 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10800 SelectionDAG &DAG) const {
10801 DebugLoc dl = Op.getDebugLoc();
10802 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10803 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10804 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10805 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10807 // The only fence that needs an instruction is a sequentially-consistent
10808 // cross-thread fence.
10809 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10810 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10811 // no-sse2). There isn't any reason to disable it if the target processor
10813 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10814 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10816 SDValue Chain = Op.getOperand(0);
10817 SDValue Zero = DAG.getConstant(0, MVT::i32);
10819 DAG.getRegister(X86::ESP, MVT::i32), // Base
10820 DAG.getTargetConstant(1, MVT::i8), // Scale
10821 DAG.getRegister(0, MVT::i32), // Index
10822 DAG.getTargetConstant(0, MVT::i32), // Disp
10823 DAG.getRegister(0, MVT::i32), // Segment.
10828 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10829 array_lengthof(Ops));
10830 return SDValue(Res, 0);
10833 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10834 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10838 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10839 EVT T = Op.getValueType();
10840 DebugLoc DL = Op.getDebugLoc();
10843 switch(T.getSimpleVT().SimpleTy) {
10844 default: llvm_unreachable("Invalid value type!");
10845 case MVT::i8: Reg = X86::AL; size = 1; break;
10846 case MVT::i16: Reg = X86::AX; size = 2; break;
10847 case MVT::i32: Reg = X86::EAX; size = 4; break;
10849 assert(Subtarget->is64Bit() && "Node not type legal!");
10850 Reg = X86::RAX; size = 8;
10853 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10854 Op.getOperand(2), SDValue());
10855 SDValue Ops[] = { cpIn.getValue(0),
10858 DAG.getTargetConstant(size, MVT::i8),
10859 cpIn.getValue(1) };
10860 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10861 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10862 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10865 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10869 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10870 SelectionDAG &DAG) const {
10871 assert(Subtarget->is64Bit() && "Result not type legalized?");
10872 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10873 SDValue TheChain = Op.getOperand(0);
10874 DebugLoc dl = Op.getDebugLoc();
10875 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10876 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10877 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10879 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10880 DAG.getConstant(32, MVT::i8));
10882 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10885 return DAG.getMergeValues(Ops, 2, dl);
10888 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10889 SelectionDAG &DAG) const {
10890 EVT SrcVT = Op.getOperand(0).getValueType();
10891 EVT DstVT = Op.getValueType();
10892 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10893 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10894 assert((DstVT == MVT::i64 ||
10895 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10896 "Unexpected custom BITCAST");
10897 // i64 <=> MMX conversions are Legal.
10898 if (SrcVT==MVT::i64 && DstVT.isVector())
10900 if (DstVT==MVT::i64 && SrcVT.isVector())
10902 // MMX <=> MMX conversions are Legal.
10903 if (SrcVT.isVector() && DstVT.isVector())
10905 // All other conversions need to be expanded.
10909 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10910 SDNode *Node = Op.getNode();
10911 DebugLoc dl = Node->getDebugLoc();
10912 EVT T = Node->getValueType(0);
10913 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10914 DAG.getConstant(0, T), Node->getOperand(2));
10915 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10916 cast<AtomicSDNode>(Node)->getMemoryVT(),
10917 Node->getOperand(0),
10918 Node->getOperand(1), negOp,
10919 cast<AtomicSDNode>(Node)->getSrcValue(),
10920 cast<AtomicSDNode>(Node)->getAlignment(),
10921 cast<AtomicSDNode>(Node)->getOrdering(),
10922 cast<AtomicSDNode>(Node)->getSynchScope());
10925 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10926 SDNode *Node = Op.getNode();
10927 DebugLoc dl = Node->getDebugLoc();
10928 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10930 // Convert seq_cst store -> xchg
10931 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10932 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10933 // (The only way to get a 16-byte store is cmpxchg16b)
10934 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10935 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10936 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10937 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10938 cast<AtomicSDNode>(Node)->getMemoryVT(),
10939 Node->getOperand(0),
10940 Node->getOperand(1), Node->getOperand(2),
10941 cast<AtomicSDNode>(Node)->getMemOperand(),
10942 cast<AtomicSDNode>(Node)->getOrdering(),
10943 cast<AtomicSDNode>(Node)->getSynchScope());
10944 return Swap.getValue(1);
10946 // Other atomic stores have a simple pattern.
10950 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10951 EVT VT = Op.getNode()->getValueType(0);
10953 // Let legalize expand this if it isn't a legal type yet.
10954 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10957 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10960 bool ExtraOp = false;
10961 switch (Op.getOpcode()) {
10962 default: llvm_unreachable("Invalid code");
10963 case ISD::ADDC: Opc = X86ISD::ADD; break;
10964 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10965 case ISD::SUBC: Opc = X86ISD::SUB; break;
10966 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10970 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10972 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10973 Op.getOperand(1), Op.getOperand(2));
10976 /// LowerOperation - Provide custom lowering hooks for some operations.
10978 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10979 switch (Op.getOpcode()) {
10980 default: llvm_unreachable("Should not custom lower this!");
10981 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10982 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10983 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10984 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10985 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10986 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10987 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10988 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10989 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10990 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10991 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10992 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10993 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10994 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10995 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10996 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10997 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10998 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10999 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11000 case ISD::SHL_PARTS:
11001 case ISD::SRA_PARTS:
11002 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11003 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11004 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11005 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11006 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11007 case ISD::FABS: return LowerFABS(Op, DAG);
11008 case ISD::FNEG: return LowerFNEG(Op, DAG);
11009 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11010 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11011 case ISD::SETCC: return LowerSETCC(Op, DAG);
11012 case ISD::SELECT: return LowerSELECT(Op, DAG);
11013 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11014 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11015 case ISD::VASTART: return LowerVASTART(Op, DAG);
11016 case ISD::VAARG: return LowerVAARG(Op, DAG);
11017 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
11018 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11019 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11020 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11021 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11022 case ISD::FRAME_TO_ARGS_OFFSET:
11023 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11024 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11025 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11026 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11027 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11028 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11029 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11030 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11031 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11032 case ISD::MUL: return LowerMUL(Op, DAG);
11035 case ISD::SHL: return LowerShift(Op, DAG);
11041 case ISD::UMULO: return LowerXALUO(Op, DAG);
11042 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
11043 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11047 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11048 case ISD::ADD: return LowerADD(Op, DAG);
11049 case ISD::SUB: return LowerSUB(Op, DAG);
11053 static void ReplaceATOMIC_LOAD(SDNode *Node,
11054 SmallVectorImpl<SDValue> &Results,
11055 SelectionDAG &DAG) {
11056 DebugLoc dl = Node->getDebugLoc();
11057 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11059 // Convert wide load -> cmpxchg8b/cmpxchg16b
11060 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11061 // (The only way to get a 16-byte load is cmpxchg16b)
11062 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11063 SDValue Zero = DAG.getConstant(0, VT);
11064 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11065 Node->getOperand(0),
11066 Node->getOperand(1), Zero, Zero,
11067 cast<AtomicSDNode>(Node)->getMemOperand(),
11068 cast<AtomicSDNode>(Node)->getOrdering(),
11069 cast<AtomicSDNode>(Node)->getSynchScope());
11070 Results.push_back(Swap.getValue(0));
11071 Results.push_back(Swap.getValue(1));
11074 void X86TargetLowering::
11075 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11076 SelectionDAG &DAG, unsigned NewOp) const {
11077 DebugLoc dl = Node->getDebugLoc();
11078 assert (Node->getValueType(0) == MVT::i64 &&
11079 "Only know how to expand i64 atomics");
11081 SDValue Chain = Node->getOperand(0);
11082 SDValue In1 = Node->getOperand(1);
11083 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11084 Node->getOperand(2), DAG.getIntPtrConstant(0));
11085 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11086 Node->getOperand(2), DAG.getIntPtrConstant(1));
11087 SDValue Ops[] = { Chain, In1, In2L, In2H };
11088 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11090 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11091 cast<MemSDNode>(Node)->getMemOperand());
11092 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11093 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11094 Results.push_back(Result.getValue(2));
11097 /// ReplaceNodeResults - Replace a node with an illegal result type
11098 /// with a new node built out of custom code.
11099 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11100 SmallVectorImpl<SDValue>&Results,
11101 SelectionDAG &DAG) const {
11102 DebugLoc dl = N->getDebugLoc();
11103 switch (N->getOpcode()) {
11105 llvm_unreachable("Do not know how to custom type legalize this operation!");
11106 case ISD::SIGN_EXTEND_INREG:
11111 // We don't want to expand or promote these.
11113 case ISD::FP_TO_SINT:
11114 case ISD::FP_TO_UINT: {
11115 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11117 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11120 std::pair<SDValue,SDValue> Vals =
11121 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11122 SDValue FIST = Vals.first, StackSlot = Vals.second;
11123 if (FIST.getNode() != 0) {
11124 EVT VT = N->getValueType(0);
11125 // Return a load from the stack slot.
11126 if (StackSlot.getNode() != 0)
11127 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11128 MachinePointerInfo(),
11129 false, false, false, 0));
11131 Results.push_back(FIST);
11135 case ISD::READCYCLECOUNTER: {
11136 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11137 SDValue TheChain = N->getOperand(0);
11138 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11139 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11141 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11143 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11144 SDValue Ops[] = { eax, edx };
11145 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11146 Results.push_back(edx.getValue(1));
11149 case ISD::ATOMIC_CMP_SWAP: {
11150 EVT T = N->getValueType(0);
11151 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11152 bool Regs64bit = T == MVT::i128;
11153 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11154 SDValue cpInL, cpInH;
11155 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11156 DAG.getConstant(0, HalfT));
11157 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11158 DAG.getConstant(1, HalfT));
11159 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11160 Regs64bit ? X86::RAX : X86::EAX,
11162 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11163 Regs64bit ? X86::RDX : X86::EDX,
11164 cpInH, cpInL.getValue(1));
11165 SDValue swapInL, swapInH;
11166 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11167 DAG.getConstant(0, HalfT));
11168 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11169 DAG.getConstant(1, HalfT));
11170 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11171 Regs64bit ? X86::RBX : X86::EBX,
11172 swapInL, cpInH.getValue(1));
11173 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11174 Regs64bit ? X86::RCX : X86::ECX,
11175 swapInH, swapInL.getValue(1));
11176 SDValue Ops[] = { swapInH.getValue(0),
11178 swapInH.getValue(1) };
11179 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11180 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11181 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11182 X86ISD::LCMPXCHG8_DAG;
11183 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11185 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11186 Regs64bit ? X86::RAX : X86::EAX,
11187 HalfT, Result.getValue(1));
11188 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11189 Regs64bit ? X86::RDX : X86::EDX,
11190 HalfT, cpOutL.getValue(2));
11191 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11192 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11193 Results.push_back(cpOutH.getValue(1));
11196 case ISD::ATOMIC_LOAD_ADD:
11197 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11199 case ISD::ATOMIC_LOAD_AND:
11200 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11202 case ISD::ATOMIC_LOAD_NAND:
11203 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11205 case ISD::ATOMIC_LOAD_OR:
11206 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11208 case ISD::ATOMIC_LOAD_SUB:
11209 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11211 case ISD::ATOMIC_LOAD_XOR:
11212 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11214 case ISD::ATOMIC_SWAP:
11215 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11217 case ISD::ATOMIC_LOAD:
11218 ReplaceATOMIC_LOAD(N, Results, DAG);
11222 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11224 default: return NULL;
11225 case X86ISD::BSF: return "X86ISD::BSF";
11226 case X86ISD::BSR: return "X86ISD::BSR";
11227 case X86ISD::SHLD: return "X86ISD::SHLD";
11228 case X86ISD::SHRD: return "X86ISD::SHRD";
11229 case X86ISD::FAND: return "X86ISD::FAND";
11230 case X86ISD::FOR: return "X86ISD::FOR";
11231 case X86ISD::FXOR: return "X86ISD::FXOR";
11232 case X86ISD::FSRL: return "X86ISD::FSRL";
11233 case X86ISD::FILD: return "X86ISD::FILD";
11234 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11235 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11236 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11237 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11238 case X86ISD::FLD: return "X86ISD::FLD";
11239 case X86ISD::FST: return "X86ISD::FST";
11240 case X86ISD::CALL: return "X86ISD::CALL";
11241 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11242 case X86ISD::BT: return "X86ISD::BT";
11243 case X86ISD::CMP: return "X86ISD::CMP";
11244 case X86ISD::COMI: return "X86ISD::COMI";
11245 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11246 case X86ISD::SETCC: return "X86ISD::SETCC";
11247 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11248 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11249 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11250 case X86ISD::CMOV: return "X86ISD::CMOV";
11251 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11252 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11253 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11254 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11255 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11256 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11257 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11258 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11259 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11260 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11261 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11262 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11263 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11264 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11265 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11266 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11267 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11268 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11269 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11270 case X86ISD::HADD: return "X86ISD::HADD";
11271 case X86ISD::HSUB: return "X86ISD::HSUB";
11272 case X86ISD::FHADD: return "X86ISD::FHADD";
11273 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11274 case X86ISD::FMAX: return "X86ISD::FMAX";
11275 case X86ISD::FMIN: return "X86ISD::FMIN";
11276 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11277 case X86ISD::FRCP: return "X86ISD::FRCP";
11278 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11279 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11280 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11281 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11282 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11283 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11284 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11285 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11286 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11287 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11288 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11289 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11290 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11291 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11292 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11293 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11294 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11295 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11296 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11297 case X86ISD::VSHL: return "X86ISD::VSHL";
11298 case X86ISD::VSRL: return "X86ISD::VSRL";
11299 case X86ISD::VSRA: return "X86ISD::VSRA";
11300 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11301 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11302 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11303 case X86ISD::CMPP: return "X86ISD::CMPP";
11304 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11305 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11306 case X86ISD::ADD: return "X86ISD::ADD";
11307 case X86ISD::SUB: return "X86ISD::SUB";
11308 case X86ISD::ADC: return "X86ISD::ADC";
11309 case X86ISD::SBB: return "X86ISD::SBB";
11310 case X86ISD::SMUL: return "X86ISD::SMUL";
11311 case X86ISD::UMUL: return "X86ISD::UMUL";
11312 case X86ISD::INC: return "X86ISD::INC";
11313 case X86ISD::DEC: return "X86ISD::DEC";
11314 case X86ISD::OR: return "X86ISD::OR";
11315 case X86ISD::XOR: return "X86ISD::XOR";
11316 case X86ISD::AND: return "X86ISD::AND";
11317 case X86ISD::ANDN: return "X86ISD::ANDN";
11318 case X86ISD::BLSI: return "X86ISD::BLSI";
11319 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11320 case X86ISD::BLSR: return "X86ISD::BLSR";
11321 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11322 case X86ISD::PTEST: return "X86ISD::PTEST";
11323 case X86ISD::TESTP: return "X86ISD::TESTP";
11324 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11325 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11326 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11327 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11328 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11329 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11330 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11331 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11332 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11333 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11334 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11335 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11336 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11337 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11338 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11339 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11340 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11341 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11342 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11343 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11344 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11345 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11346 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11347 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11348 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11349 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11350 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11351 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11352 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11353 case X86ISD::SAHF: return "X86ISD::SAHF";
11354 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11355 case X86ISD::FMADD: return "X86ISD::FMADD";
11356 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11357 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11358 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11359 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11360 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11364 // isLegalAddressingMode - Return true if the addressing mode represented
11365 // by AM is legal for this target, for a load/store of the specified type.
11366 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11368 // X86 supports extremely general addressing modes.
11369 CodeModel::Model M = getTargetMachine().getCodeModel();
11370 Reloc::Model R = getTargetMachine().getRelocationModel();
11372 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11373 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11378 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11380 // If a reference to this global requires an extra load, we can't fold it.
11381 if (isGlobalStubReference(GVFlags))
11384 // If BaseGV requires a register for the PIC base, we cannot also have a
11385 // BaseReg specified.
11386 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11389 // If lower 4G is not available, then we must use rip-relative addressing.
11390 if ((M != CodeModel::Small || R != Reloc::Static) &&
11391 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11395 switch (AM.Scale) {
11401 // These scales always work.
11406 // These scales are formed with basereg+scalereg. Only accept if there is
11411 default: // Other stuff never works.
11419 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11420 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11422 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11423 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11424 if (NumBits1 <= NumBits2)
11429 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11430 return Imm == (int32_t)Imm;
11433 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11434 // Can also use sub to handle negated immediates.
11435 return Imm == (int32_t)Imm;
11438 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11439 if (!VT1.isInteger() || !VT2.isInteger())
11441 unsigned NumBits1 = VT1.getSizeInBits();
11442 unsigned NumBits2 = VT2.getSizeInBits();
11443 if (NumBits1 <= NumBits2)
11448 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11449 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11450 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11453 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11454 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11455 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11458 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11459 // i16 instructions are longer (0x66 prefix) and potentially slower.
11460 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11463 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11464 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11465 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11466 /// are assumed to be legal.
11468 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11470 // Very little shuffling can be done for 64-bit vectors right now.
11471 if (VT.getSizeInBits() == 64)
11474 // FIXME: pshufb, blends, shifts.
11475 return (VT.getVectorNumElements() == 2 ||
11476 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11477 isMOVLMask(M, VT) ||
11478 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11479 isPSHUFDMask(M, VT) ||
11480 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11481 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11482 isPALIGNRMask(M, VT, Subtarget) ||
11483 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11484 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11485 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11486 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11490 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11492 unsigned NumElts = VT.getVectorNumElements();
11493 // FIXME: This collection of masks seems suspect.
11496 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11497 return (isMOVLMask(Mask, VT) ||
11498 isCommutedMOVLMask(Mask, VT, true) ||
11499 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11500 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11505 //===----------------------------------------------------------------------===//
11506 // X86 Scheduler Hooks
11507 //===----------------------------------------------------------------------===//
11509 // private utility function
11510 MachineBasicBlock *
11511 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11512 MachineBasicBlock *MBB,
11519 const TargetRegisterClass *RC,
11520 bool Invert) const {
11521 // For the atomic bitwise operator, we generate
11524 // ld t1 = [bitinstr.addr]
11525 // op t2 = t1, [bitinstr.val]
11526 // not t3 = t2 (if Invert)
11528 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11530 // fallthrough -->nextMBB
11531 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11532 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11533 MachineFunction::iterator MBBIter = MBB;
11536 /// First build the CFG
11537 MachineFunction *F = MBB->getParent();
11538 MachineBasicBlock *thisMBB = MBB;
11539 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11540 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11541 F->insert(MBBIter, newMBB);
11542 F->insert(MBBIter, nextMBB);
11544 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11545 nextMBB->splice(nextMBB->begin(), thisMBB,
11546 llvm::next(MachineBasicBlock::iterator(bInstr)),
11548 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11550 // Update thisMBB to fall through to newMBB
11551 thisMBB->addSuccessor(newMBB);
11553 // newMBB jumps to itself and fall through to nextMBB
11554 newMBB->addSuccessor(nextMBB);
11555 newMBB->addSuccessor(newMBB);
11557 // Insert instructions into newMBB based on incoming instruction
11558 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11559 "unexpected number of operands");
11560 DebugLoc dl = bInstr->getDebugLoc();
11561 MachineOperand& destOper = bInstr->getOperand(0);
11562 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11563 int numArgs = bInstr->getNumOperands() - 1;
11564 for (int i=0; i < numArgs; ++i)
11565 argOpers[i] = &bInstr->getOperand(i+1);
11567 // x86 address has 4 operands: base, index, scale, and displacement
11568 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11569 int valArgIndx = lastAddrIndx + 1;
11571 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11572 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11573 for (int i=0; i <= lastAddrIndx; ++i)
11574 (*MIB).addOperand(*argOpers[i]);
11576 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11577 assert((argOpers[valArgIndx]->isReg() ||
11578 argOpers[valArgIndx]->isImm()) &&
11579 "invalid operand");
11580 if (argOpers[valArgIndx]->isReg())
11581 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11583 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11585 (*MIB).addOperand(*argOpers[valArgIndx]);
11587 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11589 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11594 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11597 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11598 for (int i=0; i <= lastAddrIndx; ++i)
11599 (*MIB).addOperand(*argOpers[i]);
11601 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11602 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11603 bInstr->memoperands_end());
11605 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11606 MIB.addReg(EAXreg);
11609 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11611 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11615 // private utility function: 64 bit atomics on 32 bit host.
11616 MachineBasicBlock *
11617 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11618 MachineBasicBlock *MBB,
11623 bool Invert) const {
11624 // For the atomic bitwise operator, we generate
11625 // thisMBB (instructions are in pairs, except cmpxchg8b)
11626 // ld t1,t2 = [bitinstr.addr]
11628 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11629 // op t5, t6 <- out1, out2, [bitinstr.val]
11630 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11631 // neg t7, t8 < t5, t6 (if Invert)
11632 // mov ECX, EBX <- t5, t6
11633 // mov EAX, EDX <- t1, t2
11634 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11635 // mov t3, t4 <- EAX, EDX
11637 // result in out1, out2
11638 // fallthrough -->nextMBB
11640 const TargetRegisterClass *RC = &X86::GR32RegClass;
11641 const unsigned LoadOpc = X86::MOV32rm;
11642 const unsigned NotOpc = X86::NOT32r;
11643 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11644 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11645 MachineFunction::iterator MBBIter = MBB;
11648 /// First build the CFG
11649 MachineFunction *F = MBB->getParent();
11650 MachineBasicBlock *thisMBB = MBB;
11651 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11652 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11653 F->insert(MBBIter, newMBB);
11654 F->insert(MBBIter, nextMBB);
11656 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11657 nextMBB->splice(nextMBB->begin(), thisMBB,
11658 llvm::next(MachineBasicBlock::iterator(bInstr)),
11660 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11662 // Update thisMBB to fall through to newMBB
11663 thisMBB->addSuccessor(newMBB);
11665 // newMBB jumps to itself and fall through to nextMBB
11666 newMBB->addSuccessor(nextMBB);
11667 newMBB->addSuccessor(newMBB);
11669 DebugLoc dl = bInstr->getDebugLoc();
11670 // Insert instructions into newMBB based on incoming instruction
11671 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11672 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11673 "unexpected number of operands");
11674 MachineOperand& dest1Oper = bInstr->getOperand(0);
11675 MachineOperand& dest2Oper = bInstr->getOperand(1);
11676 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11677 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11678 argOpers[i] = &bInstr->getOperand(i+2);
11680 // We use some of the operands multiple times, so conservatively just
11681 // clear any kill flags that might be present.
11682 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11683 argOpers[i]->setIsKill(false);
11686 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11687 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11689 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11690 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11691 for (int i=0; i <= lastAddrIndx; ++i)
11692 (*MIB).addOperand(*argOpers[i]);
11693 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11694 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11695 // add 4 to displacement.
11696 for (int i=0; i <= lastAddrIndx-2; ++i)
11697 (*MIB).addOperand(*argOpers[i]);
11698 MachineOperand newOp3 = *(argOpers[3]);
11699 if (newOp3.isImm())
11700 newOp3.setImm(newOp3.getImm()+4);
11702 newOp3.setOffset(newOp3.getOffset()+4);
11703 (*MIB).addOperand(newOp3);
11704 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11706 // t3/4 are defined later, at the bottom of the loop
11707 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11708 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11709 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11710 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11711 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11712 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11714 // The subsequent operations should be using the destination registers of
11715 // the PHI instructions.
11716 t1 = dest1Oper.getReg();
11717 t2 = dest2Oper.getReg();
11719 int valArgIndx = lastAddrIndx + 1;
11720 assert((argOpers[valArgIndx]->isReg() ||
11721 argOpers[valArgIndx]->isImm()) &&
11722 "invalid operand");
11723 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11724 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11725 if (argOpers[valArgIndx]->isReg())
11726 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11728 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11729 if (regOpcL != X86::MOV32rr)
11731 (*MIB).addOperand(*argOpers[valArgIndx]);
11732 assert(argOpers[valArgIndx + 1]->isReg() ==
11733 argOpers[valArgIndx]->isReg());
11734 assert(argOpers[valArgIndx + 1]->isImm() ==
11735 argOpers[valArgIndx]->isImm());
11736 if (argOpers[valArgIndx + 1]->isReg())
11737 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11739 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11740 if (regOpcH != X86::MOV32rr)
11742 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11746 t7 = F->getRegInfo().createVirtualRegister(RC);
11747 t8 = F->getRegInfo().createVirtualRegister(RC);
11748 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11749 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11755 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11757 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11760 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11762 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11765 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11766 for (int i=0; i <= lastAddrIndx; ++i)
11767 (*MIB).addOperand(*argOpers[i]);
11769 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11770 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11771 bInstr->memoperands_end());
11773 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11774 MIB.addReg(X86::EAX);
11775 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11776 MIB.addReg(X86::EDX);
11779 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11781 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11785 // private utility function
11786 MachineBasicBlock *
11787 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11788 MachineBasicBlock *MBB,
11789 unsigned cmovOpc) const {
11790 // For the atomic min/max operator, we generate
11793 // ld t1 = [min/max.addr]
11794 // mov t2 = [min/max.val]
11796 // cmov[cond] t2 = t1
11798 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11800 // fallthrough -->nextMBB
11802 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11803 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11804 MachineFunction::iterator MBBIter = MBB;
11807 /// First build the CFG
11808 MachineFunction *F = MBB->getParent();
11809 MachineBasicBlock *thisMBB = MBB;
11810 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11811 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11812 F->insert(MBBIter, newMBB);
11813 F->insert(MBBIter, nextMBB);
11815 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11816 nextMBB->splice(nextMBB->begin(), thisMBB,
11817 llvm::next(MachineBasicBlock::iterator(mInstr)),
11819 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11821 // Update thisMBB to fall through to newMBB
11822 thisMBB->addSuccessor(newMBB);
11824 // newMBB jumps to newMBB and fall through to nextMBB
11825 newMBB->addSuccessor(nextMBB);
11826 newMBB->addSuccessor(newMBB);
11828 DebugLoc dl = mInstr->getDebugLoc();
11829 // Insert instructions into newMBB based on incoming instruction
11830 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11831 "unexpected number of operands");
11832 MachineOperand& destOper = mInstr->getOperand(0);
11833 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11834 int numArgs = mInstr->getNumOperands() - 1;
11835 for (int i=0; i < numArgs; ++i)
11836 argOpers[i] = &mInstr->getOperand(i+1);
11838 // x86 address has 4 operands: base, index, scale, and displacement
11839 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11840 int valArgIndx = lastAddrIndx + 1;
11842 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11843 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11844 for (int i=0; i <= lastAddrIndx; ++i)
11845 (*MIB).addOperand(*argOpers[i]);
11847 // We only support register and immediate values
11848 assert((argOpers[valArgIndx]->isReg() ||
11849 argOpers[valArgIndx]->isImm()) &&
11850 "invalid operand");
11852 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11853 if (argOpers[valArgIndx]->isReg())
11854 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11856 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11857 (*MIB).addOperand(*argOpers[valArgIndx]);
11859 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11862 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11867 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11868 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11872 // Cmp and exchange if none has modified the memory location
11873 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11874 for (int i=0; i <= lastAddrIndx; ++i)
11875 (*MIB).addOperand(*argOpers[i]);
11877 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11878 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11879 mInstr->memoperands_end());
11881 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11882 MIB.addReg(X86::EAX);
11885 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11887 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11891 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11892 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11893 // in the .td file.
11894 MachineBasicBlock *
11895 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11896 unsigned numArgs, bool memArg) const {
11897 assert(Subtarget->hasSSE42() &&
11898 "Target must have SSE4.2 or AVX features enabled");
11900 DebugLoc dl = MI->getDebugLoc();
11901 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11903 if (!Subtarget->hasAVX()) {
11905 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11907 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11910 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11912 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11915 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11916 for (unsigned i = 0; i < numArgs; ++i) {
11917 MachineOperand &Op = MI->getOperand(i+1);
11918 if (!(Op.isReg() && Op.isImplicit()))
11919 MIB.addOperand(Op);
11921 BuildMI(*BB, MI, dl,
11922 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
11923 .addReg(X86::XMM0);
11925 MI->eraseFromParent();
11929 MachineBasicBlock *
11930 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11931 DebugLoc dl = MI->getDebugLoc();
11932 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11934 // Address into RAX/EAX, other two args into ECX, EDX.
11935 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11936 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11937 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11938 for (int i = 0; i < X86::AddrNumOperands; ++i)
11939 MIB.addOperand(MI->getOperand(i));
11941 unsigned ValOps = X86::AddrNumOperands;
11942 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11943 .addReg(MI->getOperand(ValOps).getReg());
11944 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11945 .addReg(MI->getOperand(ValOps+1).getReg());
11947 // The instruction doesn't actually take any operands though.
11948 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11950 MI->eraseFromParent(); // The pseudo is gone now.
11954 MachineBasicBlock *
11955 X86TargetLowering::EmitVAARG64WithCustomInserter(
11957 MachineBasicBlock *MBB) const {
11958 // Emit va_arg instruction on X86-64.
11960 // Operands to this pseudo-instruction:
11961 // 0 ) Output : destination address (reg)
11962 // 1-5) Input : va_list address (addr, i64mem)
11963 // 6 ) ArgSize : Size (in bytes) of vararg type
11964 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11965 // 8 ) Align : Alignment of type
11966 // 9 ) EFLAGS (implicit-def)
11968 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11969 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11971 unsigned DestReg = MI->getOperand(0).getReg();
11972 MachineOperand &Base = MI->getOperand(1);
11973 MachineOperand &Scale = MI->getOperand(2);
11974 MachineOperand &Index = MI->getOperand(3);
11975 MachineOperand &Disp = MI->getOperand(4);
11976 MachineOperand &Segment = MI->getOperand(5);
11977 unsigned ArgSize = MI->getOperand(6).getImm();
11978 unsigned ArgMode = MI->getOperand(7).getImm();
11979 unsigned Align = MI->getOperand(8).getImm();
11981 // Memory Reference
11982 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11983 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11984 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11986 // Machine Information
11987 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11988 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11989 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11990 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11991 DebugLoc DL = MI->getDebugLoc();
11993 // struct va_list {
11996 // i64 overflow_area (address)
11997 // i64 reg_save_area (address)
11999 // sizeof(va_list) = 24
12000 // alignment(va_list) = 8
12002 unsigned TotalNumIntRegs = 6;
12003 unsigned TotalNumXMMRegs = 8;
12004 bool UseGPOffset = (ArgMode == 1);
12005 bool UseFPOffset = (ArgMode == 2);
12006 unsigned MaxOffset = TotalNumIntRegs * 8 +
12007 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12009 /* Align ArgSize to a multiple of 8 */
12010 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12011 bool NeedsAlign = (Align > 8);
12013 MachineBasicBlock *thisMBB = MBB;
12014 MachineBasicBlock *overflowMBB;
12015 MachineBasicBlock *offsetMBB;
12016 MachineBasicBlock *endMBB;
12018 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12019 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12020 unsigned OffsetReg = 0;
12022 if (!UseGPOffset && !UseFPOffset) {
12023 // If we only pull from the overflow region, we don't create a branch.
12024 // We don't need to alter control flow.
12025 OffsetDestReg = 0; // unused
12026 OverflowDestReg = DestReg;
12029 overflowMBB = thisMBB;
12032 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12033 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12034 // If not, pull from overflow_area. (branch to overflowMBB)
12039 // offsetMBB overflowMBB
12044 // Registers for the PHI in endMBB
12045 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12046 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12048 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12049 MachineFunction *MF = MBB->getParent();
12050 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12051 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12052 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12054 MachineFunction::iterator MBBIter = MBB;
12057 // Insert the new basic blocks
12058 MF->insert(MBBIter, offsetMBB);
12059 MF->insert(MBBIter, overflowMBB);
12060 MF->insert(MBBIter, endMBB);
12062 // Transfer the remainder of MBB and its successor edges to endMBB.
12063 endMBB->splice(endMBB->begin(), thisMBB,
12064 llvm::next(MachineBasicBlock::iterator(MI)),
12066 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12068 // Make offsetMBB and overflowMBB successors of thisMBB
12069 thisMBB->addSuccessor(offsetMBB);
12070 thisMBB->addSuccessor(overflowMBB);
12072 // endMBB is a successor of both offsetMBB and overflowMBB
12073 offsetMBB->addSuccessor(endMBB);
12074 overflowMBB->addSuccessor(endMBB);
12076 // Load the offset value into a register
12077 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12078 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12082 .addDisp(Disp, UseFPOffset ? 4 : 0)
12083 .addOperand(Segment)
12084 .setMemRefs(MMOBegin, MMOEnd);
12086 // Check if there is enough room left to pull this argument.
12087 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12089 .addImm(MaxOffset + 8 - ArgSizeA8);
12091 // Branch to "overflowMBB" if offset >= max
12092 // Fall through to "offsetMBB" otherwise
12093 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12094 .addMBB(overflowMBB);
12097 // In offsetMBB, emit code to use the reg_save_area.
12099 assert(OffsetReg != 0);
12101 // Read the reg_save_area address.
12102 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12103 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12108 .addOperand(Segment)
12109 .setMemRefs(MMOBegin, MMOEnd);
12111 // Zero-extend the offset
12112 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12113 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12116 .addImm(X86::sub_32bit);
12118 // Add the offset to the reg_save_area to get the final address.
12119 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12120 .addReg(OffsetReg64)
12121 .addReg(RegSaveReg);
12123 // Compute the offset for the next argument
12124 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12125 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12127 .addImm(UseFPOffset ? 16 : 8);
12129 // Store it back into the va_list.
12130 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12134 .addDisp(Disp, UseFPOffset ? 4 : 0)
12135 .addOperand(Segment)
12136 .addReg(NextOffsetReg)
12137 .setMemRefs(MMOBegin, MMOEnd);
12140 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12145 // Emit code to use overflow area
12148 // Load the overflow_area address into a register.
12149 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12150 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12155 .addOperand(Segment)
12156 .setMemRefs(MMOBegin, MMOEnd);
12158 // If we need to align it, do so. Otherwise, just copy the address
12159 // to OverflowDestReg.
12161 // Align the overflow address
12162 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12163 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12165 // aligned_addr = (addr + (align-1)) & ~(align-1)
12166 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12167 .addReg(OverflowAddrReg)
12170 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12172 .addImm(~(uint64_t)(Align-1));
12174 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12175 .addReg(OverflowAddrReg);
12178 // Compute the next overflow address after this argument.
12179 // (the overflow address should be kept 8-byte aligned)
12180 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12181 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12182 .addReg(OverflowDestReg)
12183 .addImm(ArgSizeA8);
12185 // Store the new overflow address.
12186 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12191 .addOperand(Segment)
12192 .addReg(NextAddrReg)
12193 .setMemRefs(MMOBegin, MMOEnd);
12195 // If we branched, emit the PHI to the front of endMBB.
12197 BuildMI(*endMBB, endMBB->begin(), DL,
12198 TII->get(X86::PHI), DestReg)
12199 .addReg(OffsetDestReg).addMBB(offsetMBB)
12200 .addReg(OverflowDestReg).addMBB(overflowMBB);
12203 // Erase the pseudo instruction
12204 MI->eraseFromParent();
12209 MachineBasicBlock *
12210 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12212 MachineBasicBlock *MBB) const {
12213 // Emit code to save XMM registers to the stack. The ABI says that the
12214 // number of registers to save is given in %al, so it's theoretically
12215 // possible to do an indirect jump trick to avoid saving all of them,
12216 // however this code takes a simpler approach and just executes all
12217 // of the stores if %al is non-zero. It's less code, and it's probably
12218 // easier on the hardware branch predictor, and stores aren't all that
12219 // expensive anyway.
12221 // Create the new basic blocks. One block contains all the XMM stores,
12222 // and one block is the final destination regardless of whether any
12223 // stores were performed.
12224 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12225 MachineFunction *F = MBB->getParent();
12226 MachineFunction::iterator MBBIter = MBB;
12228 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12229 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12230 F->insert(MBBIter, XMMSaveMBB);
12231 F->insert(MBBIter, EndMBB);
12233 // Transfer the remainder of MBB and its successor edges to EndMBB.
12234 EndMBB->splice(EndMBB->begin(), MBB,
12235 llvm::next(MachineBasicBlock::iterator(MI)),
12237 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12239 // The original block will now fall through to the XMM save block.
12240 MBB->addSuccessor(XMMSaveMBB);
12241 // The XMMSaveMBB will fall through to the end block.
12242 XMMSaveMBB->addSuccessor(EndMBB);
12244 // Now add the instructions.
12245 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12246 DebugLoc DL = MI->getDebugLoc();
12248 unsigned CountReg = MI->getOperand(0).getReg();
12249 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12250 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12252 if (!Subtarget->isTargetWin64()) {
12253 // If %al is 0, branch around the XMM save block.
12254 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12255 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12256 MBB->addSuccessor(EndMBB);
12259 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12260 // In the XMM save block, save all the XMM argument registers.
12261 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12262 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12263 MachineMemOperand *MMO =
12264 F->getMachineMemOperand(
12265 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12266 MachineMemOperand::MOStore,
12267 /*Size=*/16, /*Align=*/16);
12268 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12269 .addFrameIndex(RegSaveFrameIndex)
12270 .addImm(/*Scale=*/1)
12271 .addReg(/*IndexReg=*/0)
12272 .addImm(/*Disp=*/Offset)
12273 .addReg(/*Segment=*/0)
12274 .addReg(MI->getOperand(i).getReg())
12275 .addMemOperand(MMO);
12278 MI->eraseFromParent(); // The pseudo instruction is gone now.
12283 // The EFLAGS operand of SelectItr might be missing a kill marker
12284 // because there were multiple uses of EFLAGS, and ISel didn't know
12285 // which to mark. Figure out whether SelectItr should have had a
12286 // kill marker, and set it if it should. Returns the correct kill
12288 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12289 MachineBasicBlock* BB,
12290 const TargetRegisterInfo* TRI) {
12291 // Scan forward through BB for a use/def of EFLAGS.
12292 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12293 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12294 const MachineInstr& mi = *miI;
12295 if (mi.readsRegister(X86::EFLAGS))
12297 if (mi.definesRegister(X86::EFLAGS))
12298 break; // Should have kill-flag - update below.
12301 // If we hit the end of the block, check whether EFLAGS is live into a
12303 if (miI == BB->end()) {
12304 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12305 sEnd = BB->succ_end();
12306 sItr != sEnd; ++sItr) {
12307 MachineBasicBlock* succ = *sItr;
12308 if (succ->isLiveIn(X86::EFLAGS))
12313 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12314 // out. SelectMI should have a kill flag on EFLAGS.
12315 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12319 MachineBasicBlock *
12320 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12321 MachineBasicBlock *BB) const {
12322 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12323 DebugLoc DL = MI->getDebugLoc();
12325 // To "insert" a SELECT_CC instruction, we actually have to insert the
12326 // diamond control-flow pattern. The incoming instruction knows the
12327 // destination vreg to set, the condition code register to branch on, the
12328 // true/false values to select between, and a branch opcode to use.
12329 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12330 MachineFunction::iterator It = BB;
12336 // cmpTY ccX, r1, r2
12338 // fallthrough --> copy0MBB
12339 MachineBasicBlock *thisMBB = BB;
12340 MachineFunction *F = BB->getParent();
12341 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12342 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12343 F->insert(It, copy0MBB);
12344 F->insert(It, sinkMBB);
12346 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12347 // live into the sink and copy blocks.
12348 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12349 if (!MI->killsRegister(X86::EFLAGS) &&
12350 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12351 copy0MBB->addLiveIn(X86::EFLAGS);
12352 sinkMBB->addLiveIn(X86::EFLAGS);
12355 // Transfer the remainder of BB and its successor edges to sinkMBB.
12356 sinkMBB->splice(sinkMBB->begin(), BB,
12357 llvm::next(MachineBasicBlock::iterator(MI)),
12359 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12361 // Add the true and fallthrough blocks as its successors.
12362 BB->addSuccessor(copy0MBB);
12363 BB->addSuccessor(sinkMBB);
12365 // Create the conditional branch instruction.
12367 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12368 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12371 // %FalseValue = ...
12372 // # fallthrough to sinkMBB
12373 copy0MBB->addSuccessor(sinkMBB);
12376 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12378 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12379 TII->get(X86::PHI), MI->getOperand(0).getReg())
12380 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12381 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12383 MI->eraseFromParent(); // The pseudo instruction is gone now.
12387 MachineBasicBlock *
12388 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12389 bool Is64Bit) const {
12390 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12391 DebugLoc DL = MI->getDebugLoc();
12392 MachineFunction *MF = BB->getParent();
12393 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12395 assert(getTargetMachine().Options.EnableSegmentedStacks);
12397 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12398 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12401 // ... [Till the alloca]
12402 // If stacklet is not large enough, jump to mallocMBB
12405 // Allocate by subtracting from RSP
12406 // Jump to continueMBB
12409 // Allocate by call to runtime
12413 // [rest of original BB]
12416 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12417 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12418 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12420 MachineRegisterInfo &MRI = MF->getRegInfo();
12421 const TargetRegisterClass *AddrRegClass =
12422 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12424 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12425 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12426 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12427 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12428 sizeVReg = MI->getOperand(1).getReg(),
12429 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12431 MachineFunction::iterator MBBIter = BB;
12434 MF->insert(MBBIter, bumpMBB);
12435 MF->insert(MBBIter, mallocMBB);
12436 MF->insert(MBBIter, continueMBB);
12438 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12439 (MachineBasicBlock::iterator(MI)), BB->end());
12440 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12442 // Add code to the main basic block to check if the stack limit has been hit,
12443 // and if so, jump to mallocMBB otherwise to bumpMBB.
12444 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12445 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12446 .addReg(tmpSPVReg).addReg(sizeVReg);
12447 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12448 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12449 .addReg(SPLimitVReg);
12450 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12452 // bumpMBB simply decreases the stack pointer, since we know the current
12453 // stacklet has enough space.
12454 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12455 .addReg(SPLimitVReg);
12456 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12457 .addReg(SPLimitVReg);
12458 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12460 // Calls into a routine in libgcc to allocate more space from the heap.
12461 const uint32_t *RegMask =
12462 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12464 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12466 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12467 .addExternalSymbol("__morestack_allocate_stack_space")
12468 .addRegMask(RegMask)
12469 .addReg(X86::RDI, RegState::Implicit)
12470 .addReg(X86::RAX, RegState::ImplicitDefine);
12472 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12474 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12475 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12476 .addExternalSymbol("__morestack_allocate_stack_space")
12477 .addRegMask(RegMask)
12478 .addReg(X86::EAX, RegState::ImplicitDefine);
12482 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12485 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12486 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12487 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12489 // Set up the CFG correctly.
12490 BB->addSuccessor(bumpMBB);
12491 BB->addSuccessor(mallocMBB);
12492 mallocMBB->addSuccessor(continueMBB);
12493 bumpMBB->addSuccessor(continueMBB);
12495 // Take care of the PHI nodes.
12496 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12497 MI->getOperand(0).getReg())
12498 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12499 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12501 // Delete the original pseudo instruction.
12502 MI->eraseFromParent();
12505 return continueMBB;
12508 MachineBasicBlock *
12509 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12510 MachineBasicBlock *BB) const {
12511 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12512 DebugLoc DL = MI->getDebugLoc();
12514 assert(!Subtarget->isTargetEnvMacho());
12516 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12517 // non-trivial part is impdef of ESP.
12519 if (Subtarget->isTargetWin64()) {
12520 if (Subtarget->isTargetCygMing()) {
12521 // ___chkstk(Mingw64):
12522 // Clobbers R10, R11, RAX and EFLAGS.
12524 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12525 .addExternalSymbol("___chkstk")
12526 .addReg(X86::RAX, RegState::Implicit)
12527 .addReg(X86::RSP, RegState::Implicit)
12528 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12529 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12530 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12532 // __chkstk(MSVCRT): does not update stack pointer.
12533 // Clobbers R10, R11 and EFLAGS.
12534 // FIXME: RAX(allocated size) might be reused and not killed.
12535 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12536 .addExternalSymbol("__chkstk")
12537 .addReg(X86::RAX, RegState::Implicit)
12538 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12539 // RAX has the offset to subtracted from RSP.
12540 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12545 const char *StackProbeSymbol =
12546 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12548 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12549 .addExternalSymbol(StackProbeSymbol)
12550 .addReg(X86::EAX, RegState::Implicit)
12551 .addReg(X86::ESP, RegState::Implicit)
12552 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12553 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12554 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12557 MI->eraseFromParent(); // The pseudo instruction is gone now.
12561 MachineBasicBlock *
12562 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12563 MachineBasicBlock *BB) const {
12564 // This is pretty easy. We're taking the value that we received from
12565 // our load from the relocation, sticking it in either RDI (x86-64)
12566 // or EAX and doing an indirect call. The return value will then
12567 // be in the normal return register.
12568 const X86InstrInfo *TII
12569 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12570 DebugLoc DL = MI->getDebugLoc();
12571 MachineFunction *F = BB->getParent();
12573 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12574 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12576 // Get a register mask for the lowered call.
12577 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12578 // proper register mask.
12579 const uint32_t *RegMask =
12580 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12581 if (Subtarget->is64Bit()) {
12582 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12583 TII->get(X86::MOV64rm), X86::RDI)
12585 .addImm(0).addReg(0)
12586 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12587 MI->getOperand(3).getTargetFlags())
12589 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12590 addDirectMem(MIB, X86::RDI);
12591 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12592 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12593 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12594 TII->get(X86::MOV32rm), X86::EAX)
12596 .addImm(0).addReg(0)
12597 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12598 MI->getOperand(3).getTargetFlags())
12600 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12601 addDirectMem(MIB, X86::EAX);
12602 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12604 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12605 TII->get(X86::MOV32rm), X86::EAX)
12606 .addReg(TII->getGlobalBaseReg(F))
12607 .addImm(0).addReg(0)
12608 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12609 MI->getOperand(3).getTargetFlags())
12611 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12612 addDirectMem(MIB, X86::EAX);
12613 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12616 MI->eraseFromParent(); // The pseudo instruction is gone now.
12620 MachineBasicBlock *
12621 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12622 MachineBasicBlock *BB) const {
12623 switch (MI->getOpcode()) {
12624 default: llvm_unreachable("Unexpected instr type to insert");
12625 case X86::TAILJMPd64:
12626 case X86::TAILJMPr64:
12627 case X86::TAILJMPm64:
12628 llvm_unreachable("TAILJMP64 would not be touched here.");
12629 case X86::TCRETURNdi64:
12630 case X86::TCRETURNri64:
12631 case X86::TCRETURNmi64:
12633 case X86::WIN_ALLOCA:
12634 return EmitLoweredWinAlloca(MI, BB);
12635 case X86::SEG_ALLOCA_32:
12636 return EmitLoweredSegAlloca(MI, BB, false);
12637 case X86::SEG_ALLOCA_64:
12638 return EmitLoweredSegAlloca(MI, BB, true);
12639 case X86::TLSCall_32:
12640 case X86::TLSCall_64:
12641 return EmitLoweredTLSCall(MI, BB);
12642 case X86::CMOV_GR8:
12643 case X86::CMOV_FR32:
12644 case X86::CMOV_FR64:
12645 case X86::CMOV_V4F32:
12646 case X86::CMOV_V2F64:
12647 case X86::CMOV_V2I64:
12648 case X86::CMOV_V8F32:
12649 case X86::CMOV_V4F64:
12650 case X86::CMOV_V4I64:
12651 case X86::CMOV_GR16:
12652 case X86::CMOV_GR32:
12653 case X86::CMOV_RFP32:
12654 case X86::CMOV_RFP64:
12655 case X86::CMOV_RFP80:
12656 return EmitLoweredSelect(MI, BB);
12658 case X86::FP32_TO_INT16_IN_MEM:
12659 case X86::FP32_TO_INT32_IN_MEM:
12660 case X86::FP32_TO_INT64_IN_MEM:
12661 case X86::FP64_TO_INT16_IN_MEM:
12662 case X86::FP64_TO_INT32_IN_MEM:
12663 case X86::FP64_TO_INT64_IN_MEM:
12664 case X86::FP80_TO_INT16_IN_MEM:
12665 case X86::FP80_TO_INT32_IN_MEM:
12666 case X86::FP80_TO_INT64_IN_MEM: {
12667 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12668 DebugLoc DL = MI->getDebugLoc();
12670 // Change the floating point control register to use "round towards zero"
12671 // mode when truncating to an integer value.
12672 MachineFunction *F = BB->getParent();
12673 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12674 addFrameReference(BuildMI(*BB, MI, DL,
12675 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12677 // Load the old value of the high byte of the control word...
12679 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12680 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12683 // Set the high part to be round to zero...
12684 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12687 // Reload the modified control word now...
12688 addFrameReference(BuildMI(*BB, MI, DL,
12689 TII->get(X86::FLDCW16m)), CWFrameIdx);
12691 // Restore the memory image of control word to original value
12692 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12695 // Get the X86 opcode to use.
12697 switch (MI->getOpcode()) {
12698 default: llvm_unreachable("illegal opcode!");
12699 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12700 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12701 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12702 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12703 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12704 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12705 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12706 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12707 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12711 MachineOperand &Op = MI->getOperand(0);
12713 AM.BaseType = X86AddressMode::RegBase;
12714 AM.Base.Reg = Op.getReg();
12716 AM.BaseType = X86AddressMode::FrameIndexBase;
12717 AM.Base.FrameIndex = Op.getIndex();
12719 Op = MI->getOperand(1);
12721 AM.Scale = Op.getImm();
12722 Op = MI->getOperand(2);
12724 AM.IndexReg = Op.getImm();
12725 Op = MI->getOperand(3);
12726 if (Op.isGlobal()) {
12727 AM.GV = Op.getGlobal();
12729 AM.Disp = Op.getImm();
12731 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12732 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12734 // Reload the original control word now.
12735 addFrameReference(BuildMI(*BB, MI, DL,
12736 TII->get(X86::FLDCW16m)), CWFrameIdx);
12738 MI->eraseFromParent(); // The pseudo instruction is gone now.
12741 // String/text processing lowering.
12742 case X86::PCMPISTRM128REG:
12743 case X86::VPCMPISTRM128REG:
12744 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12745 case X86::PCMPISTRM128MEM:
12746 case X86::VPCMPISTRM128MEM:
12747 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12748 case X86::PCMPESTRM128REG:
12749 case X86::VPCMPESTRM128REG:
12750 return EmitPCMP(MI, BB, 5, false /* in mem */);
12751 case X86::PCMPESTRM128MEM:
12752 case X86::VPCMPESTRM128MEM:
12753 return EmitPCMP(MI, BB, 5, true /* in mem */);
12755 // Thread synchronization.
12757 return EmitMonitor(MI, BB);
12759 // Atomic Lowering.
12760 case X86::ATOMAND32:
12761 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12762 X86::AND32ri, X86::MOV32rm,
12764 X86::NOT32r, X86::EAX,
12765 &X86::GR32RegClass);
12766 case X86::ATOMOR32:
12767 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12768 X86::OR32ri, X86::MOV32rm,
12770 X86::NOT32r, X86::EAX,
12771 &X86::GR32RegClass);
12772 case X86::ATOMXOR32:
12773 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12774 X86::XOR32ri, X86::MOV32rm,
12776 X86::NOT32r, X86::EAX,
12777 &X86::GR32RegClass);
12778 case X86::ATOMNAND32:
12779 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12780 X86::AND32ri, X86::MOV32rm,
12782 X86::NOT32r, X86::EAX,
12783 &X86::GR32RegClass, true);
12784 case X86::ATOMMIN32:
12785 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12786 case X86::ATOMMAX32:
12787 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12788 case X86::ATOMUMIN32:
12789 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12790 case X86::ATOMUMAX32:
12791 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12793 case X86::ATOMAND16:
12794 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12795 X86::AND16ri, X86::MOV16rm,
12797 X86::NOT16r, X86::AX,
12798 &X86::GR16RegClass);
12799 case X86::ATOMOR16:
12800 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12801 X86::OR16ri, X86::MOV16rm,
12803 X86::NOT16r, X86::AX,
12804 &X86::GR16RegClass);
12805 case X86::ATOMXOR16:
12806 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12807 X86::XOR16ri, X86::MOV16rm,
12809 X86::NOT16r, X86::AX,
12810 &X86::GR16RegClass);
12811 case X86::ATOMNAND16:
12812 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12813 X86::AND16ri, X86::MOV16rm,
12815 X86::NOT16r, X86::AX,
12816 &X86::GR16RegClass, true);
12817 case X86::ATOMMIN16:
12818 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12819 case X86::ATOMMAX16:
12820 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12821 case X86::ATOMUMIN16:
12822 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12823 case X86::ATOMUMAX16:
12824 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12826 case X86::ATOMAND8:
12827 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12828 X86::AND8ri, X86::MOV8rm,
12830 X86::NOT8r, X86::AL,
12831 &X86::GR8RegClass);
12833 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12834 X86::OR8ri, X86::MOV8rm,
12836 X86::NOT8r, X86::AL,
12837 &X86::GR8RegClass);
12838 case X86::ATOMXOR8:
12839 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12840 X86::XOR8ri, X86::MOV8rm,
12842 X86::NOT8r, X86::AL,
12843 &X86::GR8RegClass);
12844 case X86::ATOMNAND8:
12845 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12846 X86::AND8ri, X86::MOV8rm,
12848 X86::NOT8r, X86::AL,
12849 &X86::GR8RegClass, true);
12850 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12851 // This group is for 64-bit host.
12852 case X86::ATOMAND64:
12853 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12854 X86::AND64ri32, X86::MOV64rm,
12856 X86::NOT64r, X86::RAX,
12857 &X86::GR64RegClass);
12858 case X86::ATOMOR64:
12859 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12860 X86::OR64ri32, X86::MOV64rm,
12862 X86::NOT64r, X86::RAX,
12863 &X86::GR64RegClass);
12864 case X86::ATOMXOR64:
12865 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12866 X86::XOR64ri32, X86::MOV64rm,
12868 X86::NOT64r, X86::RAX,
12869 &X86::GR64RegClass);
12870 case X86::ATOMNAND64:
12871 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12872 X86::AND64ri32, X86::MOV64rm,
12874 X86::NOT64r, X86::RAX,
12875 &X86::GR64RegClass, true);
12876 case X86::ATOMMIN64:
12877 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12878 case X86::ATOMMAX64:
12879 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12880 case X86::ATOMUMIN64:
12881 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12882 case X86::ATOMUMAX64:
12883 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12885 // This group does 64-bit operations on a 32-bit host.
12886 case X86::ATOMAND6432:
12887 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12888 X86::AND32rr, X86::AND32rr,
12889 X86::AND32ri, X86::AND32ri,
12891 case X86::ATOMOR6432:
12892 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12893 X86::OR32rr, X86::OR32rr,
12894 X86::OR32ri, X86::OR32ri,
12896 case X86::ATOMXOR6432:
12897 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12898 X86::XOR32rr, X86::XOR32rr,
12899 X86::XOR32ri, X86::XOR32ri,
12901 case X86::ATOMNAND6432:
12902 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12903 X86::AND32rr, X86::AND32rr,
12904 X86::AND32ri, X86::AND32ri,
12906 case X86::ATOMADD6432:
12907 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12908 X86::ADD32rr, X86::ADC32rr,
12909 X86::ADD32ri, X86::ADC32ri,
12911 case X86::ATOMSUB6432:
12912 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12913 X86::SUB32rr, X86::SBB32rr,
12914 X86::SUB32ri, X86::SBB32ri,
12916 case X86::ATOMSWAP6432:
12917 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12918 X86::MOV32rr, X86::MOV32rr,
12919 X86::MOV32ri, X86::MOV32ri,
12921 case X86::VASTART_SAVE_XMM_REGS:
12922 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12924 case X86::VAARG_64:
12925 return EmitVAARG64WithCustomInserter(MI, BB);
12929 //===----------------------------------------------------------------------===//
12930 // X86 Optimization Hooks
12931 //===----------------------------------------------------------------------===//
12933 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12936 const SelectionDAG &DAG,
12937 unsigned Depth) const {
12938 unsigned BitWidth = KnownZero.getBitWidth();
12939 unsigned Opc = Op.getOpcode();
12940 assert((Opc >= ISD::BUILTIN_OP_END ||
12941 Opc == ISD::INTRINSIC_WO_CHAIN ||
12942 Opc == ISD::INTRINSIC_W_CHAIN ||
12943 Opc == ISD::INTRINSIC_VOID) &&
12944 "Should use MaskedValueIsZero if you don't know whether Op"
12945 " is a target node!");
12947 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
12961 // These nodes' second result is a boolean.
12962 if (Op.getResNo() == 0)
12965 case X86ISD::SETCC:
12966 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12968 case ISD::INTRINSIC_WO_CHAIN: {
12969 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12970 unsigned NumLoBits = 0;
12973 case Intrinsic::x86_sse_movmsk_ps:
12974 case Intrinsic::x86_avx_movmsk_ps_256:
12975 case Intrinsic::x86_sse2_movmsk_pd:
12976 case Intrinsic::x86_avx_movmsk_pd_256:
12977 case Intrinsic::x86_mmx_pmovmskb:
12978 case Intrinsic::x86_sse2_pmovmskb_128:
12979 case Intrinsic::x86_avx2_pmovmskb: {
12980 // High bits of movmskp{s|d}, pmovmskb are known zero.
12982 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12983 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12984 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12985 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12986 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12987 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12988 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12989 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
12991 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13000 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13001 unsigned Depth) const {
13002 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13003 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13004 return Op.getValueType().getScalarType().getSizeInBits();
13010 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13011 /// node is a GlobalAddress + offset.
13012 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13013 const GlobalValue* &GA,
13014 int64_t &Offset) const {
13015 if (N->getOpcode() == X86ISD::Wrapper) {
13016 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13017 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13018 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13022 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13025 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13026 /// same as extracting the high 128-bit part of 256-bit vector and then
13027 /// inserting the result into the low part of a new 256-bit vector
13028 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13029 EVT VT = SVOp->getValueType(0);
13030 unsigned NumElems = VT.getVectorNumElements();
13032 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13033 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13034 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13035 SVOp->getMaskElt(j) >= 0)
13041 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13042 /// same as extracting the low 128-bit part of 256-bit vector and then
13043 /// inserting the result into the high part of a new 256-bit vector
13044 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13045 EVT VT = SVOp->getValueType(0);
13046 unsigned NumElems = VT.getVectorNumElements();
13048 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13049 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13050 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13051 SVOp->getMaskElt(j) >= 0)
13057 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13058 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13059 TargetLowering::DAGCombinerInfo &DCI,
13060 const X86Subtarget* Subtarget) {
13061 DebugLoc dl = N->getDebugLoc();
13062 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13063 SDValue V1 = SVOp->getOperand(0);
13064 SDValue V2 = SVOp->getOperand(1);
13065 EVT VT = SVOp->getValueType(0);
13066 unsigned NumElems = VT.getVectorNumElements();
13068 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13069 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13073 // V UNDEF BUILD_VECTOR UNDEF
13075 // CONCAT_VECTOR CONCAT_VECTOR
13078 // RESULT: V + zero extended
13080 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13081 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13082 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13085 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13088 // To match the shuffle mask, the first half of the mask should
13089 // be exactly the first vector, and all the rest a splat with the
13090 // first element of the second one.
13091 for (unsigned i = 0; i != NumElems/2; ++i)
13092 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13093 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13096 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13097 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13098 if (Ld->hasNUsesOfValue(1, 0)) {
13099 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13100 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13102 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13104 Ld->getPointerInfo(),
13105 Ld->getAlignment(),
13106 false/*isVolatile*/, true/*ReadMem*/,
13107 false/*WriteMem*/);
13108 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13112 // Emit a zeroed vector and insert the desired subvector on its
13114 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13115 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13116 return DCI.CombineTo(N, InsV);
13119 //===--------------------------------------------------------------------===//
13120 // Combine some shuffles into subvector extracts and inserts:
13123 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13124 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13125 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13126 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13127 return DCI.CombineTo(N, InsV);
13130 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13131 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13132 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13133 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13134 return DCI.CombineTo(N, InsV);
13140 /// PerformShuffleCombine - Performs several different shuffle combines.
13141 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13142 TargetLowering::DAGCombinerInfo &DCI,
13143 const X86Subtarget *Subtarget) {
13144 DebugLoc dl = N->getDebugLoc();
13145 EVT VT = N->getValueType(0);
13147 // Don't create instructions with illegal types after legalize types has run.
13148 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13149 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13152 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13153 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13154 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13155 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13157 // Only handle 128 wide vector from here on.
13158 if (VT.getSizeInBits() != 128)
13161 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13162 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13163 // consecutive, non-overlapping, and in the right order.
13164 SmallVector<SDValue, 16> Elts;
13165 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13166 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13168 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13172 /// DCI, PerformTruncateCombine - Converts truncate operation to
13173 /// a sequence of vector shuffle operations.
13174 /// It is possible when we truncate 256-bit vector to 128-bit vector
13176 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13177 DAGCombinerInfo &DCI) const {
13178 if (!DCI.isBeforeLegalizeOps())
13181 if (!Subtarget->hasAVX())
13184 EVT VT = N->getValueType(0);
13185 SDValue Op = N->getOperand(0);
13186 EVT OpVT = Op.getValueType();
13187 DebugLoc dl = N->getDebugLoc();
13189 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13191 if (Subtarget->hasAVX2()) {
13192 // AVX2: v4i64 -> v4i32
13195 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13197 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13198 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13201 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13202 DAG.getIntPtrConstant(0));
13205 // AVX: v4i64 -> v4i32
13206 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13207 DAG.getIntPtrConstant(0));
13209 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13210 DAG.getIntPtrConstant(2));
13212 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13213 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13216 static const int ShufMask1[] = {0, 2, 0, 0};
13218 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13219 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13222 static const int ShufMask2[] = {0, 1, 4, 5};
13224 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13227 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13229 if (Subtarget->hasAVX2()) {
13230 // AVX2: v8i32 -> v8i16
13232 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13235 SmallVector<SDValue,32> pshufbMask;
13236 for (unsigned i = 0; i < 2; ++i) {
13237 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13238 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13239 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13240 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13241 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13242 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13243 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13244 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13245 for (unsigned j = 0; j < 8; ++j)
13246 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13248 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13249 &pshufbMask[0], 32);
13250 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13252 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13254 static const int ShufMask[] = {0, 2, -1, -1};
13255 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13258 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13259 DAG.getIntPtrConstant(0));
13261 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13264 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13265 DAG.getIntPtrConstant(0));
13267 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13268 DAG.getIntPtrConstant(4));
13270 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13271 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13274 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13275 -1, -1, -1, -1, -1, -1, -1, -1};
13277 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13279 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13282 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13283 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13286 static const int ShufMask2[] = {0, 1, 4, 5};
13288 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13289 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13295 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13296 /// specific shuffle of a load can be folded into a single element load.
13297 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13298 /// shuffles have been customed lowered so we need to handle those here.
13299 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13300 TargetLowering::DAGCombinerInfo &DCI) {
13301 if (DCI.isBeforeLegalizeOps())
13304 SDValue InVec = N->getOperand(0);
13305 SDValue EltNo = N->getOperand(1);
13307 if (!isa<ConstantSDNode>(EltNo))
13310 EVT VT = InVec.getValueType();
13312 bool HasShuffleIntoBitcast = false;
13313 if (InVec.getOpcode() == ISD::BITCAST) {
13314 // Don't duplicate a load with other uses.
13315 if (!InVec.hasOneUse())
13317 EVT BCVT = InVec.getOperand(0).getValueType();
13318 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13320 InVec = InVec.getOperand(0);
13321 HasShuffleIntoBitcast = true;
13324 if (!isTargetShuffle(InVec.getOpcode()))
13327 // Don't duplicate a load with other uses.
13328 if (!InVec.hasOneUse())
13331 SmallVector<int, 16> ShuffleMask;
13333 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13337 // Select the input vector, guarding against out of range extract vector.
13338 unsigned NumElems = VT.getVectorNumElements();
13339 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13340 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13341 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13342 : InVec.getOperand(1);
13344 // If inputs to shuffle are the same for both ops, then allow 2 uses
13345 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13347 if (LdNode.getOpcode() == ISD::BITCAST) {
13348 // Don't duplicate a load with other uses.
13349 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13352 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13353 LdNode = LdNode.getOperand(0);
13356 if (!ISD::isNormalLoad(LdNode.getNode()))
13359 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13361 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13364 if (HasShuffleIntoBitcast) {
13365 // If there's a bitcast before the shuffle, check if the load type and
13366 // alignment is valid.
13367 unsigned Align = LN0->getAlignment();
13368 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13369 unsigned NewAlign = TLI.getTargetData()->
13370 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13372 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13376 // All checks match so transform back to vector_shuffle so that DAG combiner
13377 // can finish the job
13378 DebugLoc dl = N->getDebugLoc();
13380 // Create shuffle node taking into account the case that its a unary shuffle
13381 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13382 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13383 InVec.getOperand(0), Shuffle,
13385 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13386 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13390 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13391 /// generation and convert it from being a bunch of shuffles and extracts
13392 /// to a simple store and scalar loads to extract the elements.
13393 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13394 TargetLowering::DAGCombinerInfo &DCI) {
13395 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13396 if (NewOp.getNode())
13399 SDValue InputVector = N->getOperand(0);
13401 // Only operate on vectors of 4 elements, where the alternative shuffling
13402 // gets to be more expensive.
13403 if (InputVector.getValueType() != MVT::v4i32)
13406 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13407 // single use which is a sign-extend or zero-extend, and all elements are
13409 SmallVector<SDNode *, 4> Uses;
13410 unsigned ExtractedElements = 0;
13411 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13412 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13413 if (UI.getUse().getResNo() != InputVector.getResNo())
13416 SDNode *Extract = *UI;
13417 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13420 if (Extract->getValueType(0) != MVT::i32)
13422 if (!Extract->hasOneUse())
13424 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13425 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13427 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13430 // Record which element was extracted.
13431 ExtractedElements |=
13432 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13434 Uses.push_back(Extract);
13437 // If not all the elements were used, this may not be worthwhile.
13438 if (ExtractedElements != 15)
13441 // Ok, we've now decided to do the transformation.
13442 DebugLoc dl = InputVector.getDebugLoc();
13444 // Store the value to a temporary stack slot.
13445 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13446 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13447 MachinePointerInfo(), false, false, 0);
13449 // Replace each use (extract) with a load of the appropriate element.
13450 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13451 UE = Uses.end(); UI != UE; ++UI) {
13452 SDNode *Extract = *UI;
13454 // cOMpute the element's address.
13455 SDValue Idx = Extract->getOperand(1);
13457 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13458 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13459 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13460 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13462 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13463 StackPtr, OffsetVal);
13465 // Load the scalar.
13466 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13467 ScalarAddr, MachinePointerInfo(),
13468 false, false, false, 0);
13470 // Replace the exact with the load.
13471 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13474 // The replacement was made in place; don't return anything.
13478 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13480 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13481 TargetLowering::DAGCombinerInfo &DCI,
13482 const X86Subtarget *Subtarget) {
13483 DebugLoc DL = N->getDebugLoc();
13484 SDValue Cond = N->getOperand(0);
13485 // Get the LHS/RHS of the select.
13486 SDValue LHS = N->getOperand(1);
13487 SDValue RHS = N->getOperand(2);
13488 EVT VT = LHS.getValueType();
13490 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13491 // instructions match the semantics of the common C idiom x<y?x:y but not
13492 // x<=y?x:y, because of how they handle negative zero (which can be
13493 // ignored in unsafe-math mode).
13494 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13495 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13496 (Subtarget->hasSSE2() ||
13497 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13498 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13500 unsigned Opcode = 0;
13501 // Check for x CC y ? x : y.
13502 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13503 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13507 // Converting this to a min would handle NaNs incorrectly, and swapping
13508 // the operands would cause it to handle comparisons between positive
13509 // and negative zero incorrectly.
13510 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13511 if (!DAG.getTarget().Options.UnsafeFPMath &&
13512 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13514 std::swap(LHS, RHS);
13516 Opcode = X86ISD::FMIN;
13519 // Converting this to a min would handle comparisons between positive
13520 // and negative zero incorrectly.
13521 if (!DAG.getTarget().Options.UnsafeFPMath &&
13522 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13524 Opcode = X86ISD::FMIN;
13527 // Converting this to a min would handle both negative zeros and NaNs
13528 // incorrectly, but we can swap the operands to fix both.
13529 std::swap(LHS, RHS);
13533 Opcode = X86ISD::FMIN;
13537 // Converting this to a max would handle comparisons between positive
13538 // and negative zero incorrectly.
13539 if (!DAG.getTarget().Options.UnsafeFPMath &&
13540 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13542 Opcode = X86ISD::FMAX;
13545 // Converting this to a max would handle NaNs incorrectly, and swapping
13546 // the operands would cause it to handle comparisons between positive
13547 // and negative zero incorrectly.
13548 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13549 if (!DAG.getTarget().Options.UnsafeFPMath &&
13550 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13552 std::swap(LHS, RHS);
13554 Opcode = X86ISD::FMAX;
13557 // Converting this to a max would handle both negative zeros and NaNs
13558 // incorrectly, but we can swap the operands to fix both.
13559 std::swap(LHS, RHS);
13563 Opcode = X86ISD::FMAX;
13566 // Check for x CC y ? y : x -- a min/max with reversed arms.
13567 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13568 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13572 // Converting this to a min would handle comparisons between positive
13573 // and negative zero incorrectly, and swapping the operands would
13574 // cause it to handle NaNs incorrectly.
13575 if (!DAG.getTarget().Options.UnsafeFPMath &&
13576 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13577 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13579 std::swap(LHS, RHS);
13581 Opcode = X86ISD::FMIN;
13584 // Converting this to a min would handle NaNs incorrectly.
13585 if (!DAG.getTarget().Options.UnsafeFPMath &&
13586 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13588 Opcode = X86ISD::FMIN;
13591 // Converting this to a min would handle both negative zeros and NaNs
13592 // incorrectly, but we can swap the operands to fix both.
13593 std::swap(LHS, RHS);
13597 Opcode = X86ISD::FMIN;
13601 // Converting this to a max would handle NaNs incorrectly.
13602 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13604 Opcode = X86ISD::FMAX;
13607 // Converting this to a max would handle comparisons between positive
13608 // and negative zero incorrectly, and swapping the operands would
13609 // cause it to handle NaNs incorrectly.
13610 if (!DAG.getTarget().Options.UnsafeFPMath &&
13611 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13612 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13614 std::swap(LHS, RHS);
13616 Opcode = X86ISD::FMAX;
13619 // Converting this to a max would handle both negative zeros and NaNs
13620 // incorrectly, but we can swap the operands to fix both.
13621 std::swap(LHS, RHS);
13625 Opcode = X86ISD::FMAX;
13631 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13634 // If this is a select between two integer constants, try to do some
13636 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13637 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13638 // Don't do this for crazy integer types.
13639 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13640 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13641 // so that TrueC (the true value) is larger than FalseC.
13642 bool NeedsCondInvert = false;
13644 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13645 // Efficiently invertible.
13646 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13647 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13648 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13649 NeedsCondInvert = true;
13650 std::swap(TrueC, FalseC);
13653 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13654 if (FalseC->getAPIntValue() == 0 &&
13655 TrueC->getAPIntValue().isPowerOf2()) {
13656 if (NeedsCondInvert) // Invert the condition if needed.
13657 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13658 DAG.getConstant(1, Cond.getValueType()));
13660 // Zero extend the condition if needed.
13661 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13663 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13664 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13665 DAG.getConstant(ShAmt, MVT::i8));
13668 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13669 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13670 if (NeedsCondInvert) // Invert the condition if needed.
13671 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13672 DAG.getConstant(1, Cond.getValueType()));
13674 // Zero extend the condition if needed.
13675 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13676 FalseC->getValueType(0), Cond);
13677 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13678 SDValue(FalseC, 0));
13681 // Optimize cases that will turn into an LEA instruction. This requires
13682 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13683 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13684 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13685 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13687 bool isFastMultiplier = false;
13689 switch ((unsigned char)Diff) {
13691 case 1: // result = add base, cond
13692 case 2: // result = lea base( , cond*2)
13693 case 3: // result = lea base(cond, cond*2)
13694 case 4: // result = lea base( , cond*4)
13695 case 5: // result = lea base(cond, cond*4)
13696 case 8: // result = lea base( , cond*8)
13697 case 9: // result = lea base(cond, cond*8)
13698 isFastMultiplier = true;
13703 if (isFastMultiplier) {
13704 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13705 if (NeedsCondInvert) // Invert the condition if needed.
13706 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13707 DAG.getConstant(1, Cond.getValueType()));
13709 // Zero extend the condition if needed.
13710 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13712 // Scale the condition by the difference.
13714 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13715 DAG.getConstant(Diff, Cond.getValueType()));
13717 // Add the base if non-zero.
13718 if (FalseC->getAPIntValue() != 0)
13719 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13720 SDValue(FalseC, 0));
13727 // Canonicalize max and min:
13728 // (x > y) ? x : y -> (x >= y) ? x : y
13729 // (x < y) ? x : y -> (x <= y) ? x : y
13730 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13731 // the need for an extra compare
13732 // against zero. e.g.
13733 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13735 // testl %edi, %edi
13737 // cmovgl %edi, %eax
13741 // cmovsl %eax, %edi
13742 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13743 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13744 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13745 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13750 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13751 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13752 Cond.getOperand(0), Cond.getOperand(1), NewCC);
13753 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13758 // If we know that this node is legal then we know that it is going to be
13759 // matched by one of the SSE/AVX BLEND instructions. These instructions only
13760 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13761 // to simplify previous instructions.
13762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13763 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13764 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13765 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13767 // Don't optimize vector selects that map to mask-registers.
13771 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13772 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13774 APInt KnownZero, KnownOne;
13775 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13776 DCI.isBeforeLegalizeOps());
13777 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13778 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13779 DCI.CommitTargetLoweringOpt(TLO);
13785 // Check whether a boolean test is testing a boolean value generated by
13786 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
13789 // Simplify the following patterns:
13790 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
13791 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
13792 // to (Op EFLAGS Cond)
13794 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
13795 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
13796 // to (Op EFLAGS !Cond)
13798 // where Op could be BRCOND or CMOV.
13800 static SDValue BoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
13801 // Quit if not CMP and SUB with its value result used.
13802 if (Cmp.getOpcode() != X86ISD::CMP &&
13803 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
13806 // Quit if not used as a boolean value.
13807 if (CC != X86::COND_E && CC != X86::COND_NE)
13810 // Check CMP operands. One of them should be 0 or 1 and the other should be
13811 // an SetCC or extended from it.
13812 SDValue Op1 = Cmp.getOperand(0);
13813 SDValue Op2 = Cmp.getOperand(1);
13816 const ConstantSDNode* C = 0;
13817 bool needOppositeCond = (CC == X86::COND_E);
13819 if ((C = dyn_cast<ConstantSDNode>(Op1)))
13821 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
13823 else // Quit if all operands are not constants.
13826 if (C->getZExtValue() == 1)
13827 needOppositeCond = !needOppositeCond;
13828 else if (C->getZExtValue() != 0)
13829 // Quit if the constant is neither 0 or 1.
13832 // Skip 'zext' node.
13833 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
13834 SetCC = SetCC.getOperand(0);
13836 // Quit if not SETCC.
13837 // FIXME: So far we only handle the boolean value generated from SETCC. If
13838 // there is other ways to generate boolean values, we need handle them here
13840 if (SetCC.getOpcode() != X86ISD::SETCC)
13843 // Set the condition code or opposite one if necessary.
13844 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
13845 if (needOppositeCond)
13846 CC = X86::GetOppositeBranchCondition(CC);
13848 return SetCC.getOperand(1);
13851 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13852 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13853 TargetLowering::DAGCombinerInfo &DCI) {
13854 DebugLoc DL = N->getDebugLoc();
13856 // If the flag operand isn't dead, don't touch this CMOV.
13857 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13860 SDValue FalseOp = N->getOperand(0);
13861 SDValue TrueOp = N->getOperand(1);
13862 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13863 SDValue Cond = N->getOperand(3);
13865 if (CC == X86::COND_E || CC == X86::COND_NE) {
13866 switch (Cond.getOpcode()) {
13870 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13871 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13872 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13878 Flags = BoolTestSetCCCombine(Cond, CC);
13879 if (Flags.getNode()) {
13880 SDValue Ops[] = { FalseOp, TrueOp,
13881 DAG.getConstant(CC, MVT::i8), Flags };
13882 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
13883 Ops, array_lengthof(Ops));
13886 // If this is a select between two integer constants, try to do some
13887 // optimizations. Note that the operands are ordered the opposite of SELECT
13889 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13890 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13891 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13892 // larger than FalseC (the false value).
13893 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13894 CC = X86::GetOppositeBranchCondition(CC);
13895 std::swap(TrueC, FalseC);
13898 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13899 // This is efficient for any integer data type (including i8/i16) and
13901 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13902 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13903 DAG.getConstant(CC, MVT::i8), Cond);
13905 // Zero extend the condition if needed.
13906 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13908 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13909 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13910 DAG.getConstant(ShAmt, MVT::i8));
13911 if (N->getNumValues() == 2) // Dead flag value?
13912 return DCI.CombineTo(N, Cond, SDValue());
13916 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13917 // for any integer data type, including i8/i16.
13918 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13919 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13920 DAG.getConstant(CC, MVT::i8), Cond);
13922 // Zero extend the condition if needed.
13923 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13924 FalseC->getValueType(0), Cond);
13925 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13926 SDValue(FalseC, 0));
13928 if (N->getNumValues() == 2) // Dead flag value?
13929 return DCI.CombineTo(N, Cond, SDValue());
13933 // Optimize cases that will turn into an LEA instruction. This requires
13934 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13935 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13936 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13937 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13939 bool isFastMultiplier = false;
13941 switch ((unsigned char)Diff) {
13943 case 1: // result = add base, cond
13944 case 2: // result = lea base( , cond*2)
13945 case 3: // result = lea base(cond, cond*2)
13946 case 4: // result = lea base( , cond*4)
13947 case 5: // result = lea base(cond, cond*4)
13948 case 8: // result = lea base( , cond*8)
13949 case 9: // result = lea base(cond, cond*8)
13950 isFastMultiplier = true;
13955 if (isFastMultiplier) {
13956 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13957 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13958 DAG.getConstant(CC, MVT::i8), Cond);
13959 // Zero extend the condition if needed.
13960 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13962 // Scale the condition by the difference.
13964 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13965 DAG.getConstant(Diff, Cond.getValueType()));
13967 // Add the base if non-zero.
13968 if (FalseC->getAPIntValue() != 0)
13969 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13970 SDValue(FalseC, 0));
13971 if (N->getNumValues() == 2) // Dead flag value?
13972 return DCI.CombineTo(N, Cond, SDValue());
13982 /// PerformMulCombine - Optimize a single multiply with constant into two
13983 /// in order to implement it with two cheaper instructions, e.g.
13984 /// LEA + SHL, LEA + LEA.
13985 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13986 TargetLowering::DAGCombinerInfo &DCI) {
13987 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13990 EVT VT = N->getValueType(0);
13991 if (VT != MVT::i64)
13994 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13997 uint64_t MulAmt = C->getZExtValue();
13998 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14001 uint64_t MulAmt1 = 0;
14002 uint64_t MulAmt2 = 0;
14003 if ((MulAmt % 9) == 0) {
14005 MulAmt2 = MulAmt / 9;
14006 } else if ((MulAmt % 5) == 0) {
14008 MulAmt2 = MulAmt / 5;
14009 } else if ((MulAmt % 3) == 0) {
14011 MulAmt2 = MulAmt / 3;
14014 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14015 DebugLoc DL = N->getDebugLoc();
14017 if (isPowerOf2_64(MulAmt2) &&
14018 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14019 // If second multiplifer is pow2, issue it first. We want the multiply by
14020 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14022 std::swap(MulAmt1, MulAmt2);
14025 if (isPowerOf2_64(MulAmt1))
14026 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14027 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14029 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14030 DAG.getConstant(MulAmt1, VT));
14032 if (isPowerOf2_64(MulAmt2))
14033 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14034 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14036 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14037 DAG.getConstant(MulAmt2, VT));
14039 // Do not add new nodes to DAG combiner worklist.
14040 DCI.CombineTo(N, NewMul, false);
14045 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14046 SDValue N0 = N->getOperand(0);
14047 SDValue N1 = N->getOperand(1);
14048 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14049 EVT VT = N0.getValueType();
14051 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14052 // since the result of setcc_c is all zero's or all ones.
14053 if (VT.isInteger() && !VT.isVector() &&
14054 N1C && N0.getOpcode() == ISD::AND &&
14055 N0.getOperand(1).getOpcode() == ISD::Constant) {
14056 SDValue N00 = N0.getOperand(0);
14057 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14058 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14059 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14060 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14061 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14062 APInt ShAmt = N1C->getAPIntValue();
14063 Mask = Mask.shl(ShAmt);
14065 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14066 N00, DAG.getConstant(Mask, VT));
14071 // Hardware support for vector shifts is sparse which makes us scalarize the
14072 // vector operations in many cases. Also, on sandybridge ADD is faster than
14074 // (shl V, 1) -> add V,V
14075 if (isSplatVector(N1.getNode())) {
14076 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14077 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14078 // We shift all of the values by one. In many cases we do not have
14079 // hardware support for this operation. This is better expressed as an ADD
14081 if (N1C && (1 == N1C->getZExtValue())) {
14082 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14089 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14091 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14092 TargetLowering::DAGCombinerInfo &DCI,
14093 const X86Subtarget *Subtarget) {
14094 EVT VT = N->getValueType(0);
14095 if (N->getOpcode() == ISD::SHL) {
14096 SDValue V = PerformSHLCombine(N, DAG);
14097 if (V.getNode()) return V;
14100 // On X86 with SSE2 support, we can transform this to a vector shift if
14101 // all elements are shifted by the same amount. We can't do this in legalize
14102 // because the a constant vector is typically transformed to a constant pool
14103 // so we have no knowledge of the shift amount.
14104 if (!Subtarget->hasSSE2())
14107 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14108 (!Subtarget->hasAVX2() ||
14109 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14112 SDValue ShAmtOp = N->getOperand(1);
14113 EVT EltVT = VT.getVectorElementType();
14114 DebugLoc DL = N->getDebugLoc();
14115 SDValue BaseShAmt = SDValue();
14116 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14117 unsigned NumElts = VT.getVectorNumElements();
14119 for (; i != NumElts; ++i) {
14120 SDValue Arg = ShAmtOp.getOperand(i);
14121 if (Arg.getOpcode() == ISD::UNDEF) continue;
14125 // Handle the case where the build_vector is all undef
14126 // FIXME: Should DAG allow this?
14130 for (; i != NumElts; ++i) {
14131 SDValue Arg = ShAmtOp.getOperand(i);
14132 if (Arg.getOpcode() == ISD::UNDEF) continue;
14133 if (Arg != BaseShAmt) {
14137 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14138 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14139 SDValue InVec = ShAmtOp.getOperand(0);
14140 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14141 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14143 for (; i != NumElts; ++i) {
14144 SDValue Arg = InVec.getOperand(i);
14145 if (Arg.getOpcode() == ISD::UNDEF) continue;
14149 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14150 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14151 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14152 if (C->getZExtValue() == SplatIdx)
14153 BaseShAmt = InVec.getOperand(1);
14156 if (BaseShAmt.getNode() == 0) {
14157 // Don't create instructions with illegal types after legalize
14159 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14160 !DCI.isBeforeLegalize())
14163 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14164 DAG.getIntPtrConstant(0));
14169 // The shift amount is an i32.
14170 if (EltVT.bitsGT(MVT::i32))
14171 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14172 else if (EltVT.bitsLT(MVT::i32))
14173 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14175 // The shift amount is identical so we can do a vector shift.
14176 SDValue ValOp = N->getOperand(0);
14177 switch (N->getOpcode()) {
14179 llvm_unreachable("Unknown shift opcode!");
14181 switch (VT.getSimpleVT().SimpleTy) {
14182 default: return SDValue();
14189 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14192 switch (VT.getSimpleVT().SimpleTy) {
14193 default: return SDValue();
14198 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14201 switch (VT.getSimpleVT().SimpleTy) {
14202 default: return SDValue();
14209 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14215 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14216 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14217 // and friends. Likewise for OR -> CMPNEQSS.
14218 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14219 TargetLowering::DAGCombinerInfo &DCI,
14220 const X86Subtarget *Subtarget) {
14223 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14224 // we're requiring SSE2 for both.
14225 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14226 SDValue N0 = N->getOperand(0);
14227 SDValue N1 = N->getOperand(1);
14228 SDValue CMP0 = N0->getOperand(1);
14229 SDValue CMP1 = N1->getOperand(1);
14230 DebugLoc DL = N->getDebugLoc();
14232 // The SETCCs should both refer to the same CMP.
14233 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14236 SDValue CMP00 = CMP0->getOperand(0);
14237 SDValue CMP01 = CMP0->getOperand(1);
14238 EVT VT = CMP00.getValueType();
14240 if (VT == MVT::f32 || VT == MVT::f64) {
14241 bool ExpectingFlags = false;
14242 // Check for any users that want flags:
14243 for (SDNode::use_iterator UI = N->use_begin(),
14245 !ExpectingFlags && UI != UE; ++UI)
14246 switch (UI->getOpcode()) {
14251 ExpectingFlags = true;
14253 case ISD::CopyToReg:
14254 case ISD::SIGN_EXTEND:
14255 case ISD::ZERO_EXTEND:
14256 case ISD::ANY_EXTEND:
14260 if (!ExpectingFlags) {
14261 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14262 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14264 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14265 X86::CondCode tmp = cc0;
14270 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14271 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14272 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14273 X86ISD::NodeType NTOperator = is64BitFP ?
14274 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14275 // FIXME: need symbolic constants for these magic numbers.
14276 // See X86ATTInstPrinter.cpp:printSSECC().
14277 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14278 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14279 DAG.getConstant(x86cc, MVT::i8));
14280 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14282 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14283 DAG.getConstant(1, MVT::i32));
14284 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14285 return OneBitOfTruth;
14293 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14294 /// so it can be folded inside ANDNP.
14295 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14296 EVT VT = N->getValueType(0);
14298 // Match direct AllOnes for 128 and 256-bit vectors
14299 if (ISD::isBuildVectorAllOnes(N))
14302 // Look through a bit convert.
14303 if (N->getOpcode() == ISD::BITCAST)
14304 N = N->getOperand(0).getNode();
14306 // Sometimes the operand may come from a insert_subvector building a 256-bit
14308 if (VT.getSizeInBits() == 256 &&
14309 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14310 SDValue V1 = N->getOperand(0);
14311 SDValue V2 = N->getOperand(1);
14313 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14314 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14315 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14316 ISD::isBuildVectorAllOnes(V2.getNode()))
14323 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14324 TargetLowering::DAGCombinerInfo &DCI,
14325 const X86Subtarget *Subtarget) {
14326 if (DCI.isBeforeLegalizeOps())
14329 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14333 EVT VT = N->getValueType(0);
14335 // Create ANDN, BLSI, and BLSR instructions
14336 // BLSI is X & (-X)
14337 // BLSR is X & (X-1)
14338 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14339 SDValue N0 = N->getOperand(0);
14340 SDValue N1 = N->getOperand(1);
14341 DebugLoc DL = N->getDebugLoc();
14343 // Check LHS for not
14344 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14345 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14346 // Check RHS for not
14347 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14348 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14350 // Check LHS for neg
14351 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14352 isZero(N0.getOperand(0)))
14353 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14355 // Check RHS for neg
14356 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14357 isZero(N1.getOperand(0)))
14358 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14360 // Check LHS for X-1
14361 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14362 isAllOnes(N0.getOperand(1)))
14363 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14365 // Check RHS for X-1
14366 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14367 isAllOnes(N1.getOperand(1)))
14368 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14373 // Want to form ANDNP nodes:
14374 // 1) In the hopes of then easily combining them with OR and AND nodes
14375 // to form PBLEND/PSIGN.
14376 // 2) To match ANDN packed intrinsics
14377 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14380 SDValue N0 = N->getOperand(0);
14381 SDValue N1 = N->getOperand(1);
14382 DebugLoc DL = N->getDebugLoc();
14384 // Check LHS for vnot
14385 if (N0.getOpcode() == ISD::XOR &&
14386 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14387 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14388 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14390 // Check RHS for vnot
14391 if (N1.getOpcode() == ISD::XOR &&
14392 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14393 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14394 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14399 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14400 TargetLowering::DAGCombinerInfo &DCI,
14401 const X86Subtarget *Subtarget) {
14402 if (DCI.isBeforeLegalizeOps())
14405 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14409 EVT VT = N->getValueType(0);
14411 SDValue N0 = N->getOperand(0);
14412 SDValue N1 = N->getOperand(1);
14414 // look for psign/blend
14415 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14416 if (!Subtarget->hasSSSE3() ||
14417 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14420 // Canonicalize pandn to RHS
14421 if (N0.getOpcode() == X86ISD::ANDNP)
14423 // or (and (m, y), (pandn m, x))
14424 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14425 SDValue Mask = N1.getOperand(0);
14426 SDValue X = N1.getOperand(1);
14428 if (N0.getOperand(0) == Mask)
14429 Y = N0.getOperand(1);
14430 if (N0.getOperand(1) == Mask)
14431 Y = N0.getOperand(0);
14433 // Check to see if the mask appeared in both the AND and ANDNP and
14437 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14438 // Look through mask bitcast.
14439 if (Mask.getOpcode() == ISD::BITCAST)
14440 Mask = Mask.getOperand(0);
14441 if (X.getOpcode() == ISD::BITCAST)
14442 X = X.getOperand(0);
14443 if (Y.getOpcode() == ISD::BITCAST)
14444 Y = Y.getOperand(0);
14446 EVT MaskVT = Mask.getValueType();
14448 // Validate that the Mask operand is a vector sra node.
14449 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14450 // there is no psrai.b
14451 if (Mask.getOpcode() != X86ISD::VSRAI)
14454 // Check that the SRA is all signbits.
14455 SDValue SraC = Mask.getOperand(1);
14456 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14457 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14458 if ((SraAmt + 1) != EltBits)
14461 DebugLoc DL = N->getDebugLoc();
14463 // Now we know we at least have a plendvb with the mask val. See if
14464 // we can form a psignb/w/d.
14465 // psign = x.type == y.type == mask.type && y = sub(0, x);
14466 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14467 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14468 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14469 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14470 "Unsupported VT for PSIGN");
14471 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14472 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14474 // PBLENDVB only available on SSE 4.1
14475 if (!Subtarget->hasSSE41())
14478 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14480 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14481 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14482 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14483 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14484 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14488 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14491 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14492 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14494 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14496 if (!N0.hasOneUse() || !N1.hasOneUse())
14499 SDValue ShAmt0 = N0.getOperand(1);
14500 if (ShAmt0.getValueType() != MVT::i8)
14502 SDValue ShAmt1 = N1.getOperand(1);
14503 if (ShAmt1.getValueType() != MVT::i8)
14505 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14506 ShAmt0 = ShAmt0.getOperand(0);
14507 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14508 ShAmt1 = ShAmt1.getOperand(0);
14510 DebugLoc DL = N->getDebugLoc();
14511 unsigned Opc = X86ISD::SHLD;
14512 SDValue Op0 = N0.getOperand(0);
14513 SDValue Op1 = N1.getOperand(0);
14514 if (ShAmt0.getOpcode() == ISD::SUB) {
14515 Opc = X86ISD::SHRD;
14516 std::swap(Op0, Op1);
14517 std::swap(ShAmt0, ShAmt1);
14520 unsigned Bits = VT.getSizeInBits();
14521 if (ShAmt1.getOpcode() == ISD::SUB) {
14522 SDValue Sum = ShAmt1.getOperand(0);
14523 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14524 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14525 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14526 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14527 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14528 return DAG.getNode(Opc, DL, VT,
14530 DAG.getNode(ISD::TRUNCATE, DL,
14533 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14534 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14536 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14537 return DAG.getNode(Opc, DL, VT,
14538 N0.getOperand(0), N1.getOperand(0),
14539 DAG.getNode(ISD::TRUNCATE, DL,
14546 // Generate NEG and CMOV for integer abs.
14547 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14548 EVT VT = N->getValueType(0);
14550 // Since X86 does not have CMOV for 8-bit integer, we don't convert
14551 // 8-bit integer abs to NEG and CMOV.
14552 if (VT.isInteger() && VT.getSizeInBits() == 8)
14555 SDValue N0 = N->getOperand(0);
14556 SDValue N1 = N->getOperand(1);
14557 DebugLoc DL = N->getDebugLoc();
14559 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14560 // and change it to SUB and CMOV.
14561 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14562 N0.getOpcode() == ISD::ADD &&
14563 N0.getOperand(1) == N1 &&
14564 N1.getOpcode() == ISD::SRA &&
14565 N1.getOperand(0) == N0.getOperand(0))
14566 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14567 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14568 // Generate SUB & CMOV.
14569 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14570 DAG.getConstant(0, VT), N0.getOperand(0));
14572 SDValue Ops[] = { N0.getOperand(0), Neg,
14573 DAG.getConstant(X86::COND_GE, MVT::i8),
14574 SDValue(Neg.getNode(), 1) };
14575 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14576 Ops, array_lengthof(Ops));
14581 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14582 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14583 TargetLowering::DAGCombinerInfo &DCI,
14584 const X86Subtarget *Subtarget) {
14585 if (DCI.isBeforeLegalizeOps())
14588 if (Subtarget->hasCMov()) {
14589 SDValue RV = performIntegerAbsCombine(N, DAG);
14594 // Try forming BMI if it is available.
14595 if (!Subtarget->hasBMI())
14598 EVT VT = N->getValueType(0);
14600 if (VT != MVT::i32 && VT != MVT::i64)
14603 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14605 // Create BLSMSK instructions by finding X ^ (X-1)
14606 SDValue N0 = N->getOperand(0);
14607 SDValue N1 = N->getOperand(1);
14608 DebugLoc DL = N->getDebugLoc();
14610 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14611 isAllOnes(N0.getOperand(1)))
14612 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14614 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14615 isAllOnes(N1.getOperand(1)))
14616 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14621 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14622 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14623 TargetLowering::DAGCombinerInfo &DCI,
14624 const X86Subtarget *Subtarget) {
14625 LoadSDNode *Ld = cast<LoadSDNode>(N);
14626 EVT RegVT = Ld->getValueType(0);
14627 EVT MemVT = Ld->getMemoryVT();
14628 DebugLoc dl = Ld->getDebugLoc();
14629 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14631 ISD::LoadExtType Ext = Ld->getExtensionType();
14633 // If this is a vector EXT Load then attempt to optimize it using a
14634 // shuffle. We need SSE4 for the shuffles.
14635 // TODO: It is possible to support ZExt by zeroing the undef values
14636 // during the shuffle phase or after the shuffle.
14637 if (RegVT.isVector() && RegVT.isInteger() &&
14638 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14639 assert(MemVT != RegVT && "Cannot extend to the same type");
14640 assert(MemVT.isVector() && "Must load a vector from memory");
14642 unsigned NumElems = RegVT.getVectorNumElements();
14643 unsigned RegSz = RegVT.getSizeInBits();
14644 unsigned MemSz = MemVT.getSizeInBits();
14645 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14647 // All sizes must be a power of two.
14648 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14651 // Attempt to load the original value using scalar loads.
14652 // Find the largest scalar type that divides the total loaded size.
14653 MVT SclrLoadTy = MVT::i8;
14654 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14655 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14656 MVT Tp = (MVT::SimpleValueType)tp;
14657 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14662 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14663 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14665 SclrLoadTy = MVT::f64;
14667 // Calculate the number of scalar loads that we need to perform
14668 // in order to load our vector from memory.
14669 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14671 // Represent our vector as a sequence of elements which are the
14672 // largest scalar that we can load.
14673 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14674 RegSz/SclrLoadTy.getSizeInBits());
14676 // Represent the data using the same element type that is stored in
14677 // memory. In practice, we ''widen'' MemVT.
14678 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14679 RegSz/MemVT.getScalarType().getSizeInBits());
14681 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14682 "Invalid vector type");
14684 // We can't shuffle using an illegal type.
14685 if (!TLI.isTypeLegal(WideVecVT))
14688 SmallVector<SDValue, 8> Chains;
14689 SDValue Ptr = Ld->getBasePtr();
14690 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14691 TLI.getPointerTy());
14692 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14694 for (unsigned i = 0; i < NumLoads; ++i) {
14695 // Perform a single load.
14696 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14697 Ptr, Ld->getPointerInfo(),
14698 Ld->isVolatile(), Ld->isNonTemporal(),
14699 Ld->isInvariant(), Ld->getAlignment());
14700 Chains.push_back(ScalarLoad.getValue(1));
14701 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14702 // another round of DAGCombining.
14704 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14706 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14707 ScalarLoad, DAG.getIntPtrConstant(i));
14709 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14712 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14715 // Bitcast the loaded value to a vector of the original element type, in
14716 // the size of the target vector type.
14717 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14718 unsigned SizeRatio = RegSz/MemSz;
14720 // Redistribute the loaded elements into the different locations.
14721 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14722 for (unsigned i = 0; i != NumElems; ++i)
14723 ShuffleVec[i*SizeRatio] = i;
14725 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14726 DAG.getUNDEF(WideVecVT),
14729 // Bitcast to the requested type.
14730 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14731 // Replace the original load with the new sequence
14732 // and return the new chain.
14733 return DCI.CombineTo(N, Shuff, TF, true);
14739 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14740 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14741 const X86Subtarget *Subtarget) {
14742 StoreSDNode *St = cast<StoreSDNode>(N);
14743 EVT VT = St->getValue().getValueType();
14744 EVT StVT = St->getMemoryVT();
14745 DebugLoc dl = St->getDebugLoc();
14746 SDValue StoredVal = St->getOperand(1);
14747 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14749 // If we are saving a concatenation of two XMM registers, perform two stores.
14750 // On Sandy Bridge, 256-bit memory operations are executed by two
14751 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14752 // memory operation.
14753 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14754 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14755 StoredVal.getNumOperands() == 2) {
14756 SDValue Value0 = StoredVal.getOperand(0);
14757 SDValue Value1 = StoredVal.getOperand(1);
14759 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14760 SDValue Ptr0 = St->getBasePtr();
14761 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14763 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14764 St->getPointerInfo(), St->isVolatile(),
14765 St->isNonTemporal(), St->getAlignment());
14766 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14767 St->getPointerInfo(), St->isVolatile(),
14768 St->isNonTemporal(), St->getAlignment());
14769 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14772 // Optimize trunc store (of multiple scalars) to shuffle and store.
14773 // First, pack all of the elements in one place. Next, store to memory
14774 // in fewer chunks.
14775 if (St->isTruncatingStore() && VT.isVector()) {
14776 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14777 unsigned NumElems = VT.getVectorNumElements();
14778 assert(StVT != VT && "Cannot truncate to the same type");
14779 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14780 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14782 // From, To sizes and ElemCount must be pow of two
14783 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14784 // We are going to use the original vector elt for storing.
14785 // Accumulated smaller vector elements must be a multiple of the store size.
14786 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14788 unsigned SizeRatio = FromSz / ToSz;
14790 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14792 // Create a type on which we perform the shuffle
14793 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14794 StVT.getScalarType(), NumElems*SizeRatio);
14796 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14798 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14799 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14800 for (unsigned i = 0; i != NumElems; ++i)
14801 ShuffleVec[i] = i * SizeRatio;
14803 // Can't shuffle using an illegal type.
14804 if (!TLI.isTypeLegal(WideVecVT))
14807 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14808 DAG.getUNDEF(WideVecVT),
14810 // At this point all of the data is stored at the bottom of the
14811 // register. We now need to save it to mem.
14813 // Find the largest store unit
14814 MVT StoreType = MVT::i8;
14815 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14816 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14817 MVT Tp = (MVT::SimpleValueType)tp;
14818 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14822 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14823 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14824 (64 <= NumElems * ToSz))
14825 StoreType = MVT::f64;
14827 // Bitcast the original vector into a vector of store-size units
14828 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14829 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14830 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14831 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14832 SmallVector<SDValue, 8> Chains;
14833 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14834 TLI.getPointerTy());
14835 SDValue Ptr = St->getBasePtr();
14837 // Perform one or more big stores into memory.
14838 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14839 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14840 StoreType, ShuffWide,
14841 DAG.getIntPtrConstant(i));
14842 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14843 St->getPointerInfo(), St->isVolatile(),
14844 St->isNonTemporal(), St->getAlignment());
14845 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14846 Chains.push_back(Ch);
14849 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14854 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14855 // the FP state in cases where an emms may be missing.
14856 // A preferable solution to the general problem is to figure out the right
14857 // places to insert EMMS. This qualifies as a quick hack.
14859 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14860 if (VT.getSizeInBits() != 64)
14863 const Function *F = DAG.getMachineFunction().getFunction();
14864 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14865 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14866 && Subtarget->hasSSE2();
14867 if ((VT.isVector() ||
14868 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14869 isa<LoadSDNode>(St->getValue()) &&
14870 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14871 St->getChain().hasOneUse() && !St->isVolatile()) {
14872 SDNode* LdVal = St->getValue().getNode();
14873 LoadSDNode *Ld = 0;
14874 int TokenFactorIndex = -1;
14875 SmallVector<SDValue, 8> Ops;
14876 SDNode* ChainVal = St->getChain().getNode();
14877 // Must be a store of a load. We currently handle two cases: the load
14878 // is a direct child, and it's under an intervening TokenFactor. It is
14879 // possible to dig deeper under nested TokenFactors.
14880 if (ChainVal == LdVal)
14881 Ld = cast<LoadSDNode>(St->getChain());
14882 else if (St->getValue().hasOneUse() &&
14883 ChainVal->getOpcode() == ISD::TokenFactor) {
14884 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14885 if (ChainVal->getOperand(i).getNode() == LdVal) {
14886 TokenFactorIndex = i;
14887 Ld = cast<LoadSDNode>(St->getValue());
14889 Ops.push_back(ChainVal->getOperand(i));
14893 if (!Ld || !ISD::isNormalLoad(Ld))
14896 // If this is not the MMX case, i.e. we are just turning i64 load/store
14897 // into f64 load/store, avoid the transformation if there are multiple
14898 // uses of the loaded value.
14899 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14902 DebugLoc LdDL = Ld->getDebugLoc();
14903 DebugLoc StDL = N->getDebugLoc();
14904 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14905 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14907 if (Subtarget->is64Bit() || F64IsLegal) {
14908 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14909 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14910 Ld->getPointerInfo(), Ld->isVolatile(),
14911 Ld->isNonTemporal(), Ld->isInvariant(),
14912 Ld->getAlignment());
14913 SDValue NewChain = NewLd.getValue(1);
14914 if (TokenFactorIndex != -1) {
14915 Ops.push_back(NewChain);
14916 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14919 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14920 St->getPointerInfo(),
14921 St->isVolatile(), St->isNonTemporal(),
14922 St->getAlignment());
14925 // Otherwise, lower to two pairs of 32-bit loads / stores.
14926 SDValue LoAddr = Ld->getBasePtr();
14927 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14928 DAG.getConstant(4, MVT::i32));
14930 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14931 Ld->getPointerInfo(),
14932 Ld->isVolatile(), Ld->isNonTemporal(),
14933 Ld->isInvariant(), Ld->getAlignment());
14934 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14935 Ld->getPointerInfo().getWithOffset(4),
14936 Ld->isVolatile(), Ld->isNonTemporal(),
14938 MinAlign(Ld->getAlignment(), 4));
14940 SDValue NewChain = LoLd.getValue(1);
14941 if (TokenFactorIndex != -1) {
14942 Ops.push_back(LoLd);
14943 Ops.push_back(HiLd);
14944 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14948 LoAddr = St->getBasePtr();
14949 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14950 DAG.getConstant(4, MVT::i32));
14952 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14953 St->getPointerInfo(),
14954 St->isVolatile(), St->isNonTemporal(),
14955 St->getAlignment());
14956 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14957 St->getPointerInfo().getWithOffset(4),
14959 St->isNonTemporal(),
14960 MinAlign(St->getAlignment(), 4));
14961 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14966 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14967 /// and return the operands for the horizontal operation in LHS and RHS. A
14968 /// horizontal operation performs the binary operation on successive elements
14969 /// of its first operand, then on successive elements of its second operand,
14970 /// returning the resulting values in a vector. For example, if
14971 /// A = < float a0, float a1, float a2, float a3 >
14973 /// B = < float b0, float b1, float b2, float b3 >
14974 /// then the result of doing a horizontal operation on A and B is
14975 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14976 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14977 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14978 /// set to A, RHS to B, and the routine returns 'true'.
14979 /// Note that the binary operation should have the property that if one of the
14980 /// operands is UNDEF then the result is UNDEF.
14981 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14982 // Look for the following pattern: if
14983 // A = < float a0, float a1, float a2, float a3 >
14984 // B = < float b0, float b1, float b2, float b3 >
14986 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14987 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14988 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14989 // which is A horizontal-op B.
14991 // At least one of the operands should be a vector shuffle.
14992 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14993 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14996 EVT VT = LHS.getValueType();
14998 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14999 "Unsupported vector type for horizontal add/sub");
15001 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15002 // operate independently on 128-bit lanes.
15003 unsigned NumElts = VT.getVectorNumElements();
15004 unsigned NumLanes = VT.getSizeInBits()/128;
15005 unsigned NumLaneElts = NumElts / NumLanes;
15006 assert((NumLaneElts % 2 == 0) &&
15007 "Vector type should have an even number of elements in each lane");
15008 unsigned HalfLaneElts = NumLaneElts/2;
15010 // View LHS in the form
15011 // LHS = VECTOR_SHUFFLE A, B, LMask
15012 // If LHS is not a shuffle then pretend it is the shuffle
15013 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15014 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15017 SmallVector<int, 16> LMask(NumElts);
15018 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15019 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15020 A = LHS.getOperand(0);
15021 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15022 B = LHS.getOperand(1);
15023 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15024 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15026 if (LHS.getOpcode() != ISD::UNDEF)
15028 for (unsigned i = 0; i != NumElts; ++i)
15032 // Likewise, view RHS in the form
15033 // RHS = VECTOR_SHUFFLE C, D, RMask
15035 SmallVector<int, 16> RMask(NumElts);
15036 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15037 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15038 C = RHS.getOperand(0);
15039 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15040 D = RHS.getOperand(1);
15041 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15042 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15044 if (RHS.getOpcode() != ISD::UNDEF)
15046 for (unsigned i = 0; i != NumElts; ++i)
15050 // Check that the shuffles are both shuffling the same vectors.
15051 if (!(A == C && B == D) && !(A == D && B == C))
15054 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15055 if (!A.getNode() && !B.getNode())
15058 // If A and B occur in reverse order in RHS, then "swap" them (which means
15059 // rewriting the mask).
15061 CommuteVectorShuffleMask(RMask, NumElts);
15063 // At this point LHS and RHS are equivalent to
15064 // LHS = VECTOR_SHUFFLE A, B, LMask
15065 // RHS = VECTOR_SHUFFLE A, B, RMask
15066 // Check that the masks correspond to performing a horizontal operation.
15067 for (unsigned i = 0; i != NumElts; ++i) {
15068 int LIdx = LMask[i], RIdx = RMask[i];
15070 // Ignore any UNDEF components.
15071 if (LIdx < 0 || RIdx < 0 ||
15072 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15073 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15076 // Check that successive elements are being operated on. If not, this is
15077 // not a horizontal operation.
15078 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15079 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15080 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15081 if (!(LIdx == Index && RIdx == Index + 1) &&
15082 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15086 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15087 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15091 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15092 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15093 const X86Subtarget *Subtarget) {
15094 EVT VT = N->getValueType(0);
15095 SDValue LHS = N->getOperand(0);
15096 SDValue RHS = N->getOperand(1);
15098 // Try to synthesize horizontal adds from adds of shuffles.
15099 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15100 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15101 isHorizontalBinOp(LHS, RHS, true))
15102 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15106 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15107 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15108 const X86Subtarget *Subtarget) {
15109 EVT VT = N->getValueType(0);
15110 SDValue LHS = N->getOperand(0);
15111 SDValue RHS = N->getOperand(1);
15113 // Try to synthesize horizontal subs from subs of shuffles.
15114 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15115 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15116 isHorizontalBinOp(LHS, RHS, false))
15117 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15121 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15122 /// X86ISD::FXOR nodes.
15123 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15124 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15125 // F[X]OR(0.0, x) -> x
15126 // F[X]OR(x, 0.0) -> x
15127 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15128 if (C->getValueAPF().isPosZero())
15129 return N->getOperand(1);
15130 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15131 if (C->getValueAPF().isPosZero())
15132 return N->getOperand(0);
15136 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15137 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15138 // FAND(0.0, x) -> 0.0
15139 // FAND(x, 0.0) -> 0.0
15140 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15141 if (C->getValueAPF().isPosZero())
15142 return N->getOperand(0);
15143 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15144 if (C->getValueAPF().isPosZero())
15145 return N->getOperand(1);
15149 static SDValue PerformBTCombine(SDNode *N,
15151 TargetLowering::DAGCombinerInfo &DCI) {
15152 // BT ignores high bits in the bit index operand.
15153 SDValue Op1 = N->getOperand(1);
15154 if (Op1.hasOneUse()) {
15155 unsigned BitWidth = Op1.getValueSizeInBits();
15156 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15157 APInt KnownZero, KnownOne;
15158 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15159 !DCI.isBeforeLegalizeOps());
15160 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15161 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15162 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15163 DCI.CommitTargetLoweringOpt(TLO);
15168 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15169 SDValue Op = N->getOperand(0);
15170 if (Op.getOpcode() == ISD::BITCAST)
15171 Op = Op.getOperand(0);
15172 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15173 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15174 VT.getVectorElementType().getSizeInBits() ==
15175 OpVT.getVectorElementType().getSizeInBits()) {
15176 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15181 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15182 TargetLowering::DAGCombinerInfo &DCI,
15183 const X86Subtarget *Subtarget) {
15184 if (!DCI.isBeforeLegalizeOps())
15187 if (!Subtarget->hasAVX())
15190 EVT VT = N->getValueType(0);
15191 SDValue Op = N->getOperand(0);
15192 EVT OpVT = Op.getValueType();
15193 DebugLoc dl = N->getDebugLoc();
15195 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15196 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15198 if (Subtarget->hasAVX2())
15199 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15201 // Optimize vectors in AVX mode
15202 // Sign extend v8i16 to v8i32 and
15205 // Divide input vector into two parts
15206 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15207 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15208 // concat the vectors to original VT
15210 unsigned NumElems = OpVT.getVectorNumElements();
15211 SmallVector<int,8> ShufMask1(NumElems, -1);
15212 for (unsigned i = 0; i != NumElems/2; ++i)
15215 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15218 SmallVector<int,8> ShufMask2(NumElems, -1);
15219 for (unsigned i = 0; i != NumElems/2; ++i)
15220 ShufMask2[i] = i + NumElems/2;
15222 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15225 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15226 VT.getVectorNumElements()/2);
15228 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15229 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15231 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15236 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15237 const X86Subtarget* Subtarget) {
15238 DebugLoc dl = N->getDebugLoc();
15239 EVT VT = N->getValueType(0);
15241 EVT ScalarVT = VT.getScalarType();
15242 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasFMA())
15245 SDValue A = N->getOperand(0);
15246 SDValue B = N->getOperand(1);
15247 SDValue C = N->getOperand(2);
15249 bool NegA = (A.getOpcode() == ISD::FNEG);
15250 bool NegB = (B.getOpcode() == ISD::FNEG);
15251 bool NegC = (C.getOpcode() == ISD::FNEG);
15253 // Negative multiplication when NegA xor NegB
15254 bool NegMul = (NegA != NegB);
15256 A = A.getOperand(0);
15258 B = B.getOperand(0);
15260 C = C.getOperand(0);
15264 Opcode = (!NegC)? X86ISD::FMADD : X86ISD::FMSUB;
15266 Opcode = (!NegC)? X86ISD::FNMADD : X86ISD::FNMSUB;
15267 return DAG.getNode(Opcode, dl, VT, A, B, C);
15270 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15271 TargetLowering::DAGCombinerInfo &DCI,
15272 const X86Subtarget *Subtarget) {
15273 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15274 // (and (i32 x86isd::setcc_carry), 1)
15275 // This eliminates the zext. This transformation is necessary because
15276 // ISD::SETCC is always legalized to i8.
15277 DebugLoc dl = N->getDebugLoc();
15278 SDValue N0 = N->getOperand(0);
15279 EVT VT = N->getValueType(0);
15280 EVT OpVT = N0.getValueType();
15282 if (N0.getOpcode() == ISD::AND &&
15284 N0.getOperand(0).hasOneUse()) {
15285 SDValue N00 = N0.getOperand(0);
15286 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15288 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15289 if (!C || C->getZExtValue() != 1)
15291 return DAG.getNode(ISD::AND, dl, VT,
15292 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15293 N00.getOperand(0), N00.getOperand(1)),
15294 DAG.getConstant(1, VT));
15297 // Optimize vectors in AVX mode:
15300 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15301 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15302 // Concat upper and lower parts.
15305 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15306 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15307 // Concat upper and lower parts.
15309 if (!DCI.isBeforeLegalizeOps())
15312 if (!Subtarget->hasAVX())
15315 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15316 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15318 if (Subtarget->hasAVX2())
15319 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15321 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15322 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15323 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15325 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15326 VT.getVectorNumElements()/2);
15328 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15329 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15331 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15337 // Optimize x == -y --> x+y == 0
15338 // x != -y --> x+y != 0
15339 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15340 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15341 SDValue LHS = N->getOperand(0);
15342 SDValue RHS = N->getOperand(1);
15344 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15345 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15346 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15347 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15348 LHS.getValueType(), RHS, LHS.getOperand(1));
15349 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15350 addV, DAG.getConstant(0, addV.getValueType()), CC);
15352 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15354 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15355 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15356 RHS.getValueType(), LHS, RHS.getOperand(1));
15357 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15358 addV, DAG.getConstant(0, addV.getValueType()), CC);
15363 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15364 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15365 DebugLoc DL = N->getDebugLoc();
15366 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15367 SDValue EFLAGS = N->getOperand(1);
15369 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15370 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15372 if (CC == X86::COND_B)
15373 return DAG.getNode(ISD::AND, DL, MVT::i8,
15374 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15375 DAG.getConstant(CC, MVT::i8), EFLAGS),
15376 DAG.getConstant(1, MVT::i8));
15380 Flags = BoolTestSetCCCombine(EFLAGS, CC);
15381 if (Flags.getNode()) {
15382 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15383 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15389 // Optimize branch condition evaluation.
15391 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15392 TargetLowering::DAGCombinerInfo &DCI,
15393 const X86Subtarget *Subtarget) {
15394 DebugLoc DL = N->getDebugLoc();
15395 SDValue Chain = N->getOperand(0);
15396 SDValue Dest = N->getOperand(1);
15397 SDValue EFLAGS = N->getOperand(3);
15398 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15402 Flags = BoolTestSetCCCombine(EFLAGS, CC);
15403 if (Flags.getNode()) {
15404 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15405 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15412 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15413 SDValue Op0 = N->getOperand(0);
15414 EVT InVT = Op0->getValueType(0);
15416 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15417 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15418 DebugLoc dl = N->getDebugLoc();
15419 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15420 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15421 // Notice that we use SINT_TO_FP because we know that the high bits
15422 // are zero and SINT_TO_FP is better supported by the hardware.
15423 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15429 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15430 const X86TargetLowering *XTLI) {
15431 SDValue Op0 = N->getOperand(0);
15432 EVT InVT = Op0->getValueType(0);
15434 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15435 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15436 DebugLoc dl = N->getDebugLoc();
15437 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15438 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15439 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15442 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15443 // a 32-bit target where SSE doesn't support i64->FP operations.
15444 if (Op0.getOpcode() == ISD::LOAD) {
15445 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15446 EVT VT = Ld->getValueType(0);
15447 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15448 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15449 !XTLI->getSubtarget()->is64Bit() &&
15450 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15451 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15452 Ld->getChain(), Op0, DAG);
15453 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15460 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15461 EVT VT = N->getValueType(0);
15463 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15464 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15465 DebugLoc dl = N->getDebugLoc();
15466 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15467 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15468 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15474 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15475 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15476 X86TargetLowering::DAGCombinerInfo &DCI) {
15477 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15478 // the result is either zero or one (depending on the input carry bit).
15479 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15480 if (X86::isZeroNode(N->getOperand(0)) &&
15481 X86::isZeroNode(N->getOperand(1)) &&
15482 // We don't have a good way to replace an EFLAGS use, so only do this when
15484 SDValue(N, 1).use_empty()) {
15485 DebugLoc DL = N->getDebugLoc();
15486 EVT VT = N->getValueType(0);
15487 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15488 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15489 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15490 DAG.getConstant(X86::COND_B,MVT::i8),
15492 DAG.getConstant(1, VT));
15493 return DCI.CombineTo(N, Res1, CarryOut);
15499 // fold (add Y, (sete X, 0)) -> adc 0, Y
15500 // (add Y, (setne X, 0)) -> sbb -1, Y
15501 // (sub (sete X, 0), Y) -> sbb 0, Y
15502 // (sub (setne X, 0), Y) -> adc -1, Y
15503 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15504 DebugLoc DL = N->getDebugLoc();
15506 // Look through ZExts.
15507 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15508 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15511 SDValue SetCC = Ext.getOperand(0);
15512 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15515 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15516 if (CC != X86::COND_E && CC != X86::COND_NE)
15519 SDValue Cmp = SetCC.getOperand(1);
15520 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15521 !X86::isZeroNode(Cmp.getOperand(1)) ||
15522 !Cmp.getOperand(0).getValueType().isInteger())
15525 SDValue CmpOp0 = Cmp.getOperand(0);
15526 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15527 DAG.getConstant(1, CmpOp0.getValueType()));
15529 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15530 if (CC == X86::COND_NE)
15531 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15532 DL, OtherVal.getValueType(), OtherVal,
15533 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15534 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15535 DL, OtherVal.getValueType(), OtherVal,
15536 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15539 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15540 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15541 const X86Subtarget *Subtarget) {
15542 EVT VT = N->getValueType(0);
15543 SDValue Op0 = N->getOperand(0);
15544 SDValue Op1 = N->getOperand(1);
15546 // Try to synthesize horizontal adds from adds of shuffles.
15547 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15548 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15549 isHorizontalBinOp(Op0, Op1, true))
15550 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15552 return OptimizeConditionalInDecrement(N, DAG);
15555 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15556 const X86Subtarget *Subtarget) {
15557 SDValue Op0 = N->getOperand(0);
15558 SDValue Op1 = N->getOperand(1);
15560 // X86 can't encode an immediate LHS of a sub. See if we can push the
15561 // negation into a preceding instruction.
15562 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15563 // If the RHS of the sub is a XOR with one use and a constant, invert the
15564 // immediate. Then add one to the LHS of the sub so we can turn
15565 // X-Y -> X+~Y+1, saving one register.
15566 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15567 isa<ConstantSDNode>(Op1.getOperand(1))) {
15568 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15569 EVT VT = Op0.getValueType();
15570 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15572 DAG.getConstant(~XorC, VT));
15573 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15574 DAG.getConstant(C->getAPIntValue()+1, VT));
15578 // Try to synthesize horizontal adds from adds of shuffles.
15579 EVT VT = N->getValueType(0);
15580 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15581 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15582 isHorizontalBinOp(Op0, Op1, true))
15583 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15585 return OptimizeConditionalInDecrement(N, DAG);
15588 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15589 DAGCombinerInfo &DCI) const {
15590 SelectionDAG &DAG = DCI.DAG;
15591 switch (N->getOpcode()) {
15593 case ISD::EXTRACT_VECTOR_ELT:
15594 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15596 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15597 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
15598 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
15599 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
15600 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
15601 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
15604 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
15605 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
15606 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
15607 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
15608 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
15609 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
15610 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
15611 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
15612 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
15613 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
15614 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
15616 case X86ISD::FOR: return PerformFORCombine(N, DAG);
15617 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
15618 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
15619 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
15620 case ISD::ANY_EXTEND:
15621 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
15622 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
15623 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI);
15624 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
15625 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
15626 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
15627 case X86ISD::SHUFP: // Handle all target specific shuffles
15628 case X86ISD::PALIGN:
15629 case X86ISD::UNPCKH:
15630 case X86ISD::UNPCKL:
15631 case X86ISD::MOVHLPS:
15632 case X86ISD::MOVLHPS:
15633 case X86ISD::PSHUFD:
15634 case X86ISD::PSHUFHW:
15635 case X86ISD::PSHUFLW:
15636 case X86ISD::MOVSS:
15637 case X86ISD::MOVSD:
15638 case X86ISD::VPERMILP:
15639 case X86ISD::VPERM2X128:
15640 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15641 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
15647 /// isTypeDesirableForOp - Return true if the target has native support for
15648 /// the specified value type and it is 'desirable' to use the type for the
15649 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15650 /// instruction encodings are longer and some i16 instructions are slow.
15651 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15652 if (!isTypeLegal(VT))
15654 if (VT != MVT::i16)
15661 case ISD::SIGN_EXTEND:
15662 case ISD::ZERO_EXTEND:
15663 case ISD::ANY_EXTEND:
15676 /// IsDesirableToPromoteOp - This method query the target whether it is
15677 /// beneficial for dag combiner to promote the specified node. If true, it
15678 /// should return the desired promotion type by reference.
15679 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15680 EVT VT = Op.getValueType();
15681 if (VT != MVT::i16)
15684 bool Promote = false;
15685 bool Commute = false;
15686 switch (Op.getOpcode()) {
15689 LoadSDNode *LD = cast<LoadSDNode>(Op);
15690 // If the non-extending load has a single use and it's not live out, then it
15691 // might be folded.
15692 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15693 Op.hasOneUse()*/) {
15694 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15695 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15696 // The only case where we'd want to promote LOAD (rather then it being
15697 // promoted as an operand is when it's only use is liveout.
15698 if (UI->getOpcode() != ISD::CopyToReg)
15705 case ISD::SIGN_EXTEND:
15706 case ISD::ZERO_EXTEND:
15707 case ISD::ANY_EXTEND:
15712 SDValue N0 = Op.getOperand(0);
15713 // Look out for (store (shl (load), x)).
15714 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15727 SDValue N0 = Op.getOperand(0);
15728 SDValue N1 = Op.getOperand(1);
15729 if (!Commute && MayFoldLoad(N1))
15731 // Avoid disabling potential load folding opportunities.
15732 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15734 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15744 //===----------------------------------------------------------------------===//
15745 // X86 Inline Assembly Support
15746 //===----------------------------------------------------------------------===//
15749 // Helper to match a string separated by whitespace.
15750 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15751 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15753 for (unsigned i = 0, e = args.size(); i != e; ++i) {
15754 StringRef piece(*args[i]);
15755 if (!s.startswith(piece)) // Check if the piece matches.
15758 s = s.substr(piece.size());
15759 StringRef::size_type pos = s.find_first_not_of(" \t");
15760 if (pos == 0) // We matched a prefix.
15768 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15771 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15772 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15774 std::string AsmStr = IA->getAsmString();
15776 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15777 if (!Ty || Ty->getBitWidth() % 16 != 0)
15780 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15781 SmallVector<StringRef, 4> AsmPieces;
15782 SplitString(AsmStr, AsmPieces, ";\n");
15784 switch (AsmPieces.size()) {
15785 default: return false;
15787 // FIXME: this should verify that we are targeting a 486 or better. If not,
15788 // we will turn this bswap into something that will be lowered to logical
15789 // ops instead of emitting the bswap asm. For now, we don't support 486 or
15790 // lower so don't worry about this.
15792 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15793 matchAsm(AsmPieces[0], "bswapl", "$0") ||
15794 matchAsm(AsmPieces[0], "bswapq", "$0") ||
15795 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15796 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15797 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15798 // No need to check constraints, nothing other than the equivalent of
15799 // "=r,0" would be valid here.
15800 return IntrinsicLowering::LowerToByteSwap(CI);
15803 // rorw $$8, ${0:w} --> llvm.bswap.i16
15804 if (CI->getType()->isIntegerTy(16) &&
15805 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15806 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15807 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15809 const std::string &ConstraintsStr = IA->getConstraintString();
15810 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15811 std::sort(AsmPieces.begin(), AsmPieces.end());
15812 if (AsmPieces.size() == 4 &&
15813 AsmPieces[0] == "~{cc}" &&
15814 AsmPieces[1] == "~{dirflag}" &&
15815 AsmPieces[2] == "~{flags}" &&
15816 AsmPieces[3] == "~{fpsr}")
15817 return IntrinsicLowering::LowerToByteSwap(CI);
15821 if (CI->getType()->isIntegerTy(32) &&
15822 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15823 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15824 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15825 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15827 const std::string &ConstraintsStr = IA->getConstraintString();
15828 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15829 std::sort(AsmPieces.begin(), AsmPieces.end());
15830 if (AsmPieces.size() == 4 &&
15831 AsmPieces[0] == "~{cc}" &&
15832 AsmPieces[1] == "~{dirflag}" &&
15833 AsmPieces[2] == "~{flags}" &&
15834 AsmPieces[3] == "~{fpsr}")
15835 return IntrinsicLowering::LowerToByteSwap(CI);
15838 if (CI->getType()->isIntegerTy(64)) {
15839 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15840 if (Constraints.size() >= 2 &&
15841 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15842 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15843 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
15844 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15845 matchAsm(AsmPieces[1], "bswap", "%edx") &&
15846 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15847 return IntrinsicLowering::LowerToByteSwap(CI);
15857 /// getConstraintType - Given a constraint letter, return the type of
15858 /// constraint it is for this target.
15859 X86TargetLowering::ConstraintType
15860 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15861 if (Constraint.size() == 1) {
15862 switch (Constraint[0]) {
15873 return C_RegisterClass;
15897 return TargetLowering::getConstraintType(Constraint);
15900 /// Examine constraint type and operand type and determine a weight value.
15901 /// This object must already have been set up with the operand type
15902 /// and the current alternative constraint selected.
15903 TargetLowering::ConstraintWeight
15904 X86TargetLowering::getSingleConstraintMatchWeight(
15905 AsmOperandInfo &info, const char *constraint) const {
15906 ConstraintWeight weight = CW_Invalid;
15907 Value *CallOperandVal = info.CallOperandVal;
15908 // If we don't have a value, we can't do a match,
15909 // but allow it at the lowest weight.
15910 if (CallOperandVal == NULL)
15912 Type *type = CallOperandVal->getType();
15913 // Look at the constraint type.
15914 switch (*constraint) {
15916 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15927 if (CallOperandVal->getType()->isIntegerTy())
15928 weight = CW_SpecificReg;
15933 if (type->isFloatingPointTy())
15934 weight = CW_SpecificReg;
15937 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15938 weight = CW_SpecificReg;
15942 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15943 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15944 weight = CW_Register;
15947 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15948 if (C->getZExtValue() <= 31)
15949 weight = CW_Constant;
15953 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15954 if (C->getZExtValue() <= 63)
15955 weight = CW_Constant;
15959 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15960 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15961 weight = CW_Constant;
15965 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15966 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15967 weight = CW_Constant;
15971 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15972 if (C->getZExtValue() <= 3)
15973 weight = CW_Constant;
15977 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15978 if (C->getZExtValue() <= 0xff)
15979 weight = CW_Constant;
15984 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15985 weight = CW_Constant;
15989 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15990 if ((C->getSExtValue() >= -0x80000000LL) &&
15991 (C->getSExtValue() <= 0x7fffffffLL))
15992 weight = CW_Constant;
15996 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15997 if (C->getZExtValue() <= 0xffffffff)
15998 weight = CW_Constant;
16005 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16006 /// with another that has more specific requirements based on the type of the
16007 /// corresponding operand.
16008 const char *X86TargetLowering::
16009 LowerXConstraint(EVT ConstraintVT) const {
16010 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16011 // 'f' like normal targets.
16012 if (ConstraintVT.isFloatingPoint()) {
16013 if (Subtarget->hasSSE2())
16015 if (Subtarget->hasSSE1())
16019 return TargetLowering::LowerXConstraint(ConstraintVT);
16022 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16023 /// vector. If it is invalid, don't add anything to Ops.
16024 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16025 std::string &Constraint,
16026 std::vector<SDValue>&Ops,
16027 SelectionDAG &DAG) const {
16028 SDValue Result(0, 0);
16030 // Only support length 1 constraints for now.
16031 if (Constraint.length() > 1) return;
16033 char ConstraintLetter = Constraint[0];
16034 switch (ConstraintLetter) {
16037 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16038 if (C->getZExtValue() <= 31) {
16039 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16045 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16046 if (C->getZExtValue() <= 63) {
16047 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16054 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16055 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16061 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16062 if (C->getZExtValue() <= 255) {
16063 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16069 // 32-bit signed value
16070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16071 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16072 C->getSExtValue())) {
16073 // Widen to 64 bits here to get it sign extended.
16074 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16077 // FIXME gcc accepts some relocatable values here too, but only in certain
16078 // memory models; it's complicated.
16083 // 32-bit unsigned value
16084 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16085 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16086 C->getZExtValue())) {
16087 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16091 // FIXME gcc accepts some relocatable values here too, but only in certain
16092 // memory models; it's complicated.
16096 // Literal immediates are always ok.
16097 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16098 // Widen to 64 bits here to get it sign extended.
16099 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16103 // In any sort of PIC mode addresses need to be computed at runtime by
16104 // adding in a register or some sort of table lookup. These can't
16105 // be used as immediates.
16106 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16109 // If we are in non-pic codegen mode, we allow the address of a global (with
16110 // an optional displacement) to be used with 'i'.
16111 GlobalAddressSDNode *GA = 0;
16112 int64_t Offset = 0;
16114 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16116 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16117 Offset += GA->getOffset();
16119 } else if (Op.getOpcode() == ISD::ADD) {
16120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16121 Offset += C->getZExtValue();
16122 Op = Op.getOperand(0);
16125 } else if (Op.getOpcode() == ISD::SUB) {
16126 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16127 Offset += -C->getZExtValue();
16128 Op = Op.getOperand(0);
16133 // Otherwise, this isn't something we can handle, reject it.
16137 const GlobalValue *GV = GA->getGlobal();
16138 // If we require an extra load to get this address, as in PIC mode, we
16139 // can't accept it.
16140 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16141 getTargetMachine())))
16144 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16145 GA->getValueType(0), Offset);
16150 if (Result.getNode()) {
16151 Ops.push_back(Result);
16154 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16157 std::pair<unsigned, const TargetRegisterClass*>
16158 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16160 // First, see if this is a constraint that directly corresponds to an LLVM
16162 if (Constraint.size() == 1) {
16163 // GCC Constraint Letters
16164 switch (Constraint[0]) {
16166 // TODO: Slight differences here in allocation order and leaving
16167 // RIP in the class. Do they matter any more here than they do
16168 // in the normal allocation?
16169 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16170 if (Subtarget->is64Bit()) {
16171 if (VT == MVT::i32 || VT == MVT::f32)
16172 return std::make_pair(0U, &X86::GR32RegClass);
16173 if (VT == MVT::i16)
16174 return std::make_pair(0U, &X86::GR16RegClass);
16175 if (VT == MVT::i8 || VT == MVT::i1)
16176 return std::make_pair(0U, &X86::GR8RegClass);
16177 if (VT == MVT::i64 || VT == MVT::f64)
16178 return std::make_pair(0U, &X86::GR64RegClass);
16181 // 32-bit fallthrough
16182 case 'Q': // Q_REGS
16183 if (VT == MVT::i32 || VT == MVT::f32)
16184 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16185 if (VT == MVT::i16)
16186 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16187 if (VT == MVT::i8 || VT == MVT::i1)
16188 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16189 if (VT == MVT::i64)
16190 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16192 case 'r': // GENERAL_REGS
16193 case 'l': // INDEX_REGS
16194 if (VT == MVT::i8 || VT == MVT::i1)
16195 return std::make_pair(0U, &X86::GR8RegClass);
16196 if (VT == MVT::i16)
16197 return std::make_pair(0U, &X86::GR16RegClass);
16198 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16199 return std::make_pair(0U, &X86::GR32RegClass);
16200 return std::make_pair(0U, &X86::GR64RegClass);
16201 case 'R': // LEGACY_REGS
16202 if (VT == MVT::i8 || VT == MVT::i1)
16203 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16204 if (VT == MVT::i16)
16205 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16206 if (VT == MVT::i32 || !Subtarget->is64Bit())
16207 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16208 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16209 case 'f': // FP Stack registers.
16210 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16211 // value to the correct fpstack register class.
16212 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16213 return std::make_pair(0U, &X86::RFP32RegClass);
16214 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16215 return std::make_pair(0U, &X86::RFP64RegClass);
16216 return std::make_pair(0U, &X86::RFP80RegClass);
16217 case 'y': // MMX_REGS if MMX allowed.
16218 if (!Subtarget->hasMMX()) break;
16219 return std::make_pair(0U, &X86::VR64RegClass);
16220 case 'Y': // SSE_REGS if SSE2 allowed
16221 if (!Subtarget->hasSSE2()) break;
16223 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16224 if (!Subtarget->hasSSE1()) break;
16226 switch (VT.getSimpleVT().SimpleTy) {
16228 // Scalar SSE types.
16231 return std::make_pair(0U, &X86::FR32RegClass);
16234 return std::make_pair(0U, &X86::FR64RegClass);
16242 return std::make_pair(0U, &X86::VR128RegClass);
16250 return std::make_pair(0U, &X86::VR256RegClass);
16256 // Use the default implementation in TargetLowering to convert the register
16257 // constraint into a member of a register class.
16258 std::pair<unsigned, const TargetRegisterClass*> Res;
16259 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16261 // Not found as a standard register?
16262 if (Res.second == 0) {
16263 // Map st(0) -> st(7) -> ST0
16264 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16265 tolower(Constraint[1]) == 's' &&
16266 tolower(Constraint[2]) == 't' &&
16267 Constraint[3] == '(' &&
16268 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16269 Constraint[5] == ')' &&
16270 Constraint[6] == '}') {
16272 Res.first = X86::ST0+Constraint[4]-'0';
16273 Res.second = &X86::RFP80RegClass;
16277 // GCC allows "st(0)" to be called just plain "st".
16278 if (StringRef("{st}").equals_lower(Constraint)) {
16279 Res.first = X86::ST0;
16280 Res.second = &X86::RFP80RegClass;
16285 if (StringRef("{flags}").equals_lower(Constraint)) {
16286 Res.first = X86::EFLAGS;
16287 Res.second = &X86::CCRRegClass;
16291 // 'A' means EAX + EDX.
16292 if (Constraint == "A") {
16293 Res.first = X86::EAX;
16294 Res.second = &X86::GR32_ADRegClass;
16300 // Otherwise, check to see if this is a register class of the wrong value
16301 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16302 // turn into {ax},{dx}.
16303 if (Res.second->hasType(VT))
16304 return Res; // Correct type already, nothing to do.
16306 // All of the single-register GCC register classes map their values onto
16307 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16308 // really want an 8-bit or 32-bit register, map to the appropriate register
16309 // class and return the appropriate register.
16310 if (Res.second == &X86::GR16RegClass) {
16311 if (VT == MVT::i8) {
16312 unsigned DestReg = 0;
16313 switch (Res.first) {
16315 case X86::AX: DestReg = X86::AL; break;
16316 case X86::DX: DestReg = X86::DL; break;
16317 case X86::CX: DestReg = X86::CL; break;
16318 case X86::BX: DestReg = X86::BL; break;
16321 Res.first = DestReg;
16322 Res.second = &X86::GR8RegClass;
16324 } else if (VT == MVT::i32) {
16325 unsigned DestReg = 0;
16326 switch (Res.first) {
16328 case X86::AX: DestReg = X86::EAX; break;
16329 case X86::DX: DestReg = X86::EDX; break;
16330 case X86::CX: DestReg = X86::ECX; break;
16331 case X86::BX: DestReg = X86::EBX; break;
16332 case X86::SI: DestReg = X86::ESI; break;
16333 case X86::DI: DestReg = X86::EDI; break;
16334 case X86::BP: DestReg = X86::EBP; break;
16335 case X86::SP: DestReg = X86::ESP; break;
16338 Res.first = DestReg;
16339 Res.second = &X86::GR32RegClass;
16341 } else if (VT == MVT::i64) {
16342 unsigned DestReg = 0;
16343 switch (Res.first) {
16345 case X86::AX: DestReg = X86::RAX; break;
16346 case X86::DX: DestReg = X86::RDX; break;
16347 case X86::CX: DestReg = X86::RCX; break;
16348 case X86::BX: DestReg = X86::RBX; break;
16349 case X86::SI: DestReg = X86::RSI; break;
16350 case X86::DI: DestReg = X86::RDI; break;
16351 case X86::BP: DestReg = X86::RBP; break;
16352 case X86::SP: DestReg = X86::RSP; break;
16355 Res.first = DestReg;
16356 Res.second = &X86::GR64RegClass;
16359 } else if (Res.second == &X86::FR32RegClass ||
16360 Res.second == &X86::FR64RegClass ||
16361 Res.second == &X86::VR128RegClass) {
16362 // Handle references to XMM physical registers that got mapped into the
16363 // wrong class. This can happen with constraints like {xmm0} where the
16364 // target independent register mapper will just pick the first match it can
16365 // find, ignoring the required type.
16367 if (VT == MVT::f32 || VT == MVT::i32)
16368 Res.second = &X86::FR32RegClass;
16369 else if (VT == MVT::f64 || VT == MVT::i64)
16370 Res.second = &X86::FR64RegClass;
16371 else if (X86::VR128RegClass.hasType(VT))
16372 Res.second = &X86::VR128RegClass;
16373 else if (X86::VR256RegClass.hasType(VT))
16374 Res.second = &X86::VR256RegClass;