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"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
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();
162 RegInfo = TM.getRegisterInfo();
163 TD = getDataLayout();
165 // Set up the TargetLowering object.
166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168 // X86 is weird, it always uses i8 for shift amounts and setcc results.
169 setBooleanContents(ZeroOrOneBooleanContent);
170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 // For 64-bit since we have so many registers use the ILP scheduler, for
174 // 32-bit code use the register pressure specific scheduling.
175 // For Atom, always use ILP scheduling.
176 if (Subtarget->isAtom())
177 setSchedulingPreference(Sched::ILP);
178 else if (Subtarget->is64Bit())
179 setSchedulingPreference(Sched::ILP);
181 setSchedulingPreference(Sched::RegPressure);
182 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
184 // Bypass i32 with i8 on Atom when compiling with O2
185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186 addBypassSlowDiv(32, 8);
188 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189 // Setup Windows compiler runtime calls.
190 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192 setLibcallName(RTLIB::SREM_I64, "_allrem");
193 setLibcallName(RTLIB::UREM_I64, "_aullrem");
194 setLibcallName(RTLIB::MUL_I64, "_allmul");
195 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201 // The _ftol2 runtime function has an unusual calling conv, which
202 // is modeled by a special pseudo-instruction.
203 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
209 if (Subtarget->isTargetDarwin()) {
210 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211 setUseUnderscoreSetJmp(false);
212 setUseUnderscoreLongJmp(false);
213 } else if (Subtarget->isTargetMingw()) {
214 // MS runtime is weird: it exports _setjmp, but longjmp!
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(false);
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(true);
222 // Set up the register classes.
223 addRegisterClass(MVT::i8, &X86::GR8RegClass);
224 addRegisterClass(MVT::i16, &X86::GR16RegClass);
225 addRegisterClass(MVT::i32, &X86::GR32RegClass);
226 if (Subtarget->is64Bit())
227 addRegisterClass(MVT::i64, &X86::GR64RegClass);
229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231 // We don't accept any truncstore of integer registers.
232 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
239 // SETOEQ and SETUNE require checking two conditions.
240 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
250 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
253 if (Subtarget->is64Bit()) {
254 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
256 } else if (!TM.Options.UseSoftFloat) {
257 // We have an algorithm for SSE2->double, and we turn this into a
258 // 64-bit FILD followed by conditional FADD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
260 // We have an algorithm for SSE2, and we turn this into a 64-bit
261 // FILD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
265 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
268 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
270 if (!TM.Options.UseSoftFloat) {
271 // SSE has no i16 to fp conversion, only i32
272 if (X86ScalarSSEf32) {
273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
274 // f32 and f64 cases are Legal, f80 case is not
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
285 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
286 // are Legal, f80 is custom lowered.
287 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
288 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
290 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
293 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
295 if (X86ScalarSSEf32) {
296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
297 // f32 and f64 cases are Legal, f80 case is not
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 // Handle FP_TO_UINT by promoting the destination to a larger signed
306 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
307 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
310 if (Subtarget->is64Bit()) {
311 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
313 } else if (!TM.Options.UseSoftFloat) {
314 // Since AVX is a superset of SSE3, only check for SSE here.
315 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316 // Expand FP_TO_UINT into a select.
317 // FIXME: We would like to use a Custom expander here eventually to do
318 // the optimal thing for SSE vs. the default expansion in the legalizer.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
321 // With SSE3 we can use fisttpll to convert to a signed i64; without
322 // SSE, we're stuck with a fistpll.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
326 if (isTargetFTOL()) {
327 // Use the _ftol2 runtime function, which has a pseudo-instruction
328 // to handle its weird calling convention.
329 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
332 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333 if (!X86ScalarSSEf64) {
334 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
335 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
338 // Without SSE, i64->f64 goes through memory.
339 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
343 // Scalar integer divide and remainder are lowered to use operations that
344 // produce two results, to match the available instructions. This exposes
345 // the two-result form to trivial CSE, which is able to combine x/y and x%y
346 // into a single instruction.
348 // Scalar integer multiply-high is also lowered to use two-result
349 // operations, to match the available instructions. However, plain multiply
350 // (low) operations are left as Legal, as there are single-result
351 // instructions for this in x86. Using the two-result multiply instructions
352 // when both high and low results are needed must be arranged by dagcombine.
353 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355 setOperationAction(ISD::MULHS, VT, Expand);
356 setOperationAction(ISD::MULHU, VT, Expand);
357 setOperationAction(ISD::SDIV, VT, Expand);
358 setOperationAction(ISD::UDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UREM, VT, Expand);
362 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363 setOperationAction(ISD::ADDC, VT, Custom);
364 setOperationAction(ISD::ADDE, VT, Custom);
365 setOperationAction(ISD::SUBC, VT, Custom);
366 setOperationAction(ISD::SUBE, VT, Custom);
369 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
370 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
371 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
372 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
378 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
379 setOperationAction(ISD::FREM , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f64 , Expand);
381 setOperationAction(ISD::FREM , MVT::f80 , Expand);
382 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
384 // Promote the i8 variants and force them on up to i32 which has a shorter
386 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
387 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
389 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
390 if (Subtarget->hasBMI()) {
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
393 if (Subtarget->is64Bit())
394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
397 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
402 if (Subtarget->hasLZCNT()) {
403 // When promoting the i8 variants, force them to i32 for a shorter
405 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
406 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
408 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
411 if (Subtarget->is64Bit())
412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
426 if (Subtarget->hasPOPCNT()) {
427 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
429 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
436 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
437 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
439 // These should be promoted to a larger select which is supported.
440 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
441 // X86 wants to expand cmov itself.
442 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
454 if (Subtarget->is64Bit()) {
455 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
456 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
458 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461 // support continuation, user-level threading, and etc.. As a result, no
462 // other SjLj exception interfaces are implemented and please don't build
463 // your own exception handling based on them.
464 // LLVM/Clang supports zero-cost DWARF exception handling.
465 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
469 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
473 if (Subtarget->is64Bit())
474 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
476 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
479 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
480 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
481 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
482 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
484 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
486 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
488 if (Subtarget->is64Bit()) {
489 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
490 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
494 if (Subtarget->hasSSE1())
495 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
497 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
498 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
500 // On X86 and X86-64, atomic operations are lowered to locked instructions.
501 // Locked instructions, in turn, have implicit fence semantics (all memory
502 // operations are flushed before issuing the locked instruction, and they
503 // are not buffered), so we can fold away the common pattern of
504 // fence-atomic-fence.
505 setShouldFoldAtomicFences(true);
507 // Expand certain atomics
508 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
515 if (!Subtarget->is64Bit()) {
516 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
530 if (Subtarget->hasCmpxchg16b()) {
531 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
534 // FIXME - use subtarget debug flags
535 if (!Subtarget->isTargetDarwin() &&
536 !Subtarget->isTargetELF() &&
537 !Subtarget->isTargetCygMing()) {
538 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
541 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
543 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
545 if (Subtarget->is64Bit()) {
546 setExceptionPointerRegister(X86::RAX);
547 setExceptionSelectorRegister(X86::RDX);
549 setExceptionPointerRegister(X86::EAX);
550 setExceptionSelectorRegister(X86::EDX);
552 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558 setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562 setOperationAction(ISD::VASTART , MVT::Other, Custom);
563 setOperationAction(ISD::VAEND , MVT::Other, Expand);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::VAARG , MVT::Other, Custom);
566 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
568 setOperationAction(ISD::VAARG , MVT::Other, Expand);
569 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577 MVT::i64 : MVT::i32, Custom);
578 else if (TM.Options.EnableSegmentedStacks)
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Expand);
585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586 // f32 and f64 use SSE.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f32, &X86::FR32RegClass);
589 addRegisterClass(MVT::f64, &X86::FR64RegClass);
591 // Use ANDPD to simulate FABS.
592 setOperationAction(ISD::FABS , MVT::f64, Custom);
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f64, Custom);
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 // Use ANDPD and ORPD to simulate FCOPYSIGN.
600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603 // Lower this to FGETSIGNx86 plus an AND.
604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607 // We don't support sin/cos/fmod
608 setOperationAction(ISD::FSIN , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Expand FP immediates into loads from the stack, except for the special
615 addLegalFPImmediate(APFloat(+0.0)); // xorpd
616 addLegalFPImmediate(APFloat(+0.0f)); // xorps
617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618 // Use SSE for f32, x87 for f64.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623 // Use ANDPS to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f32, Custom);
626 // Use XORP to simulate FNEG.
627 setOperationAction(ISD::FNEG , MVT::f32, Custom);
629 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 // Use ANDPS and ORPS to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // We don't support sin/cos/fmod
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
639 // Special cases we handle for FP constants.
640 addLegalFPImmediate(APFloat(+0.0f)); // xorps
641 addLegalFPImmediate(APFloat(+0.0)); // FLD0
642 addLegalFPImmediate(APFloat(+1.0)); // FLD1
643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 } else if (!TM.Options.UseSoftFloat) {
651 // f32 and f64 in x87.
652 // Set up the FP register classes.
653 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
663 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
667 addLegalFPImmediate(APFloat(+0.0)); // FLD0
668 addLegalFPImmediate(APFloat(+1.0)); // FLD1
669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
677 // We don't support FMA.
678 setOperationAction(ISD::FMA, MVT::f64, Expand);
679 setOperationAction(ISD::FMA, MVT::f32, Expand);
681 // Long double always uses X87.
682 if (!TM.Options.UseSoftFloat) {
683 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688 addLegalFPImmediate(TmpFlt); // FLD0
690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
693 APFloat TmpFlt2(+1.0);
694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696 addLegalFPImmediate(TmpFlt2); // FLD1
697 TmpFlt2.changeSign();
698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
701 if (!TM.Options.UnsafeFPMath) {
702 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
703 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709 setOperationAction(ISD::FRINT, MVT::f80, Expand);
710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711 setOperationAction(ISD::FMA, MVT::f80, Expand);
714 // Always use a library call for pow.
715 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725 // First set operation action for all vector types to either promote
726 // (for widening) or expand (for scalarization). Then we will selectively
727 // turn on ones that can be effectively codegen'd.
728 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 setOperationAction(ISD::ADD , VT, Expand);
732 setOperationAction(ISD::SUB , VT, Expand);
733 setOperationAction(ISD::FADD, VT, Expand);
734 setOperationAction(ISD::FNEG, VT, Expand);
735 setOperationAction(ISD::FSUB, VT, Expand);
736 setOperationAction(ISD::MUL , VT, Expand);
737 setOperationAction(ISD::FMUL, VT, Expand);
738 setOperationAction(ISD::SDIV, VT, Expand);
739 setOperationAction(ISD::UDIV, VT, Expand);
740 setOperationAction(ISD::FDIV, VT, Expand);
741 setOperationAction(ISD::SREM, VT, Expand);
742 setOperationAction(ISD::UREM, VT, Expand);
743 setOperationAction(ISD::LOAD, VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749 setOperationAction(ISD::FABS, VT, Expand);
750 setOperationAction(ISD::FSIN, VT, Expand);
751 setOperationAction(ISD::FCOS, VT, Expand);
752 setOperationAction(ISD::FREM, VT, Expand);
753 setOperationAction(ISD::FMA, VT, Expand);
754 setOperationAction(ISD::FPOWI, VT, Expand);
755 setOperationAction(ISD::FSQRT, VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757 setOperationAction(ISD::FFLOOR, VT, Expand);
758 setOperationAction(ISD::FCEIL, VT, Expand);
759 setOperationAction(ISD::FTRUNC, VT, Expand);
760 setOperationAction(ISD::FRINT, VT, Expand);
761 setOperationAction(ISD::FNEARBYINT, VT, Expand);
762 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764 setOperationAction(ISD::SDIVREM, VT, Expand);
765 setOperationAction(ISD::UDIVREM, VT, Expand);
766 setOperationAction(ISD::FPOW, VT, Expand);
767 setOperationAction(ISD::CTPOP, VT, Expand);
768 setOperationAction(ISD::CTTZ, VT, Expand);
769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770 setOperationAction(ISD::CTLZ, VT, Expand);
771 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772 setOperationAction(ISD::SHL, VT, Expand);
773 setOperationAction(ISD::SRA, VT, Expand);
774 setOperationAction(ISD::SRL, VT, Expand);
775 setOperationAction(ISD::ROTL, VT, Expand);
776 setOperationAction(ISD::ROTR, VT, Expand);
777 setOperationAction(ISD::BSWAP, VT, Expand);
778 setOperationAction(ISD::SETCC, VT, Expand);
779 setOperationAction(ISD::FLOG, VT, Expand);
780 setOperationAction(ISD::FLOG2, VT, Expand);
781 setOperationAction(ISD::FLOG10, VT, Expand);
782 setOperationAction(ISD::FEXP, VT, Expand);
783 setOperationAction(ISD::FEXP2, VT, Expand);
784 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789 setOperationAction(ISD::TRUNCATE, VT, Expand);
790 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793 setOperationAction(ISD::VSELECT, VT, Expand);
794 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796 setTruncStoreAction(VT,
797 (MVT::SimpleValueType)InnerVT, Expand);
798 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
803 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804 // with -msoft-float, disable use of MMX as well.
805 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807 // No operations on x86mmx supported, everything uses intrinsics.
810 // MMX-sized vectors (other than x86mmx) are expected to be expanded
811 // into smaller operations.
812 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
813 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
814 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
815 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
816 setOperationAction(ISD::AND, MVT::v8i8, Expand);
817 setOperationAction(ISD::AND, MVT::v4i16, Expand);
818 setOperationAction(ISD::AND, MVT::v2i32, Expand);
819 setOperationAction(ISD::AND, MVT::v1i64, Expand);
820 setOperationAction(ISD::OR, MVT::v8i8, Expand);
821 setOperationAction(ISD::OR, MVT::v4i16, Expand);
822 setOperationAction(ISD::OR, MVT::v2i32, Expand);
823 setOperationAction(ISD::OR, MVT::v1i64, Expand);
824 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
833 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
834 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
835 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
836 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
837 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
838 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
839 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
840 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
845 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
846 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
847 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
848 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
849 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
850 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
851 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
852 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
853 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
854 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
859 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
862 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863 // registers cannot be used even for integer operations.
864 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
869 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
870 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
871 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
872 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
874 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
875 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
876 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
877 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
878 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
879 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
880 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
881 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
882 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
883 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
884 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
885 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
886 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
888 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
889 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
890 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
891 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
895 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
899 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to custom lower non-power-of-2 vectors
903 if (!isPowerOf2_32(VT.getVectorNumElements()))
905 // Do not attempt to custom lower non-128-bit vectors
906 if (!VT.is128BitVector())
908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
913 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
917 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
920 if (Subtarget->is64Bit()) {
921 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
925 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927 MVT VT = (MVT::SimpleValueType)i;
929 // Do not attempt to promote non-128-bit vectors
930 if (!VT.is128BitVector())
933 setOperationAction(ISD::AND, VT, Promote);
934 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
935 setOperationAction(ISD::OR, VT, Promote);
936 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
937 setOperationAction(ISD::XOR, VT, Promote);
938 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
939 setOperationAction(ISD::LOAD, VT, Promote);
940 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
941 setOperationAction(ISD::SELECT, VT, Promote);
942 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
945 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
947 // Custom lower v2i64 and v2f64 selects.
948 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
949 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
950 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
951 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
953 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
954 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
956 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
957 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
958 // As there is no 64-bit GPR available, we need build a special custom
959 // sequence to convert from v2i32 to v2f32.
960 if (!Subtarget->is64Bit())
961 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
963 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
964 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
966 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
969 if (Subtarget->hasSSE41()) {
970 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
971 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
972 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
973 setOperationAction(ISD::FRINT, MVT::f32, Legal);
974 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
975 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
976 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
977 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
978 setOperationAction(ISD::FRINT, MVT::f64, Legal);
979 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
981 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
982 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
983 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
984 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
985 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
986 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
987 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
988 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
989 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
990 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
992 // FIXME: Do we need to handle scalar-to-vector here?
993 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
995 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
996 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
997 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
998 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
999 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1001 // i8 and i16 vectors are custom , because the source register and source
1002 // source memory operand types are not the same width. f32 vectors are
1003 // custom since the immediate controlling the insert encodes additional
1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1015 // FIXME: these should be Legal but thats only for the case where
1016 // the index is constant. For now custom expand to deal with that.
1017 if (Subtarget->is64Bit()) {
1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1023 if (Subtarget->hasSSE2()) {
1024 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1027 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1028 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1030 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1031 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1033 if (Subtarget->hasInt256()) {
1034 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1035 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1037 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1038 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1040 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1042 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1043 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1045 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1046 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1048 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1050 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1051 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1054 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1055 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1058 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1059 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1060 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1062 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1063 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1064 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1066 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1074 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1075 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1076 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1077 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1079 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1087 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1088 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1089 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1090 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1092 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1093 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1095 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1097 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1098 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1099 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1101 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1102 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1103 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1105 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1107 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1108 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1110 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1111 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1113 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1114 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1116 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1118 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1119 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1120 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1121 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1123 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1124 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1125 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1127 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1128 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1129 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1130 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1132 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1133 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1134 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1135 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1136 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1137 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1139 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1140 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1143 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1144 setOperationAction(ISD::FMA, MVT::f32, Legal);
1145 setOperationAction(ISD::FMA, MVT::f64, Legal);
1148 if (Subtarget->hasInt256()) {
1149 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1150 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1151 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1152 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1154 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1155 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1156 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1157 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1159 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1160 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1161 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1162 // Don't lower v32i8 because there is no 128-bit byte mul
1164 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1166 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1167 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1169 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1170 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1172 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1174 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1176 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1177 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1178 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1179 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1182 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1184 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1186 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1187 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1188 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1189 // Don't lower v32i8 because there is no 128-bit byte mul
1191 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1197 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1200 // Custom lower several nodes for 256-bit types.
1201 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1202 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1203 MVT VT = (MVT::SimpleValueType)i;
1205 // Extract subvector is special because the value type
1206 // (result) is 128-bit but the source is 256-bit wide.
1207 if (VT.is128BitVector())
1208 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1210 // Do not attempt to custom lower other non-256-bit vectors
1211 if (!VT.is256BitVector())
1214 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1215 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1216 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1217 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1218 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1219 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1220 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1223 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1224 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1225 MVT VT = (MVT::SimpleValueType)i;
1227 // Do not attempt to promote non-256-bit vectors
1228 if (!VT.is256BitVector())
1231 setOperationAction(ISD::AND, VT, Promote);
1232 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1233 setOperationAction(ISD::OR, VT, Promote);
1234 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1235 setOperationAction(ISD::XOR, VT, Promote);
1236 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1237 setOperationAction(ISD::LOAD, VT, Promote);
1238 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1239 setOperationAction(ISD::SELECT, VT, Promote);
1240 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1244 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1245 // of this type with custom code.
1246 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1247 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1248 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1252 // We want to custom lower some of our intrinsics.
1253 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1254 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1256 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1257 // handle type legalization for these operations here.
1259 // FIXME: We really should do custom legalization for addition and
1260 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1261 // than generic legalization for 64-bit multiplication-with-overflow, though.
1262 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1263 // Add/Sub/Mul with overflow operations are custom lowered.
1265 setOperationAction(ISD::SADDO, VT, Custom);
1266 setOperationAction(ISD::UADDO, VT, Custom);
1267 setOperationAction(ISD::SSUBO, VT, Custom);
1268 setOperationAction(ISD::USUBO, VT, Custom);
1269 setOperationAction(ISD::SMULO, VT, Custom);
1270 setOperationAction(ISD::UMULO, VT, Custom);
1273 // There are no 8-bit 3-address imul/mul instructions
1274 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1275 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1277 if (!Subtarget->is64Bit()) {
1278 // These libcalls are not available in 32-bit.
1279 setLibcallName(RTLIB::SHL_I128, 0);
1280 setLibcallName(RTLIB::SRL_I128, 0);
1281 setLibcallName(RTLIB::SRA_I128, 0);
1284 // We have target-specific dag combine patterns for the following nodes:
1285 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1286 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1287 setTargetDAGCombine(ISD::VSELECT);
1288 setTargetDAGCombine(ISD::SELECT);
1289 setTargetDAGCombine(ISD::SHL);
1290 setTargetDAGCombine(ISD::SRA);
1291 setTargetDAGCombine(ISD::SRL);
1292 setTargetDAGCombine(ISD::OR);
1293 setTargetDAGCombine(ISD::AND);
1294 setTargetDAGCombine(ISD::ADD);
1295 setTargetDAGCombine(ISD::FADD);
1296 setTargetDAGCombine(ISD::FSUB);
1297 setTargetDAGCombine(ISD::FMA);
1298 setTargetDAGCombine(ISD::SUB);
1299 setTargetDAGCombine(ISD::LOAD);
1300 setTargetDAGCombine(ISD::STORE);
1301 setTargetDAGCombine(ISD::ZERO_EXTEND);
1302 setTargetDAGCombine(ISD::ANY_EXTEND);
1303 setTargetDAGCombine(ISD::SIGN_EXTEND);
1304 setTargetDAGCombine(ISD::TRUNCATE);
1305 setTargetDAGCombine(ISD::SINT_TO_FP);
1306 setTargetDAGCombine(ISD::SETCC);
1307 if (Subtarget->is64Bit())
1308 setTargetDAGCombine(ISD::MUL);
1309 setTargetDAGCombine(ISD::XOR);
1311 computeRegisterProperties();
1313 // On Darwin, -Os means optimize for size without hurting performance,
1314 // do not reduce the limit.
1315 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1316 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1317 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1318 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1319 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1320 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1321 setPrefLoopAlignment(4); // 2^4 bytes.
1322 benefitFromCodePlacementOpt = true;
1324 // Predictable cmov don't hurt on atom because it's in-order.
1325 predictableSelectIsExpensive = !Subtarget->isAtom();
1327 setPrefFunctionAlignment(4); // 2^4 bytes.
1330 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1331 if (!VT.isVector()) return MVT::i8;
1332 return VT.changeVectorElementTypeToInteger();
1335 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1336 /// the desired ByVal argument alignment.
1337 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1340 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1341 if (VTy->getBitWidth() == 128)
1343 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1344 unsigned EltAlign = 0;
1345 getMaxByValAlign(ATy->getElementType(), EltAlign);
1346 if (EltAlign > MaxAlign)
1347 MaxAlign = EltAlign;
1348 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1349 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1350 unsigned EltAlign = 0;
1351 getMaxByValAlign(STy->getElementType(i), EltAlign);
1352 if (EltAlign > MaxAlign)
1353 MaxAlign = EltAlign;
1360 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1361 /// function arguments in the caller parameter area. For X86, aggregates
1362 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1363 /// are at 4-byte boundaries.
1364 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1365 if (Subtarget->is64Bit()) {
1366 // Max of 8 and alignment of type.
1367 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1374 if (Subtarget->hasSSE1())
1375 getMaxByValAlign(Ty, Align);
1379 /// getOptimalMemOpType - Returns the target specific optimal type for load
1380 /// and store operations as a result of memset, memcpy, and memmove
1381 /// lowering. If DstAlign is zero that means it's safe to destination
1382 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1383 /// means there isn't a need to check it against alignment requirement,
1384 /// probably because the source does not need to be loaded. If 'IsMemset' is
1385 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1386 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1387 /// source is constant so it does not need to be loaded.
1388 /// It returns EVT::Other if the type should be determined using generic
1389 /// target-independent logic.
1391 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1392 unsigned DstAlign, unsigned SrcAlign,
1393 bool IsMemset, bool ZeroMemset,
1395 MachineFunction &MF) const {
1396 const Function *F = MF.getFunction();
1397 if ((!IsMemset || ZeroMemset) &&
1398 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1399 Attribute::NoImplicitFloat)) {
1401 (Subtarget->isUnalignedMemAccessFast() ||
1402 ((DstAlign == 0 || DstAlign >= 16) &&
1403 (SrcAlign == 0 || SrcAlign >= 16)))) {
1405 if (Subtarget->hasInt256())
1407 if (Subtarget->hasFp256())
1410 if (Subtarget->hasSSE2())
1412 if (Subtarget->hasSSE1())
1414 } else if (!MemcpyStrSrc && Size >= 8 &&
1415 !Subtarget->is64Bit() &&
1416 Subtarget->hasSSE2()) {
1417 // Do not use f64 to lower memcpy if source is string constant. It's
1418 // better to use i32 to avoid the loads.
1422 if (Subtarget->is64Bit() && Size >= 8)
1427 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1429 return X86ScalarSSEf32;
1430 else if (VT == MVT::f64)
1431 return X86ScalarSSEf64;
1436 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1438 *Fast = Subtarget->isUnalignedMemAccessFast();
1442 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1443 /// current function. The returned value is a member of the
1444 /// MachineJumpTableInfo::JTEntryKind enum.
1445 unsigned X86TargetLowering::getJumpTableEncoding() const {
1446 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1448 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1449 Subtarget->isPICStyleGOT())
1450 return MachineJumpTableInfo::EK_Custom32;
1452 // Otherwise, use the normal jump table encoding heuristics.
1453 return TargetLowering::getJumpTableEncoding();
1457 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1458 const MachineBasicBlock *MBB,
1459 unsigned uid,MCContext &Ctx) const{
1460 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1461 Subtarget->isPICStyleGOT());
1462 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1464 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1465 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1468 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1470 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1471 SelectionDAG &DAG) const {
1472 if (!Subtarget->is64Bit())
1473 // This doesn't have DebugLoc associated with it, but is not really the
1474 // same as a Register.
1475 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1479 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1480 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1482 const MCExpr *X86TargetLowering::
1483 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1484 MCContext &Ctx) const {
1485 // X86-64 uses RIP relative addressing based on the jump table label.
1486 if (Subtarget->isPICStyleRIPRel())
1487 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1489 // Otherwise, the reference is relative to the PIC base.
1490 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1493 // FIXME: Why this routine is here? Move to RegInfo!
1494 std::pair<const TargetRegisterClass*, uint8_t>
1495 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1496 const TargetRegisterClass *RRC = 0;
1498 switch (VT.SimpleTy) {
1500 return TargetLowering::findRepresentativeClass(VT);
1501 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1502 RRC = Subtarget->is64Bit() ?
1503 (const TargetRegisterClass*)&X86::GR64RegClass :
1504 (const TargetRegisterClass*)&X86::GR32RegClass;
1507 RRC = &X86::VR64RegClass;
1509 case MVT::f32: case MVT::f64:
1510 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1511 case MVT::v4f32: case MVT::v2f64:
1512 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1514 RRC = &X86::VR128RegClass;
1517 return std::make_pair(RRC, Cost);
1520 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1521 unsigned &Offset) const {
1522 if (!Subtarget->isTargetLinux())
1525 if (Subtarget->is64Bit()) {
1526 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1528 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1540 //===----------------------------------------------------------------------===//
1541 // Return Value Calling Convention Implementation
1542 //===----------------------------------------------------------------------===//
1544 #include "X86GenCallingConv.inc"
1547 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1548 MachineFunction &MF, bool isVarArg,
1549 const SmallVectorImpl<ISD::OutputArg> &Outs,
1550 LLVMContext &Context) const {
1551 SmallVector<CCValAssign, 16> RVLocs;
1552 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1554 return CCInfo.CheckReturn(Outs, RetCC_X86);
1558 X86TargetLowering::LowerReturn(SDValue Chain,
1559 CallingConv::ID CallConv, bool isVarArg,
1560 const SmallVectorImpl<ISD::OutputArg> &Outs,
1561 const SmallVectorImpl<SDValue> &OutVals,
1562 DebugLoc dl, SelectionDAG &DAG) const {
1563 MachineFunction &MF = DAG.getMachineFunction();
1564 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1566 SmallVector<CCValAssign, 16> RVLocs;
1567 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1568 RVLocs, *DAG.getContext());
1569 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1571 // Add the regs to the liveout set for the function.
1572 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1573 for (unsigned i = 0; i != RVLocs.size(); ++i)
1574 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1575 MRI.addLiveOut(RVLocs[i].getLocReg());
1579 SmallVector<SDValue, 6> RetOps;
1580 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1581 // Operand #1 = Bytes To Pop
1582 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1585 // Copy the result values into the output registers.
1586 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1587 CCValAssign &VA = RVLocs[i];
1588 assert(VA.isRegLoc() && "Can only return in registers!");
1589 SDValue ValToCopy = OutVals[i];
1590 EVT ValVT = ValToCopy.getValueType();
1592 // Promote values to the appropriate types
1593 if (VA.getLocInfo() == CCValAssign::SExt)
1594 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1595 else if (VA.getLocInfo() == CCValAssign::ZExt)
1596 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1597 else if (VA.getLocInfo() == CCValAssign::AExt)
1598 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1599 else if (VA.getLocInfo() == CCValAssign::BCvt)
1600 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1602 // If this is x86-64, and we disabled SSE, we can't return FP values,
1603 // or SSE or MMX vectors.
1604 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1605 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1606 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1607 report_fatal_error("SSE register return with SSE disabled");
1609 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1610 // llvm-gcc has never done it right and no one has noticed, so this
1611 // should be OK for now.
1612 if (ValVT == MVT::f64 &&
1613 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1614 report_fatal_error("SSE2 register return with SSE2 disabled");
1616 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1617 // the RET instruction and handled by the FP Stackifier.
1618 if (VA.getLocReg() == X86::ST0 ||
1619 VA.getLocReg() == X86::ST1) {
1620 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1621 // change the value to the FP stack register class.
1622 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1623 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1624 RetOps.push_back(ValToCopy);
1625 // Don't emit a copytoreg.
1629 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1630 // which is returned in RAX / RDX.
1631 if (Subtarget->is64Bit()) {
1632 if (ValVT == MVT::x86mmx) {
1633 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1634 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1635 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1637 // If we don't have SSE2 available, convert to v4f32 so the generated
1638 // register is legal.
1639 if (!Subtarget->hasSSE2())
1640 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1645 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1646 Flag = Chain.getValue(1);
1649 // The x86-64 ABI for returning structs by value requires that we copy
1650 // the sret argument into %rax for the return. We saved the argument into
1651 // a virtual register in the entry block, so now we copy the value out
1653 if (Subtarget->is64Bit() &&
1654 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1655 MachineFunction &MF = DAG.getMachineFunction();
1656 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1657 unsigned Reg = FuncInfo->getSRetReturnReg();
1659 "SRetReturnReg should have been set in LowerFormalArguments().");
1660 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1662 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1663 Flag = Chain.getValue(1);
1665 // RAX now acts like a return value.
1666 MRI.addLiveOut(X86::RAX);
1669 RetOps[0] = Chain; // Update chain.
1671 // Add the flag if we have it.
1673 RetOps.push_back(Flag);
1675 return DAG.getNode(X86ISD::RET_FLAG, dl,
1676 MVT::Other, &RetOps[0], RetOps.size());
1679 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1680 if (N->getNumValues() != 1)
1682 if (!N->hasNUsesOfValue(1, 0))
1685 SDValue TCChain = Chain;
1686 SDNode *Copy = *N->use_begin();
1687 if (Copy->getOpcode() == ISD::CopyToReg) {
1688 // If the copy has a glue operand, we conservatively assume it isn't safe to
1689 // perform a tail call.
1690 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1692 TCChain = Copy->getOperand(0);
1693 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1696 bool HasRet = false;
1697 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1699 if (UI->getOpcode() != X86ISD::RET_FLAG)
1712 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1713 ISD::NodeType ExtendKind) const {
1715 // TODO: Is this also valid on 32-bit?
1716 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1717 ReturnMVT = MVT::i8;
1719 ReturnMVT = MVT::i32;
1721 MVT MinVT = getRegisterType(ReturnMVT);
1722 return VT.bitsLT(MinVT) ? MinVT : VT;
1725 /// LowerCallResult - Lower the result values of a call into the
1726 /// appropriate copies out of appropriate physical registers.
1729 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1730 CallingConv::ID CallConv, bool isVarArg,
1731 const SmallVectorImpl<ISD::InputArg> &Ins,
1732 DebugLoc dl, SelectionDAG &DAG,
1733 SmallVectorImpl<SDValue> &InVals) const {
1735 // Assign locations to each value returned by this call.
1736 SmallVector<CCValAssign, 16> RVLocs;
1737 bool Is64Bit = Subtarget->is64Bit();
1738 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1739 getTargetMachine(), RVLocs, *DAG.getContext());
1740 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1742 // Copy all of the result registers out of their specified physreg.
1743 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1744 CCValAssign &VA = RVLocs[i];
1745 EVT CopyVT = VA.getValVT();
1747 // If this is x86-64, and we disabled SSE, we can't return FP values
1748 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1749 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1750 report_fatal_error("SSE register return with SSE disabled");
1755 // If this is a call to a function that returns an fp value on the floating
1756 // point stack, we must guarantee the value is popped from the stack, so
1757 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1758 // if the return value is not used. We use the FpPOP_RETVAL instruction
1760 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1761 // If we prefer to use the value in xmm registers, copy it out as f80 and
1762 // use a truncate to move it from fp stack reg to xmm reg.
1763 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1764 SDValue Ops[] = { Chain, InFlag };
1765 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1766 MVT::Other, MVT::Glue, Ops, 2), 1);
1767 Val = Chain.getValue(0);
1769 // Round the f80 to the right size, which also moves it to the appropriate
1771 if (CopyVT != VA.getValVT())
1772 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1773 // This truncation won't change the value.
1774 DAG.getIntPtrConstant(1));
1776 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1777 CopyVT, InFlag).getValue(1);
1778 Val = Chain.getValue(0);
1780 InFlag = Chain.getValue(2);
1781 InVals.push_back(Val);
1787 //===----------------------------------------------------------------------===//
1788 // C & StdCall & Fast Calling Convention implementation
1789 //===----------------------------------------------------------------------===//
1790 // StdCall calling convention seems to be standard for many Windows' API
1791 // routines and around. It differs from C calling convention just a little:
1792 // callee should clean up the stack, not caller. Symbols should be also
1793 // decorated in some fancy way :) It doesn't support any vector arguments.
1794 // For info on fast calling convention see Fast Calling Convention (tail call)
1795 // implementation LowerX86_32FastCCCallTo.
1797 /// CallIsStructReturn - Determines whether a call uses struct return
1799 enum StructReturnType {
1804 static StructReturnType
1805 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1807 return NotStructReturn;
1809 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1810 if (!Flags.isSRet())
1811 return NotStructReturn;
1812 if (Flags.isInReg())
1813 return RegStructReturn;
1814 return StackStructReturn;
1817 /// ArgsAreStructReturn - Determines whether a function uses struct
1818 /// return semantics.
1819 static StructReturnType
1820 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1822 return NotStructReturn;
1824 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1825 if (!Flags.isSRet())
1826 return NotStructReturn;
1827 if (Flags.isInReg())
1828 return RegStructReturn;
1829 return StackStructReturn;
1832 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1833 /// by "Src" to address "Dst" with size and alignment information specified by
1834 /// the specific parameter attribute. The copy will be passed as a byval
1835 /// function parameter.
1837 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1838 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1840 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1842 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1843 /*isVolatile*/false, /*AlwaysInline=*/true,
1844 MachinePointerInfo(), MachinePointerInfo());
1847 /// IsTailCallConvention - Return true if the calling convention is one that
1848 /// supports tail call optimization.
1849 static bool IsTailCallConvention(CallingConv::ID CC) {
1850 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1851 CC == CallingConv::HiPE);
1854 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1855 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1859 CallingConv::ID CalleeCC = CS.getCallingConv();
1860 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1866 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1867 /// a tailcall target by changing its ABI.
1868 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1869 bool GuaranteedTailCallOpt) {
1870 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1874 X86TargetLowering::LowerMemArgument(SDValue Chain,
1875 CallingConv::ID CallConv,
1876 const SmallVectorImpl<ISD::InputArg> &Ins,
1877 DebugLoc dl, SelectionDAG &DAG,
1878 const CCValAssign &VA,
1879 MachineFrameInfo *MFI,
1881 // Create the nodes corresponding to a load from this parameter slot.
1882 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1883 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1884 getTargetMachine().Options.GuaranteedTailCallOpt);
1885 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1888 // If value is passed by pointer we have address passed instead of the value
1890 if (VA.getLocInfo() == CCValAssign::Indirect)
1891 ValVT = VA.getLocVT();
1893 ValVT = VA.getValVT();
1895 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1896 // changed with more analysis.
1897 // In case of tail call optimization mark all arguments mutable. Since they
1898 // could be overwritten by lowering of arguments in case of a tail call.
1899 if (Flags.isByVal()) {
1900 unsigned Bytes = Flags.getByValSize();
1901 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1902 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1903 return DAG.getFrameIndex(FI, getPointerTy());
1905 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1906 VA.getLocMemOffset(), isImmutable);
1907 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1908 return DAG.getLoad(ValVT, dl, Chain, FIN,
1909 MachinePointerInfo::getFixedStack(FI),
1910 false, false, false, 0);
1915 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1916 CallingConv::ID CallConv,
1918 const SmallVectorImpl<ISD::InputArg> &Ins,
1921 SmallVectorImpl<SDValue> &InVals)
1923 MachineFunction &MF = DAG.getMachineFunction();
1924 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1926 const Function* Fn = MF.getFunction();
1927 if (Fn->hasExternalLinkage() &&
1928 Subtarget->isTargetCygMing() &&
1929 Fn->getName() == "main")
1930 FuncInfo->setForceFramePointer(true);
1932 MachineFrameInfo *MFI = MF.getFrameInfo();
1933 bool Is64Bit = Subtarget->is64Bit();
1934 bool IsWindows = Subtarget->isTargetWindows();
1935 bool IsWin64 = Subtarget->isTargetWin64();
1937 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1938 "Var args not supported with calling convention fastcc, ghc or hipe");
1940 // Assign locations to all of the incoming arguments.
1941 SmallVector<CCValAssign, 16> ArgLocs;
1942 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1943 ArgLocs, *DAG.getContext());
1945 // Allocate shadow area for Win64
1947 CCInfo.AllocateStack(32, 8);
1950 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1952 unsigned LastVal = ~0U;
1954 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1955 CCValAssign &VA = ArgLocs[i];
1956 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1958 assert(VA.getValNo() != LastVal &&
1959 "Don't support value assigned to multiple locs yet");
1961 LastVal = VA.getValNo();
1963 if (VA.isRegLoc()) {
1964 EVT RegVT = VA.getLocVT();
1965 const TargetRegisterClass *RC;
1966 if (RegVT == MVT::i32)
1967 RC = &X86::GR32RegClass;
1968 else if (Is64Bit && RegVT == MVT::i64)
1969 RC = &X86::GR64RegClass;
1970 else if (RegVT == MVT::f32)
1971 RC = &X86::FR32RegClass;
1972 else if (RegVT == MVT::f64)
1973 RC = &X86::FR64RegClass;
1974 else if (RegVT.is256BitVector())
1975 RC = &X86::VR256RegClass;
1976 else if (RegVT.is128BitVector())
1977 RC = &X86::VR128RegClass;
1978 else if (RegVT == MVT::x86mmx)
1979 RC = &X86::VR64RegClass;
1981 llvm_unreachable("Unknown argument type!");
1983 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1984 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1986 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1987 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1989 if (VA.getLocInfo() == CCValAssign::SExt)
1990 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1991 DAG.getValueType(VA.getValVT()));
1992 else if (VA.getLocInfo() == CCValAssign::ZExt)
1993 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1994 DAG.getValueType(VA.getValVT()));
1995 else if (VA.getLocInfo() == CCValAssign::BCvt)
1996 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1998 if (VA.isExtInLoc()) {
1999 // Handle MMX values passed in XMM regs.
2000 if (RegVT.isVector())
2001 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2003 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2006 assert(VA.isMemLoc());
2007 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2010 // If value is passed via pointer - do a load.
2011 if (VA.getLocInfo() == CCValAssign::Indirect)
2012 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2013 MachinePointerInfo(), false, false, false, 0);
2015 InVals.push_back(ArgValue);
2018 // The x86-64 ABI for returning structs by value requires that we copy
2019 // the sret argument into %rax for the return. Save the argument into
2020 // a virtual register so that we can access it from the return points.
2021 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2022 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2023 unsigned Reg = FuncInfo->getSRetReturnReg();
2025 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2026 FuncInfo->setSRetReturnReg(Reg);
2028 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2029 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2032 unsigned StackSize = CCInfo.getNextStackOffset();
2033 // Align stack specially for tail calls.
2034 if (FuncIsMadeTailCallSafe(CallConv,
2035 MF.getTarget().Options.GuaranteedTailCallOpt))
2036 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2038 // If the function takes variable number of arguments, make a frame index for
2039 // the start of the first vararg value... for expansion of llvm.va_start.
2041 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2042 CallConv != CallingConv::X86_ThisCall)) {
2043 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2046 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2048 // FIXME: We should really autogenerate these arrays
2049 static const uint16_t GPR64ArgRegsWin64[] = {
2050 X86::RCX, X86::RDX, X86::R8, X86::R9
2052 static const uint16_t GPR64ArgRegs64Bit[] = {
2053 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2055 static const uint16_t XMMArgRegs64Bit[] = {
2056 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2057 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2059 const uint16_t *GPR64ArgRegs;
2060 unsigned NumXMMRegs = 0;
2063 // The XMM registers which might contain var arg parameters are shadowed
2064 // in their paired GPR. So we only need to save the GPR to their home
2066 TotalNumIntRegs = 4;
2067 GPR64ArgRegs = GPR64ArgRegsWin64;
2069 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2070 GPR64ArgRegs = GPR64ArgRegs64Bit;
2072 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2075 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2078 bool NoImplicitFloatOps = Fn->getAttributes().
2079 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2080 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2081 "SSE register cannot be used when SSE is disabled!");
2082 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2083 NoImplicitFloatOps) &&
2084 "SSE register cannot be used when SSE is disabled!");
2085 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2086 !Subtarget->hasSSE1())
2087 // Kernel mode asks for SSE to be disabled, so don't push them
2089 TotalNumXMMRegs = 0;
2092 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2093 // Get to the caller-allocated home save location. Add 8 to account
2094 // for the return address.
2095 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2096 FuncInfo->setRegSaveFrameIndex(
2097 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2098 // Fixup to set vararg frame on shadow area (4 x i64).
2100 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2102 // For X86-64, if there are vararg parameters that are passed via
2103 // registers, then we must store them to their spots on the stack so
2104 // they may be loaded by deferencing the result of va_next.
2105 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2106 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2107 FuncInfo->setRegSaveFrameIndex(
2108 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2112 // Store the integer parameter registers.
2113 SmallVector<SDValue, 8> MemOps;
2114 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2116 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2117 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2118 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2119 DAG.getIntPtrConstant(Offset));
2120 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2121 &X86::GR64RegClass);
2122 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2124 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2125 MachinePointerInfo::getFixedStack(
2126 FuncInfo->getRegSaveFrameIndex(), Offset),
2128 MemOps.push_back(Store);
2132 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2133 // Now store the XMM (fp + vector) parameter registers.
2134 SmallVector<SDValue, 11> SaveXMMOps;
2135 SaveXMMOps.push_back(Chain);
2137 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2138 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2139 SaveXMMOps.push_back(ALVal);
2141 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2142 FuncInfo->getRegSaveFrameIndex()));
2143 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2144 FuncInfo->getVarArgsFPOffset()));
2146 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2147 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2148 &X86::VR128RegClass);
2149 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2150 SaveXMMOps.push_back(Val);
2152 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2154 &SaveXMMOps[0], SaveXMMOps.size()));
2157 if (!MemOps.empty())
2158 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2159 &MemOps[0], MemOps.size());
2163 // Some CCs need callee pop.
2164 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2165 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2166 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2168 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2169 // If this is an sret function, the return should pop the hidden pointer.
2170 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2171 argsAreStructReturn(Ins) == StackStructReturn)
2172 FuncInfo->setBytesToPopOnReturn(4);
2176 // RegSaveFrameIndex is X86-64 only.
2177 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2178 if (CallConv == CallingConv::X86_FastCall ||
2179 CallConv == CallingConv::X86_ThisCall)
2180 // fastcc functions can't have varargs.
2181 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2184 FuncInfo->setArgumentStackSize(StackSize);
2190 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2191 SDValue StackPtr, SDValue Arg,
2192 DebugLoc dl, SelectionDAG &DAG,
2193 const CCValAssign &VA,
2194 ISD::ArgFlagsTy Flags) const {
2195 unsigned LocMemOffset = VA.getLocMemOffset();
2196 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2197 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2198 if (Flags.isByVal())
2199 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2201 return DAG.getStore(Chain, dl, Arg, PtrOff,
2202 MachinePointerInfo::getStack(LocMemOffset),
2206 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2207 /// optimization is performed and it is required.
2209 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2210 SDValue &OutRetAddr, SDValue Chain,
2211 bool IsTailCall, bool Is64Bit,
2212 int FPDiff, DebugLoc dl) const {
2213 // Adjust the Return address stack slot.
2214 EVT VT = getPointerTy();
2215 OutRetAddr = getReturnAddressFrameIndex(DAG);
2217 // Load the "old" Return address.
2218 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2219 false, false, false, 0);
2220 return SDValue(OutRetAddr.getNode(), 1);
2223 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2224 /// optimization is performed and it is required (FPDiff!=0).
2226 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2227 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2228 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2229 // Store the return address to the appropriate stack slot.
2230 if (!FPDiff) return Chain;
2231 // Calculate the new stack slot for the return address.
2232 int NewReturnAddrFI =
2233 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2234 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2235 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2236 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2242 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2243 SmallVectorImpl<SDValue> &InVals) const {
2244 SelectionDAG &DAG = CLI.DAG;
2245 DebugLoc &dl = CLI.DL;
2246 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2247 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2248 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2249 SDValue Chain = CLI.Chain;
2250 SDValue Callee = CLI.Callee;
2251 CallingConv::ID CallConv = CLI.CallConv;
2252 bool &isTailCall = CLI.IsTailCall;
2253 bool isVarArg = CLI.IsVarArg;
2255 MachineFunction &MF = DAG.getMachineFunction();
2256 bool Is64Bit = Subtarget->is64Bit();
2257 bool IsWin64 = Subtarget->isTargetWin64();
2258 bool IsWindows = Subtarget->isTargetWindows();
2259 StructReturnType SR = callIsStructReturn(Outs);
2260 bool IsSibcall = false;
2262 if (MF.getTarget().Options.DisableTailCalls)
2266 // Check if it's really possible to do a tail call.
2267 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2268 isVarArg, SR != NotStructReturn,
2269 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2270 Outs, OutVals, Ins, DAG);
2272 // Sibcalls are automatically detected tailcalls which do not require
2274 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2281 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2282 "Var args not supported with calling convention fastcc, ghc or hipe");
2284 // Analyze operands of the call, assigning locations to each operand.
2285 SmallVector<CCValAssign, 16> ArgLocs;
2286 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2287 ArgLocs, *DAG.getContext());
2289 // Allocate shadow area for Win64
2291 CCInfo.AllocateStack(32, 8);
2294 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2296 // Get a count of how many bytes are to be pushed on the stack.
2297 unsigned NumBytes = CCInfo.getNextStackOffset();
2299 // This is a sibcall. The memory operands are available in caller's
2300 // own caller's stack.
2302 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2303 IsTailCallConvention(CallConv))
2304 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2307 if (isTailCall && !IsSibcall) {
2308 // Lower arguments at fp - stackoffset + fpdiff.
2309 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2310 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2312 FPDiff = NumBytesCallerPushed - NumBytes;
2314 // Set the delta of movement of the returnaddr stackslot.
2315 // But only set if delta is greater than previous delta.
2316 if (FPDiff < X86Info->getTCReturnAddrDelta())
2317 X86Info->setTCReturnAddrDelta(FPDiff);
2321 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2323 SDValue RetAddrFrIdx;
2324 // Load return address for tail calls.
2325 if (isTailCall && FPDiff)
2326 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2327 Is64Bit, FPDiff, dl);
2329 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2330 SmallVector<SDValue, 8> MemOpChains;
2333 // Walk the register/memloc assignments, inserting copies/loads. In the case
2334 // of tail call optimization arguments are handle later.
2335 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2336 CCValAssign &VA = ArgLocs[i];
2337 EVT RegVT = VA.getLocVT();
2338 SDValue Arg = OutVals[i];
2339 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2340 bool isByVal = Flags.isByVal();
2342 // Promote the value if needed.
2343 switch (VA.getLocInfo()) {
2344 default: llvm_unreachable("Unknown loc info!");
2345 case CCValAssign::Full: break;
2346 case CCValAssign::SExt:
2347 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2349 case CCValAssign::ZExt:
2350 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2352 case CCValAssign::AExt:
2353 if (RegVT.is128BitVector()) {
2354 // Special case: passing MMX values in XMM registers.
2355 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2356 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2357 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2359 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2361 case CCValAssign::BCvt:
2362 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2364 case CCValAssign::Indirect: {
2365 // Store the argument.
2366 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2367 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2368 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2369 MachinePointerInfo::getFixedStack(FI),
2376 if (VA.isRegLoc()) {
2377 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2378 if (isVarArg && IsWin64) {
2379 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2380 // shadow reg if callee is a varargs function.
2381 unsigned ShadowReg = 0;
2382 switch (VA.getLocReg()) {
2383 case X86::XMM0: ShadowReg = X86::RCX; break;
2384 case X86::XMM1: ShadowReg = X86::RDX; break;
2385 case X86::XMM2: ShadowReg = X86::R8; break;
2386 case X86::XMM3: ShadowReg = X86::R9; break;
2389 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2391 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2392 assert(VA.isMemLoc());
2393 if (StackPtr.getNode() == 0)
2394 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2396 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2397 dl, DAG, VA, Flags));
2401 if (!MemOpChains.empty())
2402 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2403 &MemOpChains[0], MemOpChains.size());
2405 if (Subtarget->isPICStyleGOT()) {
2406 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2409 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2410 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2412 // If we are tail calling and generating PIC/GOT style code load the
2413 // address of the callee into ECX. The value in ecx is used as target of
2414 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2415 // for tail calls on PIC/GOT architectures. Normally we would just put the
2416 // address of GOT into ebx and then call target@PLT. But for tail calls
2417 // ebx would be restored (since ebx is callee saved) before jumping to the
2420 // Note: The actual moving to ECX is done further down.
2421 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2422 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2423 !G->getGlobal()->hasProtectedVisibility())
2424 Callee = LowerGlobalAddress(Callee, DAG);
2425 else if (isa<ExternalSymbolSDNode>(Callee))
2426 Callee = LowerExternalSymbol(Callee, DAG);
2430 if (Is64Bit && isVarArg && !IsWin64) {
2431 // From AMD64 ABI document:
2432 // For calls that may call functions that use varargs or stdargs
2433 // (prototype-less calls or calls to functions containing ellipsis (...) in
2434 // the declaration) %al is used as hidden argument to specify the number
2435 // of SSE registers used. The contents of %al do not need to match exactly
2436 // the number of registers, but must be an ubound on the number of SSE
2437 // registers used and is in the range 0 - 8 inclusive.
2439 // Count the number of XMM registers allocated.
2440 static const uint16_t XMMArgRegs[] = {
2441 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2442 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2444 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2445 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2446 && "SSE registers cannot be used when SSE is disabled");
2448 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2449 DAG.getConstant(NumXMMRegs, MVT::i8)));
2452 // For tail calls lower the arguments to the 'real' stack slot.
2454 // Force all the incoming stack arguments to be loaded from the stack
2455 // before any new outgoing arguments are stored to the stack, because the
2456 // outgoing stack slots may alias the incoming argument stack slots, and
2457 // the alias isn't otherwise explicit. This is slightly more conservative
2458 // than necessary, because it means that each store effectively depends
2459 // on every argument instead of just those arguments it would clobber.
2460 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2462 SmallVector<SDValue, 8> MemOpChains2;
2465 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2466 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2467 CCValAssign &VA = ArgLocs[i];
2470 assert(VA.isMemLoc());
2471 SDValue Arg = OutVals[i];
2472 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2473 // Create frame index.
2474 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2475 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2476 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2477 FIN = DAG.getFrameIndex(FI, getPointerTy());
2479 if (Flags.isByVal()) {
2480 // Copy relative to framepointer.
2481 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2482 if (StackPtr.getNode() == 0)
2483 StackPtr = DAG.getCopyFromReg(Chain, dl,
2484 RegInfo->getStackRegister(),
2486 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2488 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2492 // Store relative to framepointer.
2493 MemOpChains2.push_back(
2494 DAG.getStore(ArgChain, dl, Arg, FIN,
2495 MachinePointerInfo::getFixedStack(FI),
2501 if (!MemOpChains2.empty())
2502 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2503 &MemOpChains2[0], MemOpChains2.size());
2505 // Store the return address to the appropriate stack slot.
2506 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2507 getPointerTy(), RegInfo->getSlotSize(),
2511 // Build a sequence of copy-to-reg nodes chained together with token chain
2512 // and flag operands which copy the outgoing args into registers.
2514 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2515 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2516 RegsToPass[i].second, InFlag);
2517 InFlag = Chain.getValue(1);
2520 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2521 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2522 // In the 64-bit large code model, we have to make all calls
2523 // through a register, since the call instruction's 32-bit
2524 // pc-relative offset may not be large enough to hold the whole
2526 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2527 // If the callee is a GlobalAddress node (quite common, every direct call
2528 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2531 // We should use extra load for direct calls to dllimported functions in
2533 const GlobalValue *GV = G->getGlobal();
2534 if (!GV->hasDLLImportLinkage()) {
2535 unsigned char OpFlags = 0;
2536 bool ExtraLoad = false;
2537 unsigned WrapperKind = ISD::DELETED_NODE;
2539 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2540 // external symbols most go through the PLT in PIC mode. If the symbol
2541 // has hidden or protected visibility, or if it is static or local, then
2542 // we don't need to use the PLT - we can directly call it.
2543 if (Subtarget->isTargetELF() &&
2544 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2545 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2546 OpFlags = X86II::MO_PLT;
2547 } else if (Subtarget->isPICStyleStubAny() &&
2548 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2549 (!Subtarget->getTargetTriple().isMacOSX() ||
2550 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2551 // PC-relative references to external symbols should go through $stub,
2552 // unless we're building with the leopard linker or later, which
2553 // automatically synthesizes these stubs.
2554 OpFlags = X86II::MO_DARWIN_STUB;
2555 } else if (Subtarget->isPICStyleRIPRel() &&
2556 isa<Function>(GV) &&
2557 cast<Function>(GV)->getAttributes().
2558 hasAttribute(AttributeSet::FunctionIndex,
2559 Attribute::NonLazyBind)) {
2560 // If the function is marked as non-lazy, generate an indirect call
2561 // which loads from the GOT directly. This avoids runtime overhead
2562 // at the cost of eager binding (and one extra byte of encoding).
2563 OpFlags = X86II::MO_GOTPCREL;
2564 WrapperKind = X86ISD::WrapperRIP;
2568 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2569 G->getOffset(), OpFlags);
2571 // Add a wrapper if needed.
2572 if (WrapperKind != ISD::DELETED_NODE)
2573 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2574 // Add extra indirection if needed.
2576 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2577 MachinePointerInfo::getGOT(),
2578 false, false, false, 0);
2580 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2581 unsigned char OpFlags = 0;
2583 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2584 // external symbols should go through the PLT.
2585 if (Subtarget->isTargetELF() &&
2586 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2587 OpFlags = X86II::MO_PLT;
2588 } else if (Subtarget->isPICStyleStubAny() &&
2589 (!Subtarget->getTargetTriple().isMacOSX() ||
2590 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2591 // PC-relative references to external symbols should go through $stub,
2592 // unless we're building with the leopard linker or later, which
2593 // automatically synthesizes these stubs.
2594 OpFlags = X86II::MO_DARWIN_STUB;
2597 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2601 // Returns a chain & a flag for retval copy to use.
2602 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2603 SmallVector<SDValue, 8> Ops;
2605 if (!IsSibcall && isTailCall) {
2606 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2607 DAG.getIntPtrConstant(0, true), InFlag);
2608 InFlag = Chain.getValue(1);
2611 Ops.push_back(Chain);
2612 Ops.push_back(Callee);
2615 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2617 // Add argument registers to the end of the list so that they are known live
2619 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2620 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2621 RegsToPass[i].second.getValueType()));
2623 // Add a register mask operand representing the call-preserved registers.
2624 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2625 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2626 assert(Mask && "Missing call preserved mask for calling convention");
2627 Ops.push_back(DAG.getRegisterMask(Mask));
2629 if (InFlag.getNode())
2630 Ops.push_back(InFlag);
2634 //// If this is the first return lowered for this function, add the regs
2635 //// to the liveout set for the function.
2636 // This isn't right, although it's probably harmless on x86; liveouts
2637 // should be computed from returns not tail calls. Consider a void
2638 // function making a tail call to a function returning int.
2639 return DAG.getNode(X86ISD::TC_RETURN, dl,
2640 NodeTys, &Ops[0], Ops.size());
2643 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2644 InFlag = Chain.getValue(1);
2646 // Create the CALLSEQ_END node.
2647 unsigned NumBytesForCalleeToPush;
2648 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2649 getTargetMachine().Options.GuaranteedTailCallOpt))
2650 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2651 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2652 SR == StackStructReturn)
2653 // If this is a call to a struct-return function, the callee
2654 // pops the hidden struct pointer, so we have to push it back.
2655 // This is common for Darwin/X86, Linux & Mingw32 targets.
2656 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2657 NumBytesForCalleeToPush = 4;
2659 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2661 // Returns a flag for retval copy to use.
2663 Chain = DAG.getCALLSEQ_END(Chain,
2664 DAG.getIntPtrConstant(NumBytes, true),
2665 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2668 InFlag = Chain.getValue(1);
2671 // Handle result values, copying them out of physregs into vregs that we
2673 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2674 Ins, dl, DAG, InVals);
2677 //===----------------------------------------------------------------------===//
2678 // Fast Calling Convention (tail call) implementation
2679 //===----------------------------------------------------------------------===//
2681 // Like std call, callee cleans arguments, convention except that ECX is
2682 // reserved for storing the tail called function address. Only 2 registers are
2683 // free for argument passing (inreg). Tail call optimization is performed
2685 // * tailcallopt is enabled
2686 // * caller/callee are fastcc
2687 // On X86_64 architecture with GOT-style position independent code only local
2688 // (within module) calls are supported at the moment.
2689 // To keep the stack aligned according to platform abi the function
2690 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2691 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2692 // If a tail called function callee has more arguments than the caller the
2693 // caller needs to make sure that there is room to move the RETADDR to. This is
2694 // achieved by reserving an area the size of the argument delta right after the
2695 // original REtADDR, but before the saved framepointer or the spilled registers
2696 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2708 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2709 /// for a 16 byte align requirement.
2711 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2712 SelectionDAG& DAG) const {
2713 MachineFunction &MF = DAG.getMachineFunction();
2714 const TargetMachine &TM = MF.getTarget();
2715 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2716 unsigned StackAlignment = TFI.getStackAlignment();
2717 uint64_t AlignMask = StackAlignment - 1;
2718 int64_t Offset = StackSize;
2719 unsigned SlotSize = RegInfo->getSlotSize();
2720 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2721 // Number smaller than 12 so just add the difference.
2722 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2724 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2725 Offset = ((~AlignMask) & Offset) + StackAlignment +
2726 (StackAlignment-SlotSize);
2731 /// MatchingStackOffset - Return true if the given stack call argument is
2732 /// already available in the same position (relatively) of the caller's
2733 /// incoming argument stack.
2735 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2736 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2737 const X86InstrInfo *TII) {
2738 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2740 if (Arg.getOpcode() == ISD::CopyFromReg) {
2741 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2742 if (!TargetRegisterInfo::isVirtualRegister(VR))
2744 MachineInstr *Def = MRI->getVRegDef(VR);
2747 if (!Flags.isByVal()) {
2748 if (!TII->isLoadFromStackSlot(Def, FI))
2751 unsigned Opcode = Def->getOpcode();
2752 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2753 Def->getOperand(1).isFI()) {
2754 FI = Def->getOperand(1).getIndex();
2755 Bytes = Flags.getByValSize();
2759 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2760 if (Flags.isByVal())
2761 // ByVal argument is passed in as a pointer but it's now being
2762 // dereferenced. e.g.
2763 // define @foo(%struct.X* %A) {
2764 // tail call @bar(%struct.X* byval %A)
2767 SDValue Ptr = Ld->getBasePtr();
2768 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2771 FI = FINode->getIndex();
2772 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2773 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2774 FI = FINode->getIndex();
2775 Bytes = Flags.getByValSize();
2779 assert(FI != INT_MAX);
2780 if (!MFI->isFixedObjectIndex(FI))
2782 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2785 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2786 /// for tail call optimization. Targets which want to do tail call
2787 /// optimization should implement this function.
2789 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2790 CallingConv::ID CalleeCC,
2792 bool isCalleeStructRet,
2793 bool isCallerStructRet,
2795 const SmallVectorImpl<ISD::OutputArg> &Outs,
2796 const SmallVectorImpl<SDValue> &OutVals,
2797 const SmallVectorImpl<ISD::InputArg> &Ins,
2798 SelectionDAG& DAG) const {
2799 if (!IsTailCallConvention(CalleeCC) &&
2800 CalleeCC != CallingConv::C)
2803 // If -tailcallopt is specified, make fastcc functions tail-callable.
2804 const MachineFunction &MF = DAG.getMachineFunction();
2805 const Function *CallerF = DAG.getMachineFunction().getFunction();
2807 // If the function return type is x86_fp80 and the callee return type is not,
2808 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2809 // perform a tailcall optimization here.
2810 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2813 CallingConv::ID CallerCC = CallerF->getCallingConv();
2814 bool CCMatch = CallerCC == CalleeCC;
2816 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2817 if (IsTailCallConvention(CalleeCC) && CCMatch)
2822 // Look for obvious safe cases to perform tail call optimization that do not
2823 // require ABI changes. This is what gcc calls sibcall.
2825 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2826 // emit a special epilogue.
2827 if (RegInfo->needsStackRealignment(MF))
2830 // Also avoid sibcall optimization if either caller or callee uses struct
2831 // return semantics.
2832 if (isCalleeStructRet || isCallerStructRet)
2835 // An stdcall caller is expected to clean up its arguments; the callee
2836 // isn't going to do that.
2837 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2840 // Do not sibcall optimize vararg calls unless all arguments are passed via
2842 if (isVarArg && !Outs.empty()) {
2844 // Optimizing for varargs on Win64 is unlikely to be safe without
2845 // additional testing.
2846 if (Subtarget->isTargetWin64())
2849 SmallVector<CCValAssign, 16> ArgLocs;
2850 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2851 getTargetMachine(), ArgLocs, *DAG.getContext());
2853 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2854 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2855 if (!ArgLocs[i].isRegLoc())
2859 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2860 // stack. Therefore, if it's not used by the call it is not safe to optimize
2861 // this into a sibcall.
2862 bool Unused = false;
2863 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2870 SmallVector<CCValAssign, 16> RVLocs;
2871 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2872 getTargetMachine(), RVLocs, *DAG.getContext());
2873 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2874 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2875 CCValAssign &VA = RVLocs[i];
2876 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2881 // If the calling conventions do not match, then we'd better make sure the
2882 // results are returned in the same way as what the caller expects.
2884 SmallVector<CCValAssign, 16> RVLocs1;
2885 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2886 getTargetMachine(), RVLocs1, *DAG.getContext());
2887 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2889 SmallVector<CCValAssign, 16> RVLocs2;
2890 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2891 getTargetMachine(), RVLocs2, *DAG.getContext());
2892 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2894 if (RVLocs1.size() != RVLocs2.size())
2896 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2897 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2899 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2901 if (RVLocs1[i].isRegLoc()) {
2902 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2905 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2911 // If the callee takes no arguments then go on to check the results of the
2913 if (!Outs.empty()) {
2914 // Check if stack adjustment is needed. For now, do not do this if any
2915 // argument is passed on the stack.
2916 SmallVector<CCValAssign, 16> ArgLocs;
2917 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2918 getTargetMachine(), ArgLocs, *DAG.getContext());
2920 // Allocate shadow area for Win64
2921 if (Subtarget->isTargetWin64()) {
2922 CCInfo.AllocateStack(32, 8);
2925 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2926 if (CCInfo.getNextStackOffset()) {
2927 MachineFunction &MF = DAG.getMachineFunction();
2928 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2931 // Check if the arguments are already laid out in the right way as
2932 // the caller's fixed stack objects.
2933 MachineFrameInfo *MFI = MF.getFrameInfo();
2934 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2935 const X86InstrInfo *TII =
2936 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2937 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2938 CCValAssign &VA = ArgLocs[i];
2939 SDValue Arg = OutVals[i];
2940 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2941 if (VA.getLocInfo() == CCValAssign::Indirect)
2943 if (!VA.isRegLoc()) {
2944 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2951 // If the tailcall address may be in a register, then make sure it's
2952 // possible to register allocate for it. In 32-bit, the call address can
2953 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2954 // callee-saved registers are restored. These happen to be the same
2955 // registers used to pass 'inreg' arguments so watch out for those.
2956 if (!Subtarget->is64Bit() &&
2957 !isa<GlobalAddressSDNode>(Callee) &&
2958 !isa<ExternalSymbolSDNode>(Callee)) {
2959 unsigned NumInRegs = 0;
2960 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2961 CCValAssign &VA = ArgLocs[i];
2964 unsigned Reg = VA.getLocReg();
2967 case X86::EAX: case X86::EDX: case X86::ECX:
2968 if (++NumInRegs == 3)
2980 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2981 const TargetLibraryInfo *libInfo) const {
2982 return X86::createFastISel(funcInfo, libInfo);
2985 //===----------------------------------------------------------------------===//
2986 // Other Lowering Hooks
2987 //===----------------------------------------------------------------------===//
2989 static bool MayFoldLoad(SDValue Op) {
2990 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2993 static bool MayFoldIntoStore(SDValue Op) {
2994 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2997 static bool isTargetShuffle(unsigned Opcode) {
2999 default: return false;
3000 case X86ISD::PSHUFD:
3001 case X86ISD::PSHUFHW:
3002 case X86ISD::PSHUFLW:
3004 case X86ISD::PALIGN:
3005 case X86ISD::MOVLHPS:
3006 case X86ISD::MOVLHPD:
3007 case X86ISD::MOVHLPS:
3008 case X86ISD::MOVLPS:
3009 case X86ISD::MOVLPD:
3010 case X86ISD::MOVSHDUP:
3011 case X86ISD::MOVSLDUP:
3012 case X86ISD::MOVDDUP:
3015 case X86ISD::UNPCKL:
3016 case X86ISD::UNPCKH:
3017 case X86ISD::VPERMILP:
3018 case X86ISD::VPERM2X128:
3019 case X86ISD::VPERMI:
3024 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3025 SDValue V1, SelectionDAG &DAG) {
3027 default: llvm_unreachable("Unknown x86 shuffle node");
3028 case X86ISD::MOVSHDUP:
3029 case X86ISD::MOVSLDUP:
3030 case X86ISD::MOVDDUP:
3031 return DAG.getNode(Opc, dl, VT, V1);
3035 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3036 SDValue V1, unsigned TargetMask,
3037 SelectionDAG &DAG) {
3039 default: llvm_unreachable("Unknown x86 shuffle node");
3040 case X86ISD::PSHUFD:
3041 case X86ISD::PSHUFHW:
3042 case X86ISD::PSHUFLW:
3043 case X86ISD::VPERMILP:
3044 case X86ISD::VPERMI:
3045 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3049 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3050 SDValue V1, SDValue V2, unsigned TargetMask,
3051 SelectionDAG &DAG) {
3053 default: llvm_unreachable("Unknown x86 shuffle node");
3054 case X86ISD::PALIGN:
3056 case X86ISD::VPERM2X128:
3057 return DAG.getNode(Opc, dl, VT, V1, V2,
3058 DAG.getConstant(TargetMask, MVT::i8));
3062 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3063 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3065 default: llvm_unreachable("Unknown x86 shuffle node");
3066 case X86ISD::MOVLHPS:
3067 case X86ISD::MOVLHPD:
3068 case X86ISD::MOVHLPS:
3069 case X86ISD::MOVLPS:
3070 case X86ISD::MOVLPD:
3073 case X86ISD::UNPCKL:
3074 case X86ISD::UNPCKH:
3075 return DAG.getNode(Opc, dl, VT, V1, V2);
3079 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3080 MachineFunction &MF = DAG.getMachineFunction();
3081 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3082 int ReturnAddrIndex = FuncInfo->getRAIndex();
3084 if (ReturnAddrIndex == 0) {
3085 // Set up a frame object for the return address.
3086 unsigned SlotSize = RegInfo->getSlotSize();
3087 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3089 FuncInfo->setRAIndex(ReturnAddrIndex);
3092 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3095 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3096 bool hasSymbolicDisplacement) {
3097 // Offset should fit into 32 bit immediate field.
3098 if (!isInt<32>(Offset))
3101 // If we don't have a symbolic displacement - we don't have any extra
3103 if (!hasSymbolicDisplacement)
3106 // FIXME: Some tweaks might be needed for medium code model.
3107 if (M != CodeModel::Small && M != CodeModel::Kernel)
3110 // For small code model we assume that latest object is 16MB before end of 31
3111 // bits boundary. We may also accept pretty large negative constants knowing
3112 // that all objects are in the positive half of address space.
3113 if (M == CodeModel::Small && Offset < 16*1024*1024)
3116 // For kernel code model we know that all object resist in the negative half
3117 // of 32bits address space. We may not accept negative offsets, since they may
3118 // be just off and we may accept pretty large positive ones.
3119 if (M == CodeModel::Kernel && Offset > 0)
3125 /// isCalleePop - Determines whether the callee is required to pop its
3126 /// own arguments. Callee pop is necessary to support tail calls.
3127 bool X86::isCalleePop(CallingConv::ID CallingConv,
3128 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3132 switch (CallingConv) {
3135 case CallingConv::X86_StdCall:
3137 case CallingConv::X86_FastCall:
3139 case CallingConv::X86_ThisCall:
3141 case CallingConv::Fast:
3143 case CallingConv::GHC:
3145 case CallingConv::HiPE:
3150 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3151 /// specific condition code, returning the condition code and the LHS/RHS of the
3152 /// comparison to make.
3153 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3154 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3156 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3157 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3158 // X > -1 -> X == 0, jump !sign.
3159 RHS = DAG.getConstant(0, RHS.getValueType());
3160 return X86::COND_NS;
3162 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3163 // X < 0 -> X == 0, jump on sign.
3166 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3168 RHS = DAG.getConstant(0, RHS.getValueType());
3169 return X86::COND_LE;
3173 switch (SetCCOpcode) {
3174 default: llvm_unreachable("Invalid integer condition!");
3175 case ISD::SETEQ: return X86::COND_E;
3176 case ISD::SETGT: return X86::COND_G;
3177 case ISD::SETGE: return X86::COND_GE;
3178 case ISD::SETLT: return X86::COND_L;
3179 case ISD::SETLE: return X86::COND_LE;
3180 case ISD::SETNE: return X86::COND_NE;
3181 case ISD::SETULT: return X86::COND_B;
3182 case ISD::SETUGT: return X86::COND_A;
3183 case ISD::SETULE: return X86::COND_BE;
3184 case ISD::SETUGE: return X86::COND_AE;
3188 // First determine if it is required or is profitable to flip the operands.
3190 // If LHS is a foldable load, but RHS is not, flip the condition.
3191 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3192 !ISD::isNON_EXTLoad(RHS.getNode())) {
3193 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3194 std::swap(LHS, RHS);
3197 switch (SetCCOpcode) {
3203 std::swap(LHS, RHS);
3207 // On a floating point condition, the flags are set as follows:
3209 // 0 | 0 | 0 | X > Y
3210 // 0 | 0 | 1 | X < Y
3211 // 1 | 0 | 0 | X == Y
3212 // 1 | 1 | 1 | unordered
3213 switch (SetCCOpcode) {
3214 default: llvm_unreachable("Condcode should be pre-legalized away");
3216 case ISD::SETEQ: return X86::COND_E;
3217 case ISD::SETOLT: // flipped
3219 case ISD::SETGT: return X86::COND_A;
3220 case ISD::SETOLE: // flipped
3222 case ISD::SETGE: return X86::COND_AE;
3223 case ISD::SETUGT: // flipped
3225 case ISD::SETLT: return X86::COND_B;
3226 case ISD::SETUGE: // flipped
3228 case ISD::SETLE: return X86::COND_BE;
3230 case ISD::SETNE: return X86::COND_NE;
3231 case ISD::SETUO: return X86::COND_P;
3232 case ISD::SETO: return X86::COND_NP;
3234 case ISD::SETUNE: return X86::COND_INVALID;
3238 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3239 /// code. Current x86 isa includes the following FP cmov instructions:
3240 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3241 static bool hasFPCMov(unsigned X86CC) {
3257 /// isFPImmLegal - Returns true if the target can instruction select the
3258 /// specified FP immediate natively. If false, the legalizer will
3259 /// materialize the FP immediate as a load from a constant pool.
3260 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3261 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3262 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3268 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3269 /// the specified range (L, H].
3270 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3271 return (Val < 0) || (Val >= Low && Val < Hi);
3274 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3275 /// specified value.
3276 static bool isUndefOrEqual(int Val, int CmpVal) {
3277 return (Val < 0 || Val == CmpVal);
3280 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3281 /// from position Pos and ending in Pos+Size, falls within the specified
3282 /// sequential range (L, L+Pos]. or is undef.
3283 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3284 unsigned Pos, unsigned Size, int Low) {
3285 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3286 if (!isUndefOrEqual(Mask[i], Low))
3291 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3292 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3293 /// the second operand.
3294 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3295 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3296 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3297 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3298 return (Mask[0] < 2 && Mask[1] < 2);
3302 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3303 /// is suitable for input to PSHUFHW.
3304 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3305 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3308 // Lower quadword copied in order or undef.
3309 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3312 // Upper quadword shuffled.
3313 for (unsigned i = 4; i != 8; ++i)
3314 if (!isUndefOrInRange(Mask[i], 4, 8))
3317 if (VT == MVT::v16i16) {
3318 // Lower quadword copied in order or undef.
3319 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3322 // Upper quadword shuffled.
3323 for (unsigned i = 12; i != 16; ++i)
3324 if (!isUndefOrInRange(Mask[i], 12, 16))
3331 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3332 /// is suitable for input to PSHUFLW.
3333 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3334 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3337 // Upper quadword copied in order.
3338 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3341 // Lower quadword shuffled.
3342 for (unsigned i = 0; i != 4; ++i)
3343 if (!isUndefOrInRange(Mask[i], 0, 4))
3346 if (VT == MVT::v16i16) {
3347 // Upper quadword copied in order.
3348 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3351 // Lower quadword shuffled.
3352 for (unsigned i = 8; i != 12; ++i)
3353 if (!isUndefOrInRange(Mask[i], 8, 12))
3360 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3361 /// is suitable for input to PALIGNR.
3362 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3363 const X86Subtarget *Subtarget) {
3364 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3365 (VT.is256BitVector() && !Subtarget->hasInt256()))
3368 unsigned NumElts = VT.getVectorNumElements();
3369 unsigned NumLanes = VT.getSizeInBits()/128;
3370 unsigned NumLaneElts = NumElts/NumLanes;
3372 // Do not handle 64-bit element shuffles with palignr.
3373 if (NumLaneElts == 2)
3376 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3378 for (i = 0; i != NumLaneElts; ++i) {
3383 // Lane is all undef, go to next lane
3384 if (i == NumLaneElts)
3387 int Start = Mask[i+l];
3389 // Make sure its in this lane in one of the sources
3390 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3391 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3394 // If not lane 0, then we must match lane 0
3395 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3398 // Correct second source to be contiguous with first source
3399 if (Start >= (int)NumElts)
3400 Start -= NumElts - NumLaneElts;
3402 // Make sure we're shifting in the right direction.
3403 if (Start <= (int)(i+l))
3408 // Check the rest of the elements to see if they are consecutive.
3409 for (++i; i != NumLaneElts; ++i) {
3410 int Idx = Mask[i+l];
3412 // Make sure its in this lane
3413 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3414 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3417 // If not lane 0, then we must match lane 0
3418 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3421 if (Idx >= (int)NumElts)
3422 Idx -= NumElts - NumLaneElts;
3424 if (!isUndefOrEqual(Idx, Start+i))
3433 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3434 /// the two vector operands have swapped position.
3435 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3436 unsigned NumElems) {
3437 for (unsigned i = 0; i != NumElems; ++i) {
3441 else if (idx < (int)NumElems)
3442 Mask[i] = idx + NumElems;
3444 Mask[i] = idx - NumElems;
3448 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3449 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3450 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3451 /// reverse of what x86 shuffles want.
3452 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3453 bool Commuted = false) {
3454 if (!HasFp256 && VT.is256BitVector())
3457 unsigned NumElems = VT.getVectorNumElements();
3458 unsigned NumLanes = VT.getSizeInBits()/128;
3459 unsigned NumLaneElems = NumElems/NumLanes;
3461 if (NumLaneElems != 2 && NumLaneElems != 4)
3464 // VSHUFPSY divides the resulting vector into 4 chunks.
3465 // The sources are also splitted into 4 chunks, and each destination
3466 // chunk must come from a different source chunk.
3468 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3469 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3471 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3472 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3474 // VSHUFPDY divides the resulting vector into 4 chunks.
3475 // The sources are also splitted into 4 chunks, and each destination
3476 // chunk must come from a different source chunk.
3478 // SRC1 => X3 X2 X1 X0
3479 // SRC2 => Y3 Y2 Y1 Y0
3481 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3483 unsigned HalfLaneElems = NumLaneElems/2;
3484 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3485 for (unsigned i = 0; i != NumLaneElems; ++i) {
3486 int Idx = Mask[i+l];
3487 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3488 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3490 // For VSHUFPSY, the mask of the second half must be the same as the
3491 // first but with the appropriate offsets. This works in the same way as
3492 // VPERMILPS works with masks.
3493 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3495 if (!isUndefOrEqual(Idx, Mask[i]+l))
3503 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3504 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3505 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3506 if (!VT.is128BitVector())
3509 unsigned NumElems = VT.getVectorNumElements();
3514 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3515 return isUndefOrEqual(Mask[0], 6) &&
3516 isUndefOrEqual(Mask[1], 7) &&
3517 isUndefOrEqual(Mask[2], 2) &&
3518 isUndefOrEqual(Mask[3], 3);
3521 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3522 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3524 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3525 if (!VT.is128BitVector())
3528 unsigned NumElems = VT.getVectorNumElements();
3533 return isUndefOrEqual(Mask[0], 2) &&
3534 isUndefOrEqual(Mask[1], 3) &&
3535 isUndefOrEqual(Mask[2], 2) &&
3536 isUndefOrEqual(Mask[3], 3);
3539 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3540 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3541 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3542 if (!VT.is128BitVector())
3545 unsigned NumElems = VT.getVectorNumElements();
3547 if (NumElems != 2 && NumElems != 4)
3550 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3551 if (!isUndefOrEqual(Mask[i], i + NumElems))
3554 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3555 if (!isUndefOrEqual(Mask[i], i))
3561 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3562 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3563 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3564 if (!VT.is128BitVector())
3567 unsigned NumElems = VT.getVectorNumElements();
3569 if (NumElems != 2 && NumElems != 4)
3572 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3573 if (!isUndefOrEqual(Mask[i], i))
3576 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3577 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3584 // Some special combinations that can be optimized.
3587 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3588 SelectionDAG &DAG) {
3589 MVT VT = SVOp->getValueType(0).getSimpleVT();
3590 DebugLoc dl = SVOp->getDebugLoc();
3592 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3595 ArrayRef<int> Mask = SVOp->getMask();
3597 // These are the special masks that may be optimized.
3598 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3599 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3600 bool MatchEvenMask = true;
3601 bool MatchOddMask = true;
3602 for (int i=0; i<8; ++i) {
3603 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3604 MatchEvenMask = false;
3605 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3606 MatchOddMask = false;
3609 if (!MatchEvenMask && !MatchOddMask)
3612 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3614 SDValue Op0 = SVOp->getOperand(0);
3615 SDValue Op1 = SVOp->getOperand(1);
3617 if (MatchEvenMask) {
3618 // Shift the second operand right to 32 bits.
3619 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3620 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3622 // Shift the first operand left to 32 bits.
3623 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3624 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3626 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3627 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3630 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3631 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3632 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3633 bool HasInt256, bool V2IsSplat = false) {
3634 unsigned NumElts = VT.getVectorNumElements();
3636 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3637 "Unsupported vector type for unpckh");
3639 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3640 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3643 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3644 // independently on 128-bit lanes.
3645 unsigned NumLanes = VT.getSizeInBits()/128;
3646 unsigned NumLaneElts = NumElts/NumLanes;
3648 for (unsigned l = 0; l != NumLanes; ++l) {
3649 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3650 i != (l+1)*NumLaneElts;
3653 int BitI1 = Mask[i+1];
3654 if (!isUndefOrEqual(BitI, j))
3657 if (!isUndefOrEqual(BitI1, NumElts))
3660 if (!isUndefOrEqual(BitI1, j + NumElts))
3669 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3670 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3671 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3672 bool HasInt256, bool V2IsSplat = false) {
3673 unsigned NumElts = VT.getVectorNumElements();
3675 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3676 "Unsupported vector type for unpckh");
3678 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3679 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3682 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3683 // independently on 128-bit lanes.
3684 unsigned NumLanes = VT.getSizeInBits()/128;
3685 unsigned NumLaneElts = NumElts/NumLanes;
3687 for (unsigned l = 0; l != NumLanes; ++l) {
3688 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3689 i != (l+1)*NumLaneElts; i += 2, ++j) {
3691 int BitI1 = Mask[i+1];
3692 if (!isUndefOrEqual(BitI, j))
3695 if (isUndefOrEqual(BitI1, NumElts))
3698 if (!isUndefOrEqual(BitI1, j+NumElts))
3706 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3707 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3709 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3710 unsigned NumElts = VT.getVectorNumElements();
3711 bool Is256BitVec = VT.is256BitVector();
3713 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3714 "Unsupported vector type for unpckh");
3716 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3717 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3720 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3721 // FIXME: Need a better way to get rid of this, there's no latency difference
3722 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3723 // the former later. We should also remove the "_undef" special mask.
3724 if (NumElts == 4 && Is256BitVec)
3727 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3728 // independently on 128-bit lanes.
3729 unsigned NumLanes = VT.getSizeInBits()/128;
3730 unsigned NumLaneElts = NumElts/NumLanes;
3732 for (unsigned l = 0; l != NumLanes; ++l) {
3733 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3734 i != (l+1)*NumLaneElts;
3737 int BitI1 = Mask[i+1];
3739 if (!isUndefOrEqual(BitI, j))
3741 if (!isUndefOrEqual(BitI1, j))
3749 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3750 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3752 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3753 unsigned NumElts = VT.getVectorNumElements();
3755 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3756 "Unsupported vector type for unpckh");
3758 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3759 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3762 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3763 // independently on 128-bit lanes.
3764 unsigned NumLanes = VT.getSizeInBits()/128;
3765 unsigned NumLaneElts = NumElts/NumLanes;
3767 for (unsigned l = 0; l != NumLanes; ++l) {
3768 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3769 i != (l+1)*NumLaneElts; i += 2, ++j) {
3771 int BitI1 = Mask[i+1];
3772 if (!isUndefOrEqual(BitI, j))
3774 if (!isUndefOrEqual(BitI1, j))
3781 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3782 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3783 /// MOVSD, and MOVD, i.e. setting the lowest element.
3784 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3785 if (VT.getVectorElementType().getSizeInBits() < 32)
3787 if (!VT.is128BitVector())
3790 unsigned NumElts = VT.getVectorNumElements();
3792 if (!isUndefOrEqual(Mask[0], NumElts))
3795 for (unsigned i = 1; i != NumElts; ++i)
3796 if (!isUndefOrEqual(Mask[i], i))
3802 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3803 /// as permutations between 128-bit chunks or halves. As an example: this
3805 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3806 /// The first half comes from the second half of V1 and the second half from the
3807 /// the second half of V2.
3808 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3809 if (!HasFp256 || !VT.is256BitVector())
3812 // The shuffle result is divided into half A and half B. In total the two
3813 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3814 // B must come from C, D, E or F.
3815 unsigned HalfSize = VT.getVectorNumElements()/2;
3816 bool MatchA = false, MatchB = false;
3818 // Check if A comes from one of C, D, E, F.
3819 for (unsigned Half = 0; Half != 4; ++Half) {
3820 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3826 // Check if B comes from one of C, D, E, F.
3827 for (unsigned Half = 0; Half != 4; ++Half) {
3828 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3834 return MatchA && MatchB;
3837 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3838 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3839 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3840 MVT VT = SVOp->getValueType(0).getSimpleVT();
3842 unsigned HalfSize = VT.getVectorNumElements()/2;
3844 unsigned FstHalf = 0, SndHalf = 0;
3845 for (unsigned i = 0; i < HalfSize; ++i) {
3846 if (SVOp->getMaskElt(i) > 0) {
3847 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3851 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3852 if (SVOp->getMaskElt(i) > 0) {
3853 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3858 return (FstHalf | (SndHalf << 4));
3861 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3862 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3863 /// Note that VPERMIL mask matching is different depending whether theunderlying
3864 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3865 /// to the same elements of the low, but to the higher half of the source.
3866 /// In VPERMILPD the two lanes could be shuffled independently of each other
3867 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3868 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3872 unsigned NumElts = VT.getVectorNumElements();
3873 // Only match 256-bit with 32/64-bit types
3874 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3877 unsigned NumLanes = VT.getSizeInBits()/128;
3878 unsigned LaneSize = NumElts/NumLanes;
3879 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3880 for (unsigned i = 0; i != LaneSize; ++i) {
3881 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3883 if (NumElts != 8 || l == 0)
3885 // VPERMILPS handling
3888 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3896 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3897 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3898 /// element of vector 2 and the other elements to come from vector 1 in order.
3899 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3900 bool V2IsSplat = false, bool V2IsUndef = false) {
3901 if (!VT.is128BitVector())
3904 unsigned NumOps = VT.getVectorNumElements();
3905 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3908 if (!isUndefOrEqual(Mask[0], 0))
3911 for (unsigned i = 1; i != NumOps; ++i)
3912 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3913 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3914 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3920 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3921 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3922 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3923 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3924 const X86Subtarget *Subtarget) {
3925 if (!Subtarget->hasSSE3())
3928 unsigned NumElems = VT.getVectorNumElements();
3930 if ((VT.is128BitVector() && NumElems != 4) ||
3931 (VT.is256BitVector() && NumElems != 8))
3934 // "i+1" is the value the indexed mask element must have
3935 for (unsigned i = 0; i != NumElems; i += 2)
3936 if (!isUndefOrEqual(Mask[i], i+1) ||
3937 !isUndefOrEqual(Mask[i+1], i+1))
3943 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3945 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3946 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3947 const X86Subtarget *Subtarget) {
3948 if (!Subtarget->hasSSE3())
3951 unsigned NumElems = VT.getVectorNumElements();
3953 if ((VT.is128BitVector() && NumElems != 4) ||
3954 (VT.is256BitVector() && NumElems != 8))
3957 // "i" is the value the indexed mask element must have
3958 for (unsigned i = 0; i != NumElems; i += 2)
3959 if (!isUndefOrEqual(Mask[i], i) ||
3960 !isUndefOrEqual(Mask[i+1], i))
3966 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3967 /// specifies a shuffle of elements that is suitable for input to 256-bit
3968 /// version of MOVDDUP.
3969 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3970 if (!HasFp256 || !VT.is256BitVector())
3973 unsigned NumElts = VT.getVectorNumElements();
3977 for (unsigned i = 0; i != NumElts/2; ++i)
3978 if (!isUndefOrEqual(Mask[i], 0))
3980 for (unsigned i = NumElts/2; i != NumElts; ++i)
3981 if (!isUndefOrEqual(Mask[i], NumElts/2))
3986 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3987 /// specifies a shuffle of elements that is suitable for input to 128-bit
3988 /// version of MOVDDUP.
3989 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3990 if (!VT.is128BitVector())
3993 unsigned e = VT.getVectorNumElements() / 2;
3994 for (unsigned i = 0; i != e; ++i)
3995 if (!isUndefOrEqual(Mask[i], i))
3997 for (unsigned i = 0; i != e; ++i)
3998 if (!isUndefOrEqual(Mask[e+i], i))
4003 /// isVEXTRACTF128Index - Return true if the specified
4004 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4005 /// suitable for input to VEXTRACTF128.
4006 bool X86::isVEXTRACTF128Index(SDNode *N) {
4007 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4010 // The index should be aligned on a 128-bit boundary.
4012 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4014 MVT VT = N->getValueType(0).getSimpleVT();
4015 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4016 bool Result = (Index * ElSize) % 128 == 0;
4021 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4022 /// operand specifies a subvector insert that is suitable for input to
4024 bool X86::isVINSERTF128Index(SDNode *N) {
4025 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4028 // The index should be aligned on a 128-bit boundary.
4030 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4032 MVT VT = N->getValueType(0).getSimpleVT();
4033 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4034 bool Result = (Index * ElSize) % 128 == 0;
4039 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4040 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4041 /// Handles 128-bit and 256-bit.
4042 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4043 MVT VT = N->getValueType(0).getSimpleVT();
4045 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4046 "Unsupported vector type for PSHUF/SHUFP");
4048 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4049 // independently on 128-bit lanes.
4050 unsigned NumElts = VT.getVectorNumElements();
4051 unsigned NumLanes = VT.getSizeInBits()/128;
4052 unsigned NumLaneElts = NumElts/NumLanes;
4054 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4055 "Only supports 2 or 4 elements per lane");
4057 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4059 for (unsigned i = 0; i != NumElts; ++i) {
4060 int Elt = N->getMaskElt(i);
4061 if (Elt < 0) continue;
4062 Elt &= NumLaneElts - 1;
4063 unsigned ShAmt = (i << Shift) % 8;
4064 Mask |= Elt << ShAmt;
4070 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4071 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4072 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4073 MVT VT = N->getValueType(0).getSimpleVT();
4075 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4076 "Unsupported vector type for PSHUFHW");
4078 unsigned NumElts = VT.getVectorNumElements();
4081 for (unsigned l = 0; l != NumElts; l += 8) {
4082 // 8 nodes per lane, but we only care about the last 4.
4083 for (unsigned i = 0; i < 4; ++i) {
4084 int Elt = N->getMaskElt(l+i+4);
4085 if (Elt < 0) continue;
4086 Elt &= 0x3; // only 2-bits.
4087 Mask |= Elt << (i * 2);
4094 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4095 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4096 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4097 MVT VT = N->getValueType(0).getSimpleVT();
4099 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4100 "Unsupported vector type for PSHUFHW");
4102 unsigned NumElts = VT.getVectorNumElements();
4105 for (unsigned l = 0; l != NumElts; l += 8) {
4106 // 8 nodes per lane, but we only care about the first 4.
4107 for (unsigned i = 0; i < 4; ++i) {
4108 int Elt = N->getMaskElt(l+i);
4109 if (Elt < 0) continue;
4110 Elt &= 0x3; // only 2-bits
4111 Mask |= Elt << (i * 2);
4118 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4119 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4120 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4121 MVT VT = SVOp->getValueType(0).getSimpleVT();
4122 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4124 unsigned NumElts = VT.getVectorNumElements();
4125 unsigned NumLanes = VT.getSizeInBits()/128;
4126 unsigned NumLaneElts = NumElts/NumLanes;
4130 for (i = 0; i != NumElts; ++i) {
4131 Val = SVOp->getMaskElt(i);
4135 if (Val >= (int)NumElts)
4136 Val -= NumElts - NumLaneElts;
4138 assert(Val - i > 0 && "PALIGNR imm should be positive");
4139 return (Val - i) * EltSize;
4142 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4143 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4145 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4146 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4147 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4150 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4152 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4153 MVT ElVT = VecVT.getVectorElementType();
4155 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4156 return Index / NumElemsPerChunk;
4159 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4160 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4162 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4163 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4164 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4167 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4169 MVT VecVT = N->getValueType(0).getSimpleVT();
4170 MVT ElVT = VecVT.getVectorElementType();
4172 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4173 return Index / NumElemsPerChunk;
4176 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4177 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4178 /// Handles 256-bit.
4179 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4180 MVT VT = N->getValueType(0).getSimpleVT();
4182 unsigned NumElts = VT.getVectorNumElements();
4184 assert((VT.is256BitVector() && NumElts == 4) &&
4185 "Unsupported vector type for VPERMQ/VPERMPD");
4188 for (unsigned i = 0; i != NumElts; ++i) {
4189 int Elt = N->getMaskElt(i);
4192 Mask |= Elt << (i*2);
4197 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4199 bool X86::isZeroNode(SDValue Elt) {
4200 return ((isa<ConstantSDNode>(Elt) &&
4201 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4202 (isa<ConstantFPSDNode>(Elt) &&
4203 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4206 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4207 /// their permute mask.
4208 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4209 SelectionDAG &DAG) {
4210 MVT VT = SVOp->getValueType(0).getSimpleVT();
4211 unsigned NumElems = VT.getVectorNumElements();
4212 SmallVector<int, 8> MaskVec;
4214 for (unsigned i = 0; i != NumElems; ++i) {
4215 int Idx = SVOp->getMaskElt(i);
4217 if (Idx < (int)NumElems)
4222 MaskVec.push_back(Idx);
4224 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4225 SVOp->getOperand(0), &MaskVec[0]);
4228 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4229 /// match movhlps. The lower half elements should come from upper half of
4230 /// V1 (and in order), and the upper half elements should come from the upper
4231 /// half of V2 (and in order).
4232 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4233 if (!VT.is128BitVector())
4235 if (VT.getVectorNumElements() != 4)
4237 for (unsigned i = 0, e = 2; i != e; ++i)
4238 if (!isUndefOrEqual(Mask[i], i+2))
4240 for (unsigned i = 2; i != 4; ++i)
4241 if (!isUndefOrEqual(Mask[i], i+4))
4246 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4247 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4249 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4250 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4252 N = N->getOperand(0).getNode();
4253 if (!ISD::isNON_EXTLoad(N))
4256 *LD = cast<LoadSDNode>(N);
4260 // Test whether the given value is a vector value which will be legalized
4262 static bool WillBeConstantPoolLoad(SDNode *N) {
4263 if (N->getOpcode() != ISD::BUILD_VECTOR)
4266 // Check for any non-constant elements.
4267 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4268 switch (N->getOperand(i).getNode()->getOpcode()) {
4270 case ISD::ConstantFP:
4277 // Vectors of all-zeros and all-ones are materialized with special
4278 // instructions rather than being loaded.
4279 return !ISD::isBuildVectorAllZeros(N) &&
4280 !ISD::isBuildVectorAllOnes(N);
4283 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4284 /// match movlp{s|d}. The lower half elements should come from lower half of
4285 /// V1 (and in order), and the upper half elements should come from the upper
4286 /// half of V2 (and in order). And since V1 will become the source of the
4287 /// MOVLP, it must be either a vector load or a scalar load to vector.
4288 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4289 ArrayRef<int> Mask, EVT VT) {
4290 if (!VT.is128BitVector())
4293 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4295 // Is V2 is a vector load, don't do this transformation. We will try to use
4296 // load folding shufps op.
4297 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4300 unsigned NumElems = VT.getVectorNumElements();
4302 if (NumElems != 2 && NumElems != 4)
4304 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4305 if (!isUndefOrEqual(Mask[i], i))
4307 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4308 if (!isUndefOrEqual(Mask[i], i+NumElems))
4313 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4315 static bool isSplatVector(SDNode *N) {
4316 if (N->getOpcode() != ISD::BUILD_VECTOR)
4319 SDValue SplatValue = N->getOperand(0);
4320 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4321 if (N->getOperand(i) != SplatValue)
4326 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4327 /// to an zero vector.
4328 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4329 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4330 SDValue V1 = N->getOperand(0);
4331 SDValue V2 = N->getOperand(1);
4332 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4333 for (unsigned i = 0; i != NumElems; ++i) {
4334 int Idx = N->getMaskElt(i);
4335 if (Idx >= (int)NumElems) {
4336 unsigned Opc = V2.getOpcode();
4337 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4339 if (Opc != ISD::BUILD_VECTOR ||
4340 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4342 } else if (Idx >= 0) {
4343 unsigned Opc = V1.getOpcode();
4344 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4346 if (Opc != ISD::BUILD_VECTOR ||
4347 !X86::isZeroNode(V1.getOperand(Idx)))
4354 /// getZeroVector - Returns a vector of specified type with all zero elements.
4356 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4357 SelectionDAG &DAG, DebugLoc dl) {
4358 assert(VT.isVector() && "Expected a vector type");
4360 // Always build SSE zero vectors as <4 x i32> bitcasted
4361 // to their dest type. This ensures they get CSE'd.
4363 if (VT.is128BitVector()) { // SSE
4364 if (Subtarget->hasSSE2()) { // SSE2
4365 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4366 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4368 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4369 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4371 } else if (VT.is256BitVector()) { // AVX
4372 if (Subtarget->hasInt256()) { // AVX2
4373 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4374 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4375 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4377 // 256-bit logic and arithmetic instructions in AVX are all
4378 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4379 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4380 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4381 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4384 llvm_unreachable("Unexpected vector type");
4386 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4389 /// getOnesVector - Returns a vector of specified type with all bits set.
4390 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4391 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4392 /// Then bitcast to their original type, ensuring they get CSE'd.
4393 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4395 assert(VT.isVector() && "Expected a vector type");
4397 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4399 if (VT.is256BitVector()) {
4400 if (HasInt256) { // AVX2
4401 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4402 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4404 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4405 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4407 } else if (VT.is128BitVector()) {
4408 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4410 llvm_unreachable("Unexpected vector type");
4412 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4415 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4416 /// that point to V2 points to its first element.
4417 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4418 for (unsigned i = 0; i != NumElems; ++i) {
4419 if (Mask[i] > (int)NumElems) {
4425 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4426 /// operation of specified width.
4427 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4429 unsigned NumElems = VT.getVectorNumElements();
4430 SmallVector<int, 8> Mask;
4431 Mask.push_back(NumElems);
4432 for (unsigned i = 1; i != NumElems; ++i)
4434 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4437 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4438 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4440 unsigned NumElems = VT.getVectorNumElements();
4441 SmallVector<int, 8> Mask;
4442 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4444 Mask.push_back(i + NumElems);
4446 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4449 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4450 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4452 unsigned NumElems = VT.getVectorNumElements();
4453 SmallVector<int, 8> Mask;
4454 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4455 Mask.push_back(i + Half);
4456 Mask.push_back(i + NumElems + Half);
4458 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4461 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4462 // a generic shuffle instruction because the target has no such instructions.
4463 // Generate shuffles which repeat i16 and i8 several times until they can be
4464 // represented by v4f32 and then be manipulated by target suported shuffles.
4465 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4466 EVT VT = V.getValueType();
4467 int NumElems = VT.getVectorNumElements();
4468 DebugLoc dl = V.getDebugLoc();
4470 while (NumElems > 4) {
4471 if (EltNo < NumElems/2) {
4472 V = getUnpackl(DAG, dl, VT, V, V);
4474 V = getUnpackh(DAG, dl, VT, V, V);
4475 EltNo -= NumElems/2;
4482 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4483 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4484 EVT VT = V.getValueType();
4485 DebugLoc dl = V.getDebugLoc();
4487 if (VT.is128BitVector()) {
4488 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4489 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4490 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4492 } else if (VT.is256BitVector()) {
4493 // To use VPERMILPS to splat scalars, the second half of indicies must
4494 // refer to the higher part, which is a duplication of the lower one,
4495 // because VPERMILPS can only handle in-lane permutations.
4496 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4497 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4499 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4500 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4503 llvm_unreachable("Vector size not supported");
4505 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4508 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4509 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4510 EVT SrcVT = SV->getValueType(0);
4511 SDValue V1 = SV->getOperand(0);
4512 DebugLoc dl = SV->getDebugLoc();
4514 int EltNo = SV->getSplatIndex();
4515 int NumElems = SrcVT.getVectorNumElements();
4516 bool Is256BitVec = SrcVT.is256BitVector();
4518 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4519 "Unknown how to promote splat for type");
4521 // Extract the 128-bit part containing the splat element and update
4522 // the splat element index when it refers to the higher register.
4524 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4525 if (EltNo >= NumElems/2)
4526 EltNo -= NumElems/2;
4529 // All i16 and i8 vector types can't be used directly by a generic shuffle
4530 // instruction because the target has no such instruction. Generate shuffles
4531 // which repeat i16 and i8 several times until they fit in i32, and then can
4532 // be manipulated by target suported shuffles.
4533 EVT EltVT = SrcVT.getVectorElementType();
4534 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4535 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4537 // Recreate the 256-bit vector and place the same 128-bit vector
4538 // into the low and high part. This is necessary because we want
4539 // to use VPERM* to shuffle the vectors
4541 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4544 return getLegalSplat(DAG, V1, EltNo);
4547 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4548 /// vector of zero or undef vector. This produces a shuffle where the low
4549 /// element of V2 is swizzled into the zero/undef vector, landing at element
4550 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4551 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4553 const X86Subtarget *Subtarget,
4554 SelectionDAG &DAG) {
4555 EVT VT = V2.getValueType();
4557 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4558 unsigned NumElems = VT.getVectorNumElements();
4559 SmallVector<int, 16> MaskVec;
4560 for (unsigned i = 0; i != NumElems; ++i)
4561 // If this is the insertion idx, put the low elt of V2 here.
4562 MaskVec.push_back(i == Idx ? NumElems : i);
4563 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4566 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4567 /// target specific opcode. Returns true if the Mask could be calculated.
4568 /// Sets IsUnary to true if only uses one source.
4569 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4570 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4571 unsigned NumElems = VT.getVectorNumElements();
4575 switch(N->getOpcode()) {
4577 ImmN = N->getOperand(N->getNumOperands()-1);
4578 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4580 case X86ISD::UNPCKH:
4581 DecodeUNPCKHMask(VT, Mask);
4583 case X86ISD::UNPCKL:
4584 DecodeUNPCKLMask(VT, Mask);
4586 case X86ISD::MOVHLPS:
4587 DecodeMOVHLPSMask(NumElems, Mask);
4589 case X86ISD::MOVLHPS:
4590 DecodeMOVLHPSMask(NumElems, Mask);
4592 case X86ISD::PSHUFD:
4593 case X86ISD::VPERMILP:
4594 ImmN = N->getOperand(N->getNumOperands()-1);
4595 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4598 case X86ISD::PSHUFHW:
4599 ImmN = N->getOperand(N->getNumOperands()-1);
4600 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4603 case X86ISD::PSHUFLW:
4604 ImmN = N->getOperand(N->getNumOperands()-1);
4605 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4608 case X86ISD::VPERMI:
4609 ImmN = N->getOperand(N->getNumOperands()-1);
4610 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4614 case X86ISD::MOVSD: {
4615 // The index 0 always comes from the first element of the second source,
4616 // this is why MOVSS and MOVSD are used in the first place. The other
4617 // elements come from the other positions of the first source vector
4618 Mask.push_back(NumElems);
4619 for (unsigned i = 1; i != NumElems; ++i) {
4624 case X86ISD::VPERM2X128:
4625 ImmN = N->getOperand(N->getNumOperands()-1);
4626 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4627 if (Mask.empty()) return false;
4629 case X86ISD::MOVDDUP:
4630 case X86ISD::MOVLHPD:
4631 case X86ISD::MOVLPD:
4632 case X86ISD::MOVLPS:
4633 case X86ISD::MOVSHDUP:
4634 case X86ISD::MOVSLDUP:
4635 case X86ISD::PALIGN:
4636 // Not yet implemented
4638 default: llvm_unreachable("unknown target shuffle node");
4644 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4645 /// element of the result of the vector shuffle.
4646 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4649 return SDValue(); // Limit search depth.
4651 SDValue V = SDValue(N, 0);
4652 EVT VT = V.getValueType();
4653 unsigned Opcode = V.getOpcode();
4655 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4656 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4657 int Elt = SV->getMaskElt(Index);
4660 return DAG.getUNDEF(VT.getVectorElementType());
4662 unsigned NumElems = VT.getVectorNumElements();
4663 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4664 : SV->getOperand(1);
4665 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4668 // Recurse into target specific vector shuffles to find scalars.
4669 if (isTargetShuffle(Opcode)) {
4670 MVT ShufVT = V.getValueType().getSimpleVT();
4671 unsigned NumElems = ShufVT.getVectorNumElements();
4672 SmallVector<int, 16> ShuffleMask;
4675 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4678 int Elt = ShuffleMask[Index];
4680 return DAG.getUNDEF(ShufVT.getVectorElementType());
4682 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4684 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4688 // Actual nodes that may contain scalar elements
4689 if (Opcode == ISD::BITCAST) {
4690 V = V.getOperand(0);
4691 EVT SrcVT = V.getValueType();
4692 unsigned NumElems = VT.getVectorNumElements();
4694 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4698 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4699 return (Index == 0) ? V.getOperand(0)
4700 : DAG.getUNDEF(VT.getVectorElementType());
4702 if (V.getOpcode() == ISD::BUILD_VECTOR)
4703 return V.getOperand(Index);
4708 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4709 /// shuffle operation which come from a consecutively from a zero. The
4710 /// search can start in two different directions, from left or right.
4712 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4713 bool ZerosFromLeft, SelectionDAG &DAG) {
4715 for (i = 0; i != NumElems; ++i) {
4716 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4717 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4718 if (!(Elt.getNode() &&
4719 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4726 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4727 /// correspond consecutively to elements from one of the vector operands,
4728 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4730 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4731 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4732 unsigned NumElems, unsigned &OpNum) {
4733 bool SeenV1 = false;
4734 bool SeenV2 = false;
4736 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4737 int Idx = SVOp->getMaskElt(i);
4738 // Ignore undef indicies
4742 if (Idx < (int)NumElems)
4747 // Only accept consecutive elements from the same vector
4748 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4752 OpNum = SeenV1 ? 0 : 1;
4756 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4757 /// logical left shift of a vector.
4758 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4759 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4760 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4761 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4762 false /* check zeros from right */, DAG);
4768 // Considering the elements in the mask that are not consecutive zeros,
4769 // check if they consecutively come from only one of the source vectors.
4771 // V1 = {X, A, B, C} 0
4773 // vector_shuffle V1, V2 <1, 2, 3, X>
4775 if (!isShuffleMaskConsecutive(SVOp,
4776 0, // Mask Start Index
4777 NumElems-NumZeros, // Mask End Index(exclusive)
4778 NumZeros, // Where to start looking in the src vector
4779 NumElems, // Number of elements in vector
4780 OpSrc)) // Which source operand ?
4785 ShVal = SVOp->getOperand(OpSrc);
4789 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4790 /// logical left shift of a vector.
4791 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4792 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4793 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4794 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4795 true /* check zeros from left */, DAG);
4801 // Considering the elements in the mask that are not consecutive zeros,
4802 // check if they consecutively come from only one of the source vectors.
4804 // 0 { A, B, X, X } = V2
4806 // vector_shuffle V1, V2 <X, X, 4, 5>
4808 if (!isShuffleMaskConsecutive(SVOp,
4809 NumZeros, // Mask Start Index
4810 NumElems, // Mask End Index(exclusive)
4811 0, // Where to start looking in the src vector
4812 NumElems, // Number of elements in vector
4813 OpSrc)) // Which source operand ?
4818 ShVal = SVOp->getOperand(OpSrc);
4822 /// isVectorShift - Returns true if the shuffle can be implemented as a
4823 /// logical left or right shift of a vector.
4824 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4825 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4826 // Although the logic below support any bitwidth size, there are no
4827 // shift instructions which handle more than 128-bit vectors.
4828 if (!SVOp->getValueType(0).is128BitVector())
4831 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4832 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4838 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4840 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4841 unsigned NumNonZero, unsigned NumZero,
4843 const X86Subtarget* Subtarget,
4844 const TargetLowering &TLI) {
4848 DebugLoc dl = Op.getDebugLoc();
4851 for (unsigned i = 0; i < 16; ++i) {
4852 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4853 if (ThisIsNonZero && First) {
4855 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4857 V = DAG.getUNDEF(MVT::v8i16);
4862 SDValue ThisElt(0, 0), LastElt(0, 0);
4863 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4864 if (LastIsNonZero) {
4865 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4866 MVT::i16, Op.getOperand(i-1));
4868 if (ThisIsNonZero) {
4869 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4870 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4871 ThisElt, DAG.getConstant(8, MVT::i8));
4873 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4877 if (ThisElt.getNode())
4878 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4879 DAG.getIntPtrConstant(i/2));
4883 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4886 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4888 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4889 unsigned NumNonZero, unsigned NumZero,
4891 const X86Subtarget* Subtarget,
4892 const TargetLowering &TLI) {
4896 DebugLoc dl = Op.getDebugLoc();
4899 for (unsigned i = 0; i < 8; ++i) {
4900 bool isNonZero = (NonZeros & (1 << i)) != 0;
4904 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4906 V = DAG.getUNDEF(MVT::v8i16);
4909 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4910 MVT::v8i16, V, Op.getOperand(i),
4911 DAG.getIntPtrConstant(i));
4918 /// getVShift - Return a vector logical shift node.
4920 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4921 unsigned NumBits, SelectionDAG &DAG,
4922 const TargetLowering &TLI, DebugLoc dl) {
4923 assert(VT.is128BitVector() && "Unknown type for VShift");
4924 EVT ShVT = MVT::v2i64;
4925 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4926 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4927 return DAG.getNode(ISD::BITCAST, dl, VT,
4928 DAG.getNode(Opc, dl, ShVT, SrcOp,
4929 DAG.getConstant(NumBits,
4930 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4934 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4935 SelectionDAG &DAG) const {
4937 // Check if the scalar load can be widened into a vector load. And if
4938 // the address is "base + cst" see if the cst can be "absorbed" into
4939 // the shuffle mask.
4940 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4941 SDValue Ptr = LD->getBasePtr();
4942 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4944 EVT PVT = LD->getValueType(0);
4945 if (PVT != MVT::i32 && PVT != MVT::f32)
4950 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4951 FI = FINode->getIndex();
4953 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4954 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4955 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4956 Offset = Ptr.getConstantOperandVal(1);
4957 Ptr = Ptr.getOperand(0);
4962 // FIXME: 256-bit vector instructions don't require a strict alignment,
4963 // improve this code to support it better.
4964 unsigned RequiredAlign = VT.getSizeInBits()/8;
4965 SDValue Chain = LD->getChain();
4966 // Make sure the stack object alignment is at least 16 or 32.
4967 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4968 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4969 if (MFI->isFixedObjectIndex(FI)) {
4970 // Can't change the alignment. FIXME: It's possible to compute
4971 // the exact stack offset and reference FI + adjust offset instead.
4972 // If someone *really* cares about this. That's the way to implement it.
4975 MFI->setObjectAlignment(FI, RequiredAlign);
4979 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4980 // Ptr + (Offset & ~15).
4983 if ((Offset % RequiredAlign) & 3)
4985 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4987 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4988 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4990 int EltNo = (Offset - StartOffset) >> 2;
4991 unsigned NumElems = VT.getVectorNumElements();
4993 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4994 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4995 LD->getPointerInfo().getWithOffset(StartOffset),
4996 false, false, false, 0);
4998 SmallVector<int, 8> Mask;
4999 for (unsigned i = 0; i != NumElems; ++i)
5000 Mask.push_back(EltNo);
5002 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5008 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5009 /// vector of type 'VT', see if the elements can be replaced by a single large
5010 /// load which has the same value as a build_vector whose operands are 'elts'.
5012 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5014 /// FIXME: we'd also like to handle the case where the last elements are zero
5015 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5016 /// There's even a handy isZeroNode for that purpose.
5017 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5018 DebugLoc &DL, SelectionDAG &DAG) {
5019 EVT EltVT = VT.getVectorElementType();
5020 unsigned NumElems = Elts.size();
5022 LoadSDNode *LDBase = NULL;
5023 unsigned LastLoadedElt = -1U;
5025 // For each element in the initializer, see if we've found a load or an undef.
5026 // If we don't find an initial load element, or later load elements are
5027 // non-consecutive, bail out.
5028 for (unsigned i = 0; i < NumElems; ++i) {
5029 SDValue Elt = Elts[i];
5031 if (!Elt.getNode() ||
5032 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5035 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5037 LDBase = cast<LoadSDNode>(Elt.getNode());
5041 if (Elt.getOpcode() == ISD::UNDEF)
5044 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5045 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5050 // If we have found an entire vector of loads and undefs, then return a large
5051 // load of the entire vector width starting at the base pointer. If we found
5052 // consecutive loads for the low half, generate a vzext_load node.
5053 if (LastLoadedElt == NumElems - 1) {
5054 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5055 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5056 LDBase->getPointerInfo(),
5057 LDBase->isVolatile(), LDBase->isNonTemporal(),
5058 LDBase->isInvariant(), 0);
5059 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5060 LDBase->getPointerInfo(),
5061 LDBase->isVolatile(), LDBase->isNonTemporal(),
5062 LDBase->isInvariant(), LDBase->getAlignment());
5064 if (NumElems == 4 && LastLoadedElt == 1 &&
5065 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5066 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5067 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5069 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5070 LDBase->getPointerInfo(),
5071 LDBase->getAlignment(),
5072 false/*isVolatile*/, true/*ReadMem*/,
5075 // Make sure the newly-created LOAD is in the same position as LDBase in
5076 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5077 // update uses of LDBase's output chain to use the TokenFactor.
5078 if (LDBase->hasAnyUseOfValue(1)) {
5079 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5080 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5081 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5082 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5083 SDValue(ResNode.getNode(), 1));
5086 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5091 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5092 /// to generate a splat value for the following cases:
5093 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5094 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5095 /// a scalar load, or a constant.
5096 /// The VBROADCAST node is returned when a pattern is found,
5097 /// or SDValue() otherwise.
5099 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5100 if (!Subtarget->hasFp256())
5103 MVT VT = Op.getValueType().getSimpleVT();
5104 DebugLoc dl = Op.getDebugLoc();
5106 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5107 "Unsupported vector type for broadcast.");
5112 switch (Op.getOpcode()) {
5114 // Unknown pattern found.
5117 case ISD::BUILD_VECTOR: {
5118 // The BUILD_VECTOR node must be a splat.
5119 if (!isSplatVector(Op.getNode()))
5122 Ld = Op.getOperand(0);
5123 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5124 Ld.getOpcode() == ISD::ConstantFP);
5126 // The suspected load node has several users. Make sure that all
5127 // of its users are from the BUILD_VECTOR node.
5128 // Constants may have multiple users.
5129 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5134 case ISD::VECTOR_SHUFFLE: {
5135 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5137 // Shuffles must have a splat mask where the first element is
5139 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5142 SDValue Sc = Op.getOperand(0);
5143 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5144 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5146 if (!Subtarget->hasInt256())
5149 // Use the register form of the broadcast instruction available on AVX2.
5150 if (VT.is256BitVector())
5151 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5152 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5155 Ld = Sc.getOperand(0);
5156 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5157 Ld.getOpcode() == ISD::ConstantFP);
5159 // The scalar_to_vector node and the suspected
5160 // load node must have exactly one user.
5161 // Constants may have multiple users.
5162 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5168 bool Is256 = VT.is256BitVector();
5170 // Handle the broadcasting a single constant scalar from the constant pool
5171 // into a vector. On Sandybridge it is still better to load a constant vector
5172 // from the constant pool and not to broadcast it from a scalar.
5173 if (ConstSplatVal && Subtarget->hasInt256()) {
5174 EVT CVT = Ld.getValueType();
5175 assert(!CVT.isVector() && "Must not broadcast a vector type");
5176 unsigned ScalarSize = CVT.getSizeInBits();
5178 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5179 const Constant *C = 0;
5180 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5181 C = CI->getConstantIntValue();
5182 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5183 C = CF->getConstantFPValue();
5185 assert(C && "Invalid constant type");
5187 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5188 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5189 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5190 MachinePointerInfo::getConstantPool(),
5191 false, false, false, Alignment);
5193 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5197 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5198 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5200 // Handle AVX2 in-register broadcasts.
5201 if (!IsLoad && Subtarget->hasInt256() &&
5202 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5203 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5205 // The scalar source must be a normal load.
5209 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5210 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5212 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5213 // double since there is no vbroadcastsd xmm
5214 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5215 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5216 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5219 // Unsupported broadcast.
5224 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5225 EVT VT = Op.getValueType();
5227 // Skip if insert_vec_elt is not supported.
5228 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5231 DebugLoc DL = Op.getDebugLoc();
5232 unsigned NumElems = Op.getNumOperands();
5236 SmallVector<unsigned, 4> InsertIndices;
5237 SmallVector<int, 8> Mask(NumElems, -1);
5239 for (unsigned i = 0; i != NumElems; ++i) {
5240 unsigned Opc = Op.getOperand(i).getOpcode();
5242 if (Opc == ISD::UNDEF)
5245 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5246 // Quit if more than 1 elements need inserting.
5247 if (InsertIndices.size() > 1)
5250 InsertIndices.push_back(i);
5254 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5255 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5257 // Quit if extracted from vector of different type.
5258 if (ExtractedFromVec.getValueType() != VT)
5261 // Quit if non-constant index.
5262 if (!isa<ConstantSDNode>(ExtIdx))
5265 if (VecIn1.getNode() == 0)
5266 VecIn1 = ExtractedFromVec;
5267 else if (VecIn1 != ExtractedFromVec) {
5268 if (VecIn2.getNode() == 0)
5269 VecIn2 = ExtractedFromVec;
5270 else if (VecIn2 != ExtractedFromVec)
5271 // Quit if more than 2 vectors to shuffle
5275 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5277 if (ExtractedFromVec == VecIn1)
5279 else if (ExtractedFromVec == VecIn2)
5280 Mask[i] = Idx + NumElems;
5283 if (VecIn1.getNode() == 0)
5286 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5287 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5288 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5289 unsigned Idx = InsertIndices[i];
5290 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5291 DAG.getIntPtrConstant(Idx));
5298 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5299 DebugLoc dl = Op.getDebugLoc();
5301 MVT VT = Op.getValueType().getSimpleVT();
5302 MVT ExtVT = VT.getVectorElementType();
5303 unsigned NumElems = Op.getNumOperands();
5305 // Vectors containing all zeros can be matched by pxor and xorps later
5306 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5307 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5308 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5309 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5312 return getZeroVector(VT, Subtarget, DAG, dl);
5315 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5316 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5317 // vpcmpeqd on 256-bit vectors.
5318 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5319 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5322 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5325 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5326 if (Broadcast.getNode())
5329 unsigned EVTBits = ExtVT.getSizeInBits();
5331 unsigned NumZero = 0;
5332 unsigned NumNonZero = 0;
5333 unsigned NonZeros = 0;
5334 bool IsAllConstants = true;
5335 SmallSet<SDValue, 8> Values;
5336 for (unsigned i = 0; i < NumElems; ++i) {
5337 SDValue Elt = Op.getOperand(i);
5338 if (Elt.getOpcode() == ISD::UNDEF)
5341 if (Elt.getOpcode() != ISD::Constant &&
5342 Elt.getOpcode() != ISD::ConstantFP)
5343 IsAllConstants = false;
5344 if (X86::isZeroNode(Elt))
5347 NonZeros |= (1 << i);
5352 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5353 if (NumNonZero == 0)
5354 return DAG.getUNDEF(VT);
5356 // Special case for single non-zero, non-undef, element.
5357 if (NumNonZero == 1) {
5358 unsigned Idx = CountTrailingZeros_32(NonZeros);
5359 SDValue Item = Op.getOperand(Idx);
5361 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5362 // the value are obviously zero, truncate the value to i32 and do the
5363 // insertion that way. Only do this if the value is non-constant or if the
5364 // value is a constant being inserted into element 0. It is cheaper to do
5365 // a constant pool load than it is to do a movd + shuffle.
5366 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5367 (!IsAllConstants || Idx == 0)) {
5368 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5370 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5371 EVT VecVT = MVT::v4i32;
5372 unsigned VecElts = 4;
5374 // Truncate the value (which may itself be a constant) to i32, and
5375 // convert it to a vector with movd (S2V+shuffle to zero extend).
5376 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5377 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5378 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5380 // Now we have our 32-bit value zero extended in the low element of
5381 // a vector. If Idx != 0, swizzle it into place.
5383 SmallVector<int, 4> Mask;
5384 Mask.push_back(Idx);
5385 for (unsigned i = 1; i != VecElts; ++i)
5387 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5390 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5394 // If we have a constant or non-constant insertion into the low element of
5395 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5396 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5397 // depending on what the source datatype is.
5400 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5402 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5403 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5404 if (VT.is256BitVector()) {
5405 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5406 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5407 Item, DAG.getIntPtrConstant(0));
5409 assert(VT.is128BitVector() && "Expected an SSE value type!");
5410 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5411 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5412 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5415 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5416 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5417 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5418 if (VT.is256BitVector()) {
5419 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5420 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5422 assert(VT.is128BitVector() && "Expected an SSE value type!");
5423 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5425 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5429 // Is it a vector logical left shift?
5430 if (NumElems == 2 && Idx == 1 &&
5431 X86::isZeroNode(Op.getOperand(0)) &&
5432 !X86::isZeroNode(Op.getOperand(1))) {
5433 unsigned NumBits = VT.getSizeInBits();
5434 return getVShift(true, VT,
5435 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5436 VT, Op.getOperand(1)),
5437 NumBits/2, DAG, *this, dl);
5440 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5443 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5444 // is a non-constant being inserted into an element other than the low one,
5445 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5446 // movd/movss) to move this into the low element, then shuffle it into
5448 if (EVTBits == 32) {
5449 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5451 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5452 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5453 SmallVector<int, 8> MaskVec;
5454 for (unsigned i = 0; i != NumElems; ++i)
5455 MaskVec.push_back(i == Idx ? 0 : 1);
5456 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5460 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5461 if (Values.size() == 1) {
5462 if (EVTBits == 32) {
5463 // Instead of a shuffle like this:
5464 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5465 // Check if it's possible to issue this instead.
5466 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5467 unsigned Idx = CountTrailingZeros_32(NonZeros);
5468 SDValue Item = Op.getOperand(Idx);
5469 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5470 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5475 // A vector full of immediates; various special cases are already
5476 // handled, so this is best done with a single constant-pool load.
5480 // For AVX-length vectors, build the individual 128-bit pieces and use
5481 // shuffles to put them in place.
5482 if (VT.is256BitVector()) {
5483 SmallVector<SDValue, 32> V;
5484 for (unsigned i = 0; i != NumElems; ++i)
5485 V.push_back(Op.getOperand(i));
5487 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5489 // Build both the lower and upper subvector.
5490 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5491 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5494 // Recreate the wider vector with the lower and upper part.
5495 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5498 // Let legalizer expand 2-wide build_vectors.
5499 if (EVTBits == 64) {
5500 if (NumNonZero == 1) {
5501 // One half is zero or undef.
5502 unsigned Idx = CountTrailingZeros_32(NonZeros);
5503 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5504 Op.getOperand(Idx));
5505 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5510 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5511 if (EVTBits == 8 && NumElems == 16) {
5512 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5514 if (V.getNode()) return V;
5517 if (EVTBits == 16 && NumElems == 8) {
5518 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5520 if (V.getNode()) return V;
5523 // If element VT is == 32 bits, turn it into a number of shuffles.
5524 SmallVector<SDValue, 8> V(NumElems);
5525 if (NumElems == 4 && NumZero > 0) {
5526 for (unsigned i = 0; i < 4; ++i) {
5527 bool isZero = !(NonZeros & (1 << i));
5529 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5531 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5534 for (unsigned i = 0; i < 2; ++i) {
5535 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5538 V[i] = V[i*2]; // Must be a zero vector.
5541 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5544 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5547 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5552 bool Reverse1 = (NonZeros & 0x3) == 2;
5553 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5557 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5558 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5560 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5563 if (Values.size() > 1 && VT.is128BitVector()) {
5564 // Check for a build vector of consecutive loads.
5565 for (unsigned i = 0; i < NumElems; ++i)
5566 V[i] = Op.getOperand(i);
5568 // Check for elements which are consecutive loads.
5569 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5573 // Check for a build vector from mostly shuffle plus few inserting.
5574 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5578 // For SSE 4.1, use insertps to put the high elements into the low element.
5579 if (getSubtarget()->hasSSE41()) {
5581 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5582 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5584 Result = DAG.getUNDEF(VT);
5586 for (unsigned i = 1; i < NumElems; ++i) {
5587 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5588 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5589 Op.getOperand(i), DAG.getIntPtrConstant(i));
5594 // Otherwise, expand into a number of unpckl*, start by extending each of
5595 // our (non-undef) elements to the full vector width with the element in the
5596 // bottom slot of the vector (which generates no code for SSE).
5597 for (unsigned i = 0; i < NumElems; ++i) {
5598 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5599 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5601 V[i] = DAG.getUNDEF(VT);
5604 // Next, we iteratively mix elements, e.g. for v4f32:
5605 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5606 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5607 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5608 unsigned EltStride = NumElems >> 1;
5609 while (EltStride != 0) {
5610 for (unsigned i = 0; i < EltStride; ++i) {
5611 // If V[i+EltStride] is undef and this is the first round of mixing,
5612 // then it is safe to just drop this shuffle: V[i] is already in the
5613 // right place, the one element (since it's the first round) being
5614 // inserted as undef can be dropped. This isn't safe for successive
5615 // rounds because they will permute elements within both vectors.
5616 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5617 EltStride == NumElems/2)
5620 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5629 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5630 // to create 256-bit vectors from two other 128-bit ones.
5631 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5632 DebugLoc dl = Op.getDebugLoc();
5633 MVT ResVT = Op.getValueType().getSimpleVT();
5635 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5637 SDValue V1 = Op.getOperand(0);
5638 SDValue V2 = Op.getOperand(1);
5639 unsigned NumElems = ResVT.getVectorNumElements();
5641 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5644 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5645 assert(Op.getNumOperands() == 2);
5647 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5648 // from two other 128-bit ones.
5649 return LowerAVXCONCAT_VECTORS(Op, DAG);
5652 // Try to lower a shuffle node into a simple blend instruction.
5654 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5655 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5656 SDValue V1 = SVOp->getOperand(0);
5657 SDValue V2 = SVOp->getOperand(1);
5658 DebugLoc dl = SVOp->getDebugLoc();
5659 MVT VT = SVOp->getValueType(0).getSimpleVT();
5660 MVT EltVT = VT.getVectorElementType();
5661 unsigned NumElems = VT.getVectorNumElements();
5663 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5665 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5668 // Check the mask for BLEND and build the value.
5669 unsigned MaskValue = 0;
5670 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5671 unsigned NumLanes = (NumElems-1)/8 + 1;
5672 unsigned NumElemsInLane = NumElems / NumLanes;
5674 // Blend for v16i16 should be symetric for the both lanes.
5675 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5677 int SndLaneEltIdx = (NumLanes == 2) ?
5678 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5679 int EltIdx = SVOp->getMaskElt(i);
5681 if ((EltIdx == -1 || EltIdx == (int)i) &&
5682 (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5685 if (((unsigned)EltIdx == (i + NumElems)) &&
5686 (SndLaneEltIdx == -1 ||
5687 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5688 MaskValue |= (1<<i);
5693 // Convert i32 vectors to floating point if it is not AVX2.
5694 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5696 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5697 BlendVT = EVT::getVectorVT(*DAG.getContext(),
5698 EVT::getFloatingPointVT(EltVT.getSizeInBits()),
5700 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5701 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5704 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5705 DAG.getConstant(MaskValue, MVT::i32));
5706 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5709 // v8i16 shuffles - Prefer shuffles in the following order:
5710 // 1. [all] pshuflw, pshufhw, optional move
5711 // 2. [ssse3] 1 x pshufb
5712 // 3. [ssse3] 2 x pshufb + 1 x por
5713 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5715 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5716 SelectionDAG &DAG) {
5717 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5718 SDValue V1 = SVOp->getOperand(0);
5719 SDValue V2 = SVOp->getOperand(1);
5720 DebugLoc dl = SVOp->getDebugLoc();
5721 SmallVector<int, 8> MaskVals;
5723 // Determine if more than 1 of the words in each of the low and high quadwords
5724 // of the result come from the same quadword of one of the two inputs. Undef
5725 // mask values count as coming from any quadword, for better codegen.
5726 unsigned LoQuad[] = { 0, 0, 0, 0 };
5727 unsigned HiQuad[] = { 0, 0, 0, 0 };
5728 std::bitset<4> InputQuads;
5729 for (unsigned i = 0; i < 8; ++i) {
5730 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5731 int EltIdx = SVOp->getMaskElt(i);
5732 MaskVals.push_back(EltIdx);
5741 InputQuads.set(EltIdx / 4);
5744 int BestLoQuad = -1;
5745 unsigned MaxQuad = 1;
5746 for (unsigned i = 0; i < 4; ++i) {
5747 if (LoQuad[i] > MaxQuad) {
5749 MaxQuad = LoQuad[i];
5753 int BestHiQuad = -1;
5755 for (unsigned i = 0; i < 4; ++i) {
5756 if (HiQuad[i] > MaxQuad) {
5758 MaxQuad = HiQuad[i];
5762 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5763 // of the two input vectors, shuffle them into one input vector so only a
5764 // single pshufb instruction is necessary. If There are more than 2 input
5765 // quads, disable the next transformation since it does not help SSSE3.
5766 bool V1Used = InputQuads[0] || InputQuads[1];
5767 bool V2Used = InputQuads[2] || InputQuads[3];
5768 if (Subtarget->hasSSSE3()) {
5769 if (InputQuads.count() == 2 && V1Used && V2Used) {
5770 BestLoQuad = InputQuads[0] ? 0 : 1;
5771 BestHiQuad = InputQuads[2] ? 2 : 3;
5773 if (InputQuads.count() > 2) {
5779 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5780 // the shuffle mask. If a quad is scored as -1, that means that it contains
5781 // words from all 4 input quadwords.
5783 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5785 BestLoQuad < 0 ? 0 : BestLoQuad,
5786 BestHiQuad < 0 ? 1 : BestHiQuad
5788 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5789 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5790 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5791 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5793 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5794 // source words for the shuffle, to aid later transformations.
5795 bool AllWordsInNewV = true;
5796 bool InOrder[2] = { true, true };
5797 for (unsigned i = 0; i != 8; ++i) {
5798 int idx = MaskVals[i];
5800 InOrder[i/4] = false;
5801 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5803 AllWordsInNewV = false;
5807 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5808 if (AllWordsInNewV) {
5809 for (int i = 0; i != 8; ++i) {
5810 int idx = MaskVals[i];
5813 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5814 if ((idx != i) && idx < 4)
5816 if ((idx != i) && idx > 3)
5825 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5826 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5827 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5828 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5829 unsigned TargetMask = 0;
5830 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5831 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5833 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5834 getShufflePSHUFLWImmediate(SVOp);
5835 V1 = NewV.getOperand(0);
5836 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5840 // If we have SSSE3, and all words of the result are from 1 input vector,
5841 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5842 // is present, fall back to case 4.
5843 if (Subtarget->hasSSSE3()) {
5844 SmallVector<SDValue,16> pshufbMask;
5846 // If we have elements from both input vectors, set the high bit of the
5847 // shuffle mask element to zero out elements that come from V2 in the V1
5848 // mask, and elements that come from V1 in the V2 mask, so that the two
5849 // results can be OR'd together.
5850 bool TwoInputs = V1Used && V2Used;
5851 for (unsigned i = 0; i != 8; ++i) {
5852 int EltIdx = MaskVals[i] * 2;
5853 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5854 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5855 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5856 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5858 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5859 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5860 DAG.getNode(ISD::BUILD_VECTOR, dl,
5861 MVT::v16i8, &pshufbMask[0], 16));
5863 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5865 // Calculate the shuffle mask for the second input, shuffle it, and
5866 // OR it with the first shuffled input.
5868 for (unsigned i = 0; i != 8; ++i) {
5869 int EltIdx = MaskVals[i] * 2;
5870 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5871 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5872 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5873 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5875 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5876 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5877 DAG.getNode(ISD::BUILD_VECTOR, dl,
5878 MVT::v16i8, &pshufbMask[0], 16));
5879 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5880 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5883 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5884 // and update MaskVals with new element order.
5885 std::bitset<8> InOrder;
5886 if (BestLoQuad >= 0) {
5887 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5888 for (int i = 0; i != 4; ++i) {
5889 int idx = MaskVals[i];
5892 } else if ((idx / 4) == BestLoQuad) {
5897 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5900 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5901 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5902 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5904 getShufflePSHUFLWImmediate(SVOp), DAG);
5908 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5909 // and update MaskVals with the new element order.
5910 if (BestHiQuad >= 0) {
5911 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5912 for (unsigned i = 4; i != 8; ++i) {
5913 int idx = MaskVals[i];
5916 } else if ((idx / 4) == BestHiQuad) {
5917 MaskV[i] = (idx & 3) + 4;
5921 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5924 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5925 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5926 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5928 getShufflePSHUFHWImmediate(SVOp), DAG);
5932 // In case BestHi & BestLo were both -1, which means each quadword has a word
5933 // from each of the four input quadwords, calculate the InOrder bitvector now
5934 // before falling through to the insert/extract cleanup.
5935 if (BestLoQuad == -1 && BestHiQuad == -1) {
5937 for (int i = 0; i != 8; ++i)
5938 if (MaskVals[i] < 0 || MaskVals[i] == i)
5942 // The other elements are put in the right place using pextrw and pinsrw.
5943 for (unsigned i = 0; i != 8; ++i) {
5946 int EltIdx = MaskVals[i];
5949 SDValue ExtOp = (EltIdx < 8) ?
5950 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5951 DAG.getIntPtrConstant(EltIdx)) :
5952 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5953 DAG.getIntPtrConstant(EltIdx - 8));
5954 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5955 DAG.getIntPtrConstant(i));
5960 // v16i8 shuffles - Prefer shuffles in the following order:
5961 // 1. [ssse3] 1 x pshufb
5962 // 2. [ssse3] 2 x pshufb + 1 x por
5963 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5965 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5967 const X86TargetLowering &TLI) {
5968 SDValue V1 = SVOp->getOperand(0);
5969 SDValue V2 = SVOp->getOperand(1);
5970 DebugLoc dl = SVOp->getDebugLoc();
5971 ArrayRef<int> MaskVals = SVOp->getMask();
5973 // If we have SSSE3, case 1 is generated when all result bytes come from
5974 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5975 // present, fall back to case 3.
5977 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5978 if (TLI.getSubtarget()->hasSSSE3()) {
5979 SmallVector<SDValue,16> pshufbMask;
5981 // If all result elements are from one input vector, then only translate
5982 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5984 // Otherwise, we have elements from both input vectors, and must zero out
5985 // elements that come from V2 in the first mask, and V1 in the second mask
5986 // so that we can OR them together.
5987 for (unsigned i = 0; i != 16; ++i) {
5988 int EltIdx = MaskVals[i];
5989 if (EltIdx < 0 || EltIdx >= 16)
5991 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5993 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5994 DAG.getNode(ISD::BUILD_VECTOR, dl,
5995 MVT::v16i8, &pshufbMask[0], 16));
5997 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5998 // the 2nd operand if it's undefined or zero.
5999 if (V2.getOpcode() == ISD::UNDEF ||
6000 ISD::isBuildVectorAllZeros(V2.getNode()))
6003 // Calculate the shuffle mask for the second input, shuffle it, and
6004 // OR it with the first shuffled input.
6006 for (unsigned i = 0; i != 16; ++i) {
6007 int EltIdx = MaskVals[i];
6008 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6009 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6011 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6012 DAG.getNode(ISD::BUILD_VECTOR, dl,
6013 MVT::v16i8, &pshufbMask[0], 16));
6014 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6017 // No SSSE3 - Calculate in place words and then fix all out of place words
6018 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6019 // the 16 different words that comprise the two doublequadword input vectors.
6020 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6021 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6023 for (int i = 0; i != 8; ++i) {
6024 int Elt0 = MaskVals[i*2];
6025 int Elt1 = MaskVals[i*2+1];
6027 // This word of the result is all undef, skip it.
6028 if (Elt0 < 0 && Elt1 < 0)
6031 // This word of the result is already in the correct place, skip it.
6032 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6035 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6036 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6039 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6040 // using a single extract together, load it and store it.
6041 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6042 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6043 DAG.getIntPtrConstant(Elt1 / 2));
6044 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6045 DAG.getIntPtrConstant(i));
6049 // If Elt1 is defined, extract it from the appropriate source. If the
6050 // source byte is not also odd, shift the extracted word left 8 bits
6051 // otherwise clear the bottom 8 bits if we need to do an or.
6053 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6054 DAG.getIntPtrConstant(Elt1 / 2));
6055 if ((Elt1 & 1) == 0)
6056 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6058 TLI.getShiftAmountTy(InsElt.getValueType())));
6060 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6061 DAG.getConstant(0xFF00, MVT::i16));
6063 // If Elt0 is defined, extract it from the appropriate source. If the
6064 // source byte is not also even, shift the extracted word right 8 bits. If
6065 // Elt1 was also defined, OR the extracted values together before
6066 // inserting them in the result.
6068 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6069 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6070 if ((Elt0 & 1) != 0)
6071 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6073 TLI.getShiftAmountTy(InsElt0.getValueType())));
6075 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6076 DAG.getConstant(0x00FF, MVT::i16));
6077 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6080 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6081 DAG.getIntPtrConstant(i));
6083 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6086 // v32i8 shuffles - Translate to VPSHUFB if possible.
6088 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6089 const X86Subtarget *Subtarget,
6090 SelectionDAG &DAG) {
6091 MVT VT = SVOp->getValueType(0).getSimpleVT();
6092 SDValue V1 = SVOp->getOperand(0);
6093 SDValue V2 = SVOp->getOperand(1);
6094 DebugLoc dl = SVOp->getDebugLoc();
6095 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6097 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6098 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6099 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6101 // VPSHUFB may be generated if
6102 // (1) one of input vector is undefined or zeroinitializer.
6103 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6104 // And (2) the mask indexes don't cross the 128-bit lane.
6105 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6106 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6109 if (V1IsAllZero && !V2IsAllZero) {
6110 CommuteVectorShuffleMask(MaskVals, 32);
6113 SmallVector<SDValue, 32> pshufbMask;
6114 for (unsigned i = 0; i != 32; i++) {
6115 int EltIdx = MaskVals[i];
6116 if (EltIdx < 0 || EltIdx >= 32)
6119 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6120 // Cross lane is not allowed.
6124 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6126 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6127 DAG.getNode(ISD::BUILD_VECTOR, dl,
6128 MVT::v32i8, &pshufbMask[0], 32));
6131 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6132 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6133 /// done when every pair / quad of shuffle mask elements point to elements in
6134 /// the right sequence. e.g.
6135 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6137 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6138 SelectionDAG &DAG) {
6139 MVT VT = SVOp->getValueType(0).getSimpleVT();
6140 DebugLoc dl = SVOp->getDebugLoc();
6141 unsigned NumElems = VT.getVectorNumElements();
6144 switch (VT.SimpleTy) {
6145 default: llvm_unreachable("Unexpected!");
6146 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6147 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6148 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6149 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6150 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6151 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6154 SmallVector<int, 8> MaskVec;
6155 for (unsigned i = 0; i != NumElems; i += Scale) {
6157 for (unsigned j = 0; j != Scale; ++j) {
6158 int EltIdx = SVOp->getMaskElt(i+j);
6162 StartIdx = (EltIdx / Scale);
6163 if (EltIdx != (int)(StartIdx*Scale + j))
6166 MaskVec.push_back(StartIdx);
6169 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6170 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6171 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6174 /// getVZextMovL - Return a zero-extending vector move low node.
6176 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6177 SDValue SrcOp, SelectionDAG &DAG,
6178 const X86Subtarget *Subtarget, DebugLoc dl) {
6179 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6180 LoadSDNode *LD = NULL;
6181 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6182 LD = dyn_cast<LoadSDNode>(SrcOp);
6184 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6186 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6187 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6188 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6189 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6190 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6192 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6193 return DAG.getNode(ISD::BITCAST, dl, VT,
6194 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6195 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6203 return DAG.getNode(ISD::BITCAST, dl, VT,
6204 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6205 DAG.getNode(ISD::BITCAST, dl,
6209 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6210 /// which could not be matched by any known target speficic shuffle
6212 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6214 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6215 if (NewOp.getNode())
6218 MVT VT = SVOp->getValueType(0).getSimpleVT();
6220 unsigned NumElems = VT.getVectorNumElements();
6221 unsigned NumLaneElems = NumElems / 2;
6223 DebugLoc dl = SVOp->getDebugLoc();
6224 MVT EltVT = VT.getVectorElementType();
6225 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6228 SmallVector<int, 16> Mask;
6229 for (unsigned l = 0; l < 2; ++l) {
6230 // Build a shuffle mask for the output, discovering on the fly which
6231 // input vectors to use as shuffle operands (recorded in InputUsed).
6232 // If building a suitable shuffle vector proves too hard, then bail
6233 // out with UseBuildVector set.
6234 bool UseBuildVector = false;
6235 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6236 unsigned LaneStart = l * NumLaneElems;
6237 for (unsigned i = 0; i != NumLaneElems; ++i) {
6238 // The mask element. This indexes into the input.
6239 int Idx = SVOp->getMaskElt(i+LaneStart);
6241 // the mask element does not index into any input vector.
6246 // The input vector this mask element indexes into.
6247 int Input = Idx / NumLaneElems;
6249 // Turn the index into an offset from the start of the input vector.
6250 Idx -= Input * NumLaneElems;
6252 // Find or create a shuffle vector operand to hold this input.
6254 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6255 if (InputUsed[OpNo] == Input)
6256 // This input vector is already an operand.
6258 if (InputUsed[OpNo] < 0) {
6259 // Create a new operand for this input vector.
6260 InputUsed[OpNo] = Input;
6265 if (OpNo >= array_lengthof(InputUsed)) {
6266 // More than two input vectors used! Give up on trying to create a
6267 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6268 UseBuildVector = true;
6272 // Add the mask index for the new shuffle vector.
6273 Mask.push_back(Idx + OpNo * NumLaneElems);
6276 if (UseBuildVector) {
6277 SmallVector<SDValue, 16> SVOps;
6278 for (unsigned i = 0; i != NumLaneElems; ++i) {
6279 // The mask element. This indexes into the input.
6280 int Idx = SVOp->getMaskElt(i+LaneStart);
6282 SVOps.push_back(DAG.getUNDEF(EltVT));
6286 // The input vector this mask element indexes into.
6287 int Input = Idx / NumElems;
6289 // Turn the index into an offset from the start of the input vector.
6290 Idx -= Input * NumElems;
6292 // Extract the vector element by hand.
6293 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6294 SVOp->getOperand(Input),
6295 DAG.getIntPtrConstant(Idx)));
6298 // Construct the output using a BUILD_VECTOR.
6299 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6301 } else if (InputUsed[0] < 0) {
6302 // No input vectors were used! The result is undefined.
6303 Output[l] = DAG.getUNDEF(NVT);
6305 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6306 (InputUsed[0] % 2) * NumLaneElems,
6308 // If only one input was used, use an undefined vector for the other.
6309 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6310 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6311 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6312 // At least one input vector was used. Create a new shuffle vector.
6313 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6319 // Concatenate the result back
6320 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6323 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6324 /// 4 elements, and match them with several different shuffle types.
6326 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6327 SDValue V1 = SVOp->getOperand(0);
6328 SDValue V2 = SVOp->getOperand(1);
6329 DebugLoc dl = SVOp->getDebugLoc();
6330 MVT VT = SVOp->getValueType(0).getSimpleVT();
6332 assert(VT.is128BitVector() && "Unsupported vector size");
6334 std::pair<int, int> Locs[4];
6335 int Mask1[] = { -1, -1, -1, -1 };
6336 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6340 for (unsigned i = 0; i != 4; ++i) {
6341 int Idx = PermMask[i];
6343 Locs[i] = std::make_pair(-1, -1);
6345 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6347 Locs[i] = std::make_pair(0, NumLo);
6351 Locs[i] = std::make_pair(1, NumHi);
6353 Mask1[2+NumHi] = Idx;
6359 if (NumLo <= 2 && NumHi <= 2) {
6360 // If no more than two elements come from either vector. This can be
6361 // implemented with two shuffles. First shuffle gather the elements.
6362 // The second shuffle, which takes the first shuffle as both of its
6363 // vector operands, put the elements into the right order.
6364 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6366 int Mask2[] = { -1, -1, -1, -1 };
6368 for (unsigned i = 0; i != 4; ++i)
6369 if (Locs[i].first != -1) {
6370 unsigned Idx = (i < 2) ? 0 : 4;
6371 Idx += Locs[i].first * 2 + Locs[i].second;
6375 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6378 if (NumLo == 3 || NumHi == 3) {
6379 // Otherwise, we must have three elements from one vector, call it X, and
6380 // one element from the other, call it Y. First, use a shufps to build an
6381 // intermediate vector with the one element from Y and the element from X
6382 // that will be in the same half in the final destination (the indexes don't
6383 // matter). Then, use a shufps to build the final vector, taking the half
6384 // containing the element from Y from the intermediate, and the other half
6387 // Normalize it so the 3 elements come from V1.
6388 CommuteVectorShuffleMask(PermMask, 4);
6392 // Find the element from V2.
6394 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6395 int Val = PermMask[HiIndex];
6402 Mask1[0] = PermMask[HiIndex];
6404 Mask1[2] = PermMask[HiIndex^1];
6406 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6409 Mask1[0] = PermMask[0];
6410 Mask1[1] = PermMask[1];
6411 Mask1[2] = HiIndex & 1 ? 6 : 4;
6412 Mask1[3] = HiIndex & 1 ? 4 : 6;
6413 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6416 Mask1[0] = HiIndex & 1 ? 2 : 0;
6417 Mask1[1] = HiIndex & 1 ? 0 : 2;
6418 Mask1[2] = PermMask[2];
6419 Mask1[3] = PermMask[3];
6424 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6427 // Break it into (shuffle shuffle_hi, shuffle_lo).
6428 int LoMask[] = { -1, -1, -1, -1 };
6429 int HiMask[] = { -1, -1, -1, -1 };
6431 int *MaskPtr = LoMask;
6432 unsigned MaskIdx = 0;
6435 for (unsigned i = 0; i != 4; ++i) {
6442 int Idx = PermMask[i];
6444 Locs[i] = std::make_pair(-1, -1);
6445 } else if (Idx < 4) {
6446 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6447 MaskPtr[LoIdx] = Idx;
6450 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6451 MaskPtr[HiIdx] = Idx;
6456 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6457 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6458 int MaskOps[] = { -1, -1, -1, -1 };
6459 for (unsigned i = 0; i != 4; ++i)
6460 if (Locs[i].first != -1)
6461 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6462 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6465 static bool MayFoldVectorLoad(SDValue V) {
6466 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6467 V = V.getOperand(0);
6469 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6470 V = V.getOperand(0);
6471 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6472 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6473 // BUILD_VECTOR (load), undef
6474 V = V.getOperand(0);
6476 return MayFoldLoad(V);
6480 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6481 EVT VT = Op.getValueType();
6483 // Canonizalize to v2f64.
6484 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6485 return DAG.getNode(ISD::BITCAST, dl, VT,
6486 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6491 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6493 SDValue V1 = Op.getOperand(0);
6494 SDValue V2 = Op.getOperand(1);
6495 EVT VT = Op.getValueType();
6497 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6499 if (HasSSE2 && VT == MVT::v2f64)
6500 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6502 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6503 return DAG.getNode(ISD::BITCAST, dl, VT,
6504 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6505 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6506 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6510 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6511 SDValue V1 = Op.getOperand(0);
6512 SDValue V2 = Op.getOperand(1);
6513 EVT VT = Op.getValueType();
6515 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6516 "unsupported shuffle type");
6518 if (V2.getOpcode() == ISD::UNDEF)
6522 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6526 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6527 SDValue V1 = Op.getOperand(0);
6528 SDValue V2 = Op.getOperand(1);
6529 EVT VT = Op.getValueType();
6530 unsigned NumElems = VT.getVectorNumElements();
6532 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6533 // operand of these instructions is only memory, so check if there's a
6534 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6536 bool CanFoldLoad = false;
6538 // Trivial case, when V2 comes from a load.
6539 if (MayFoldVectorLoad(V2))
6542 // When V1 is a load, it can be folded later into a store in isel, example:
6543 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6545 // (MOVLPSmr addr:$src1, VR128:$src2)
6546 // So, recognize this potential and also use MOVLPS or MOVLPD
6547 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6550 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6552 if (HasSSE2 && NumElems == 2)
6553 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6556 // If we don't care about the second element, proceed to use movss.
6557 if (SVOp->getMaskElt(1) != -1)
6558 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6561 // movl and movlp will both match v2i64, but v2i64 is never matched by
6562 // movl earlier because we make it strict to avoid messing with the movlp load
6563 // folding logic (see the code above getMOVLP call). Match it here then,
6564 // this is horrible, but will stay like this until we move all shuffle
6565 // matching to x86 specific nodes. Note that for the 1st condition all
6566 // types are matched with movsd.
6568 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6569 // as to remove this logic from here, as much as possible
6570 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6571 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6572 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6575 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6577 // Invert the operand order and use SHUFPS to match it.
6578 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6579 getShuffleSHUFImmediate(SVOp), DAG);
6582 // Reduce a vector shuffle to zext.
6584 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6585 // PMOVZX is only available from SSE41.
6586 if (!Subtarget->hasSSE41())
6589 EVT VT = Op.getValueType();
6591 // Only AVX2 support 256-bit vector integer extending.
6592 if (!Subtarget->hasInt256() && VT.is256BitVector())
6595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6596 DebugLoc DL = Op.getDebugLoc();
6597 SDValue V1 = Op.getOperand(0);
6598 SDValue V2 = Op.getOperand(1);
6599 unsigned NumElems = VT.getVectorNumElements();
6601 // Extending is an unary operation and the element type of the source vector
6602 // won't be equal to or larger than i64.
6603 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6604 VT.getVectorElementType() == MVT::i64)
6607 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6608 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6609 while ((1U << Shift) < NumElems) {
6610 if (SVOp->getMaskElt(1U << Shift) == 1)
6613 // The maximal ratio is 8, i.e. from i8 to i64.
6618 // Check the shuffle mask.
6619 unsigned Mask = (1U << Shift) - 1;
6620 for (unsigned i = 0; i != NumElems; ++i) {
6621 int EltIdx = SVOp->getMaskElt(i);
6622 if ((i & Mask) != 0 && EltIdx != -1)
6624 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6628 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6629 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6630 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6632 if (!isTypeLegal(NVT))
6635 // Simplify the operand as it's prepared to be fed into shuffle.
6636 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6637 if (V1.getOpcode() == ISD::BITCAST &&
6638 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6639 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6641 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6642 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6643 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6644 ConstantSDNode *CIdx =
6645 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6646 // If it's foldable, i.e. normal load with single use, we will let code
6647 // selection to fold it. Otherwise, we will short the conversion sequence.
6648 if (CIdx && CIdx->getZExtValue() == 0 &&
6649 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6650 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6653 return DAG.getNode(ISD::BITCAST, DL, VT,
6654 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6658 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6659 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6660 MVT VT = Op.getValueType().getSimpleVT();
6661 DebugLoc dl = Op.getDebugLoc();
6662 SDValue V1 = Op.getOperand(0);
6663 SDValue V2 = Op.getOperand(1);
6665 if (isZeroShuffle(SVOp))
6666 return getZeroVector(VT, Subtarget, DAG, dl);
6668 // Handle splat operations
6669 if (SVOp->isSplat()) {
6670 unsigned NumElem = VT.getVectorNumElements();
6672 // Use vbroadcast whenever the splat comes from a foldable load
6673 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6674 if (Broadcast.getNode())
6677 // Handle splats by matching through known shuffle masks
6678 if ((VT.is128BitVector() && NumElem <= 4) ||
6679 (VT.is256BitVector() && NumElem <= 8))
6682 // All remaning splats are promoted to target supported vector shuffles.
6683 return PromoteSplat(SVOp, DAG);
6686 // Check integer expanding shuffles.
6687 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6688 if (NewOp.getNode())
6691 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6693 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6694 VT == MVT::v16i16 || VT == MVT::v32i8) {
6695 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6696 if (NewOp.getNode())
6697 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6698 } else if ((VT == MVT::v4i32 ||
6699 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6700 // FIXME: Figure out a cleaner way to do this.
6701 // Try to make use of movq to zero out the top part.
6702 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6703 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6704 if (NewOp.getNode()) {
6705 MVT NewVT = NewOp.getValueType().getSimpleVT();
6706 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6707 NewVT, true, false))
6708 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6709 DAG, Subtarget, dl);
6711 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6712 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6713 if (NewOp.getNode()) {
6714 MVT NewVT = NewOp.getValueType().getSimpleVT();
6715 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6716 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6717 DAG, Subtarget, dl);
6725 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6726 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6727 SDValue V1 = Op.getOperand(0);
6728 SDValue V2 = Op.getOperand(1);
6729 MVT VT = Op.getValueType().getSimpleVT();
6730 DebugLoc dl = Op.getDebugLoc();
6731 unsigned NumElems = VT.getVectorNumElements();
6732 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6733 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6734 bool V1IsSplat = false;
6735 bool V2IsSplat = false;
6736 bool HasSSE2 = Subtarget->hasSSE2();
6737 bool HasFp256 = Subtarget->hasFp256();
6738 bool HasInt256 = Subtarget->hasInt256();
6739 MachineFunction &MF = DAG.getMachineFunction();
6740 bool OptForSize = MF.getFunction()->getAttributes().
6741 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6743 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6745 if (V1IsUndef && V2IsUndef)
6746 return DAG.getUNDEF(VT);
6748 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6750 // Vector shuffle lowering takes 3 steps:
6752 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6753 // narrowing and commutation of operands should be handled.
6754 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6756 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6757 // so the shuffle can be broken into other shuffles and the legalizer can
6758 // try the lowering again.
6760 // The general idea is that no vector_shuffle operation should be left to
6761 // be matched during isel, all of them must be converted to a target specific
6764 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6765 // narrowing and commutation of operands should be handled. The actual code
6766 // doesn't include all of those, work in progress...
6767 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6768 if (NewOp.getNode())
6771 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6773 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6774 // unpckh_undef). Only use pshufd if speed is more important than size.
6775 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6776 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6777 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6778 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6780 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6781 V2IsUndef && MayFoldVectorLoad(V1))
6782 return getMOVDDup(Op, dl, V1, DAG);
6784 if (isMOVHLPS_v_undef_Mask(M, VT))
6785 return getMOVHighToLow(Op, dl, DAG);
6787 // Use to match splats
6788 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6789 (VT == MVT::v2f64 || VT == MVT::v2i64))
6790 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6792 if (isPSHUFDMask(M, VT)) {
6793 // The actual implementation will match the mask in the if above and then
6794 // during isel it can match several different instructions, not only pshufd
6795 // as its name says, sad but true, emulate the behavior for now...
6796 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6797 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6799 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6801 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6802 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6804 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6805 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6808 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6812 // Check if this can be converted into a logical shift.
6813 bool isLeft = false;
6816 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6817 if (isShift && ShVal.hasOneUse()) {
6818 // If the shifted value has multiple uses, it may be cheaper to use
6819 // v_set0 + movlhps or movhlps, etc.
6820 MVT EltVT = VT.getVectorElementType();
6821 ShAmt *= EltVT.getSizeInBits();
6822 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6825 if (isMOVLMask(M, VT)) {
6826 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6827 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6828 if (!isMOVLPMask(M, VT)) {
6829 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6830 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6832 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6833 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6837 // FIXME: fold these into legal mask.
6838 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6839 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6841 if (isMOVHLPSMask(M, VT))
6842 return getMOVHighToLow(Op, dl, DAG);
6844 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6845 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6847 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6848 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6850 if (isMOVLPMask(M, VT))
6851 return getMOVLP(Op, dl, DAG, HasSSE2);
6853 if (ShouldXformToMOVHLPS(M, VT) ||
6854 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6855 return CommuteVectorShuffle(SVOp, DAG);
6858 // No better options. Use a vshldq / vsrldq.
6859 MVT EltVT = VT.getVectorElementType();
6860 ShAmt *= EltVT.getSizeInBits();
6861 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6864 bool Commuted = false;
6865 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6866 // 1,1,1,1 -> v8i16 though.
6867 V1IsSplat = isSplatVector(V1.getNode());
6868 V2IsSplat = isSplatVector(V2.getNode());
6870 // Canonicalize the splat or undef, if present, to be on the RHS.
6871 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6872 CommuteVectorShuffleMask(M, NumElems);
6874 std::swap(V1IsSplat, V2IsSplat);
6878 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6879 // Shuffling low element of v1 into undef, just return v1.
6882 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6883 // the instruction selector will not match, so get a canonical MOVL with
6884 // swapped operands to undo the commute.
6885 return getMOVL(DAG, dl, VT, V2, V1);
6888 if (isUNPCKLMask(M, VT, HasInt256))
6889 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6891 if (isUNPCKHMask(M, VT, HasInt256))
6892 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6895 // Normalize mask so all entries that point to V2 points to its first
6896 // element then try to match unpck{h|l} again. If match, return a
6897 // new vector_shuffle with the corrected mask.p
6898 SmallVector<int, 8> NewMask(M.begin(), M.end());
6899 NormalizeMask(NewMask, NumElems);
6900 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6901 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6902 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6903 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6907 // Commute is back and try unpck* again.
6908 // FIXME: this seems wrong.
6909 CommuteVectorShuffleMask(M, NumElems);
6911 std::swap(V1IsSplat, V2IsSplat);
6914 if (isUNPCKLMask(M, VT, HasInt256))
6915 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6917 if (isUNPCKHMask(M, VT, HasInt256))
6918 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6921 // Normalize the node to match x86 shuffle ops if needed
6922 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6923 return CommuteVectorShuffle(SVOp, DAG);
6925 // The checks below are all present in isShuffleMaskLegal, but they are
6926 // inlined here right now to enable us to directly emit target specific
6927 // nodes, and remove one by one until they don't return Op anymore.
6929 if (isPALIGNRMask(M, VT, Subtarget))
6930 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6931 getShufflePALIGNRImmediate(SVOp),
6934 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6935 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6936 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6937 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6940 if (isPSHUFHWMask(M, VT, HasInt256))
6941 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6942 getShufflePSHUFHWImmediate(SVOp),
6945 if (isPSHUFLWMask(M, VT, HasInt256))
6946 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6947 getShufflePSHUFLWImmediate(SVOp),
6950 if (isSHUFPMask(M, VT, HasFp256))
6951 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6952 getShuffleSHUFImmediate(SVOp), DAG);
6954 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6955 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6956 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6957 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6959 //===--------------------------------------------------------------------===//
6960 // Generate target specific nodes for 128 or 256-bit shuffles only
6961 // supported in the AVX instruction set.
6964 // Handle VMOVDDUPY permutations
6965 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6966 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6968 // Handle VPERMILPS/D* permutations
6969 if (isVPERMILPMask(M, VT, HasFp256)) {
6970 if (HasInt256 && VT == MVT::v8i32)
6971 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6972 getShuffleSHUFImmediate(SVOp), DAG);
6973 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6974 getShuffleSHUFImmediate(SVOp), DAG);
6977 // Handle VPERM2F128/VPERM2I128 permutations
6978 if (isVPERM2X128Mask(M, VT, HasFp256))
6979 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6980 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6982 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6983 if (BlendOp.getNode())
6986 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6987 SmallVector<SDValue, 8> permclMask;
6988 for (unsigned i = 0; i != 8; ++i) {
6989 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6991 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6993 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6994 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6995 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6998 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6999 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7000 getShuffleCLImmediate(SVOp), DAG);
7002 //===--------------------------------------------------------------------===//
7003 // Since no target specific shuffle was selected for this generic one,
7004 // lower it into other known shuffles. FIXME: this isn't true yet, but
7005 // this is the plan.
7008 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7009 if (VT == MVT::v8i16) {
7010 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7011 if (NewOp.getNode())
7015 if (VT == MVT::v16i8) {
7016 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7017 if (NewOp.getNode())
7021 if (VT == MVT::v32i8) {
7022 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7023 if (NewOp.getNode())
7027 // Handle all 128-bit wide vectors with 4 elements, and match them with
7028 // several different shuffle types.
7029 if (NumElems == 4 && VT.is128BitVector())
7030 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7032 // Handle general 256-bit shuffles
7033 if (VT.is256BitVector())
7034 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7039 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7040 MVT VT = Op.getValueType().getSimpleVT();
7041 DebugLoc dl = Op.getDebugLoc();
7043 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7046 if (VT.getSizeInBits() == 8) {
7047 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7048 Op.getOperand(0), Op.getOperand(1));
7049 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7050 DAG.getValueType(VT));
7051 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7054 if (VT.getSizeInBits() == 16) {
7055 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7056 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7058 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7059 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7060 DAG.getNode(ISD::BITCAST, dl,
7064 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7065 Op.getOperand(0), Op.getOperand(1));
7066 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7067 DAG.getValueType(VT));
7068 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7071 if (VT == MVT::f32) {
7072 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7073 // the result back to FR32 register. It's only worth matching if the
7074 // result has a single use which is a store or a bitcast to i32. And in
7075 // the case of a store, it's not worth it if the index is a constant 0,
7076 // because a MOVSSmr can be used instead, which is smaller and faster.
7077 if (!Op.hasOneUse())
7079 SDNode *User = *Op.getNode()->use_begin();
7080 if ((User->getOpcode() != ISD::STORE ||
7081 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7082 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7083 (User->getOpcode() != ISD::BITCAST ||
7084 User->getValueType(0) != MVT::i32))
7086 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7087 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7090 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7093 if (VT == MVT::i32 || VT == MVT::i64) {
7094 // ExtractPS/pextrq works with constant index.
7095 if (isa<ConstantSDNode>(Op.getOperand(1)))
7102 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7103 SelectionDAG &DAG) const {
7104 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7107 SDValue Vec = Op.getOperand(0);
7108 MVT VecVT = Vec.getValueType().getSimpleVT();
7110 // If this is a 256-bit vector result, first extract the 128-bit vector and
7111 // then extract the element from the 128-bit vector.
7112 if (VecVT.is256BitVector()) {
7113 DebugLoc dl = Op.getNode()->getDebugLoc();
7114 unsigned NumElems = VecVT.getVectorNumElements();
7115 SDValue Idx = Op.getOperand(1);
7116 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7118 // Get the 128-bit vector.
7119 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7121 if (IdxVal >= NumElems/2)
7122 IdxVal -= NumElems/2;
7123 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7124 DAG.getConstant(IdxVal, MVT::i32));
7127 assert(VecVT.is128BitVector() && "Unexpected vector length");
7129 if (Subtarget->hasSSE41()) {
7130 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7135 MVT VT = Op.getValueType().getSimpleVT();
7136 DebugLoc dl = Op.getDebugLoc();
7137 // TODO: handle v16i8.
7138 if (VT.getSizeInBits() == 16) {
7139 SDValue Vec = Op.getOperand(0);
7140 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7142 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7143 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7144 DAG.getNode(ISD::BITCAST, dl,
7147 // Transform it so it match pextrw which produces a 32-bit result.
7148 MVT EltVT = MVT::i32;
7149 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7150 Op.getOperand(0), Op.getOperand(1));
7151 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7152 DAG.getValueType(VT));
7153 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7156 if (VT.getSizeInBits() == 32) {
7157 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7161 // SHUFPS the element to the lowest double word, then movss.
7162 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7163 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7164 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7165 DAG.getUNDEF(VVT), Mask);
7166 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7167 DAG.getIntPtrConstant(0));
7170 if (VT.getSizeInBits() == 64) {
7171 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7172 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7173 // to match extract_elt for f64.
7174 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7178 // UNPCKHPD the element to the lowest double word, then movsd.
7179 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7180 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7181 int Mask[2] = { 1, -1 };
7182 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7183 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7184 DAG.getUNDEF(VVT), Mask);
7185 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7186 DAG.getIntPtrConstant(0));
7192 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7193 MVT VT = Op.getValueType().getSimpleVT();
7194 MVT EltVT = VT.getVectorElementType();
7195 DebugLoc dl = Op.getDebugLoc();
7197 SDValue N0 = Op.getOperand(0);
7198 SDValue N1 = Op.getOperand(1);
7199 SDValue N2 = Op.getOperand(2);
7201 if (!VT.is128BitVector())
7204 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7205 isa<ConstantSDNode>(N2)) {
7207 if (VT == MVT::v8i16)
7208 Opc = X86ISD::PINSRW;
7209 else if (VT == MVT::v16i8)
7210 Opc = X86ISD::PINSRB;
7212 Opc = X86ISD::PINSRB;
7214 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7216 if (N1.getValueType() != MVT::i32)
7217 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7218 if (N2.getValueType() != MVT::i32)
7219 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7220 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7223 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7224 // Bits [7:6] of the constant are the source select. This will always be
7225 // zero here. The DAG Combiner may combine an extract_elt index into these
7226 // bits. For example (insert (extract, 3), 2) could be matched by putting
7227 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7228 // Bits [5:4] of the constant are the destination select. This is the
7229 // value of the incoming immediate.
7230 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7231 // combine either bitwise AND or insert of float 0.0 to set these bits.
7232 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7233 // Create this as a scalar to vector..
7234 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7235 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7238 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7239 // PINSR* works with constant index.
7246 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7247 MVT VT = Op.getValueType().getSimpleVT();
7248 MVT EltVT = VT.getVectorElementType();
7250 DebugLoc dl = Op.getDebugLoc();
7251 SDValue N0 = Op.getOperand(0);
7252 SDValue N1 = Op.getOperand(1);
7253 SDValue N2 = Op.getOperand(2);
7255 // If this is a 256-bit vector result, first extract the 128-bit vector,
7256 // insert the element into the extracted half and then place it back.
7257 if (VT.is256BitVector()) {
7258 if (!isa<ConstantSDNode>(N2))
7261 // Get the desired 128-bit vector half.
7262 unsigned NumElems = VT.getVectorNumElements();
7263 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7264 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7266 // Insert the element into the desired half.
7267 bool Upper = IdxVal >= NumElems/2;
7268 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7269 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7271 // Insert the changed part back to the 256-bit vector
7272 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7275 if (Subtarget->hasSSE41())
7276 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7278 if (EltVT == MVT::i8)
7281 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7282 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7283 // as its second argument.
7284 if (N1.getValueType() != MVT::i32)
7285 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7286 if (N2.getValueType() != MVT::i32)
7287 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7288 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7293 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7294 LLVMContext *Context = DAG.getContext();
7295 DebugLoc dl = Op.getDebugLoc();
7296 MVT OpVT = Op.getValueType().getSimpleVT();
7298 // If this is a 256-bit vector result, first insert into a 128-bit
7299 // vector and then insert into the 256-bit vector.
7300 if (!OpVT.is128BitVector()) {
7301 // Insert into a 128-bit vector.
7302 EVT VT128 = EVT::getVectorVT(*Context,
7303 OpVT.getVectorElementType(),
7304 OpVT.getVectorNumElements() / 2);
7306 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7308 // Insert the 128-bit vector.
7309 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7312 if (OpVT == MVT::v1i64 &&
7313 Op.getOperand(0).getValueType() == MVT::i64)
7314 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7316 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7317 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7318 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7319 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7322 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7323 // a simple subregister reference or explicit instructions to grab
7324 // upper bits of a vector.
7325 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7326 SelectionDAG &DAG) {
7327 if (Subtarget->hasFp256()) {
7328 DebugLoc dl = Op.getNode()->getDebugLoc();
7329 SDValue Vec = Op.getNode()->getOperand(0);
7330 SDValue Idx = Op.getNode()->getOperand(1);
7332 if (Op.getNode()->getValueType(0).is128BitVector() &&
7333 Vec.getNode()->getValueType(0).is256BitVector() &&
7334 isa<ConstantSDNode>(Idx)) {
7335 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7336 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7342 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7343 // simple superregister reference or explicit instructions to insert
7344 // the upper bits of a vector.
7345 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7346 SelectionDAG &DAG) {
7347 if (Subtarget->hasFp256()) {
7348 DebugLoc dl = Op.getNode()->getDebugLoc();
7349 SDValue Vec = Op.getNode()->getOperand(0);
7350 SDValue SubVec = Op.getNode()->getOperand(1);
7351 SDValue Idx = Op.getNode()->getOperand(2);
7353 if (Op.getNode()->getValueType(0).is256BitVector() &&
7354 SubVec.getNode()->getValueType(0).is128BitVector() &&
7355 isa<ConstantSDNode>(Idx)) {
7356 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7357 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7363 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7364 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7365 // one of the above mentioned nodes. It has to be wrapped because otherwise
7366 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7367 // be used to form addressing mode. These wrapped nodes will be selected
7370 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7371 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7373 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7375 unsigned char OpFlag = 0;
7376 unsigned WrapperKind = X86ISD::Wrapper;
7377 CodeModel::Model M = getTargetMachine().getCodeModel();
7379 if (Subtarget->isPICStyleRIPRel() &&
7380 (M == CodeModel::Small || M == CodeModel::Kernel))
7381 WrapperKind = X86ISD::WrapperRIP;
7382 else if (Subtarget->isPICStyleGOT())
7383 OpFlag = X86II::MO_GOTOFF;
7384 else if (Subtarget->isPICStyleStubPIC())
7385 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7387 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7389 CP->getOffset(), OpFlag);
7390 DebugLoc DL = CP->getDebugLoc();
7391 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7392 // With PIC, the address is actually $g + Offset.
7394 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7395 DAG.getNode(X86ISD::GlobalBaseReg,
7396 DebugLoc(), getPointerTy()),
7403 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7404 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7406 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7408 unsigned char OpFlag = 0;
7409 unsigned WrapperKind = X86ISD::Wrapper;
7410 CodeModel::Model M = getTargetMachine().getCodeModel();
7412 if (Subtarget->isPICStyleRIPRel() &&
7413 (M == CodeModel::Small || M == CodeModel::Kernel))
7414 WrapperKind = X86ISD::WrapperRIP;
7415 else if (Subtarget->isPICStyleGOT())
7416 OpFlag = X86II::MO_GOTOFF;
7417 else if (Subtarget->isPICStyleStubPIC())
7418 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7420 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7422 DebugLoc DL = JT->getDebugLoc();
7423 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7425 // With PIC, the address is actually $g + Offset.
7427 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7428 DAG.getNode(X86ISD::GlobalBaseReg,
7429 DebugLoc(), getPointerTy()),
7436 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7437 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7439 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7441 unsigned char OpFlag = 0;
7442 unsigned WrapperKind = X86ISD::Wrapper;
7443 CodeModel::Model M = getTargetMachine().getCodeModel();
7445 if (Subtarget->isPICStyleRIPRel() &&
7446 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7447 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7448 OpFlag = X86II::MO_GOTPCREL;
7449 WrapperKind = X86ISD::WrapperRIP;
7450 } else if (Subtarget->isPICStyleGOT()) {
7451 OpFlag = X86II::MO_GOT;
7452 } else if (Subtarget->isPICStyleStubPIC()) {
7453 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7454 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7455 OpFlag = X86II::MO_DARWIN_NONLAZY;
7458 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7460 DebugLoc DL = Op.getDebugLoc();
7461 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7463 // With PIC, the address is actually $g + Offset.
7464 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7465 !Subtarget->is64Bit()) {
7466 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7467 DAG.getNode(X86ISD::GlobalBaseReg,
7468 DebugLoc(), getPointerTy()),
7472 // For symbols that require a load from a stub to get the address, emit the
7474 if (isGlobalStubReference(OpFlag))
7475 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7476 MachinePointerInfo::getGOT(), false, false, false, 0);
7482 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7483 // Create the TargetBlockAddressAddress node.
7484 unsigned char OpFlags =
7485 Subtarget->ClassifyBlockAddressReference();
7486 CodeModel::Model M = getTargetMachine().getCodeModel();
7487 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7488 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7489 DebugLoc dl = Op.getDebugLoc();
7490 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7493 if (Subtarget->isPICStyleRIPRel() &&
7494 (M == CodeModel::Small || M == CodeModel::Kernel))
7495 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7497 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7499 // With PIC, the address is actually $g + Offset.
7500 if (isGlobalRelativeToPICBase(OpFlags)) {
7501 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7502 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7510 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7512 SelectionDAG &DAG) const {
7513 // Create the TargetGlobalAddress node, folding in the constant
7514 // offset if it is legal.
7515 unsigned char OpFlags =
7516 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7517 CodeModel::Model M = getTargetMachine().getCodeModel();
7519 if (OpFlags == X86II::MO_NO_FLAG &&
7520 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7521 // A direct static reference to a global.
7522 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7525 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7528 if (Subtarget->isPICStyleRIPRel() &&
7529 (M == CodeModel::Small || M == CodeModel::Kernel))
7530 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7532 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7534 // With PIC, the address is actually $g + Offset.
7535 if (isGlobalRelativeToPICBase(OpFlags)) {
7536 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7537 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7541 // For globals that require a load from a stub to get the address, emit the
7543 if (isGlobalStubReference(OpFlags))
7544 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7545 MachinePointerInfo::getGOT(), false, false, false, 0);
7547 // If there was a non-zero offset that we didn't fold, create an explicit
7550 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7551 DAG.getConstant(Offset, getPointerTy()));
7557 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7558 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7559 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7560 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7564 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7565 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7566 unsigned char OperandFlags, bool LocalDynamic = false) {
7567 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7568 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7569 DebugLoc dl = GA->getDebugLoc();
7570 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7571 GA->getValueType(0),
7575 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7579 SDValue Ops[] = { Chain, TGA, *InFlag };
7580 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7582 SDValue Ops[] = { Chain, TGA };
7583 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7586 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7587 MFI->setAdjustsStack(true);
7589 SDValue Flag = Chain.getValue(1);
7590 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7593 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7595 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7598 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7599 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7600 DAG.getNode(X86ISD::GlobalBaseReg,
7601 DebugLoc(), PtrVT), InFlag);
7602 InFlag = Chain.getValue(1);
7604 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7607 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7609 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7611 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7612 X86::RAX, X86II::MO_TLSGD);
7615 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7619 DebugLoc dl = GA->getDebugLoc();
7621 // Get the start address of the TLS block for this module.
7622 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7623 .getInfo<X86MachineFunctionInfo>();
7624 MFI->incNumLocalDynamicTLSAccesses();
7628 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7629 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7632 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7633 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7634 InFlag = Chain.getValue(1);
7635 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7636 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7639 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7643 unsigned char OperandFlags = X86II::MO_DTPOFF;
7644 unsigned WrapperKind = X86ISD::Wrapper;
7645 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7646 GA->getValueType(0),
7647 GA->getOffset(), OperandFlags);
7648 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7650 // Add x@dtpoff with the base.
7651 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7654 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7655 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7656 const EVT PtrVT, TLSModel::Model model,
7657 bool is64Bit, bool isPIC) {
7658 DebugLoc dl = GA->getDebugLoc();
7660 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7661 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7662 is64Bit ? 257 : 256));
7664 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7665 DAG.getIntPtrConstant(0),
7666 MachinePointerInfo(Ptr),
7667 false, false, false, 0);
7669 unsigned char OperandFlags = 0;
7670 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7672 unsigned WrapperKind = X86ISD::Wrapper;
7673 if (model == TLSModel::LocalExec) {
7674 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7675 } else if (model == TLSModel::InitialExec) {
7677 OperandFlags = X86II::MO_GOTTPOFF;
7678 WrapperKind = X86ISD::WrapperRIP;
7680 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7683 llvm_unreachable("Unexpected model");
7686 // emit "addl x@ntpoff,%eax" (local exec)
7687 // or "addl x@indntpoff,%eax" (initial exec)
7688 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7689 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7690 GA->getValueType(0),
7691 GA->getOffset(), OperandFlags);
7692 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7694 if (model == TLSModel::InitialExec) {
7695 if (isPIC && !is64Bit) {
7696 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7697 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7701 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7702 MachinePointerInfo::getGOT(), false, false, false,
7706 // The address of the thread local variable is the add of the thread
7707 // pointer with the offset of the variable.
7708 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7712 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7714 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7715 const GlobalValue *GV = GA->getGlobal();
7717 if (Subtarget->isTargetELF()) {
7718 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7721 case TLSModel::GeneralDynamic:
7722 if (Subtarget->is64Bit())
7723 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7724 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7725 case TLSModel::LocalDynamic:
7726 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7727 Subtarget->is64Bit());
7728 case TLSModel::InitialExec:
7729 case TLSModel::LocalExec:
7730 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7731 Subtarget->is64Bit(),
7732 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7734 llvm_unreachable("Unknown TLS model.");
7737 if (Subtarget->isTargetDarwin()) {
7738 // Darwin only has one model of TLS. Lower to that.
7739 unsigned char OpFlag = 0;
7740 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7741 X86ISD::WrapperRIP : X86ISD::Wrapper;
7743 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7745 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7746 !Subtarget->is64Bit();
7748 OpFlag = X86II::MO_TLVP_PIC_BASE;
7750 OpFlag = X86II::MO_TLVP;
7751 DebugLoc DL = Op.getDebugLoc();
7752 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7753 GA->getValueType(0),
7754 GA->getOffset(), OpFlag);
7755 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7757 // With PIC32, the address is actually $g + Offset.
7759 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7760 DAG.getNode(X86ISD::GlobalBaseReg,
7761 DebugLoc(), getPointerTy()),
7764 // Lowering the machine isd will make sure everything is in the right
7766 SDValue Chain = DAG.getEntryNode();
7767 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7768 SDValue Args[] = { Chain, Offset };
7769 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7771 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7772 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7773 MFI->setAdjustsStack(true);
7775 // And our return value (tls address) is in the standard call return value
7777 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7778 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7782 if (Subtarget->isTargetWindows()) {
7783 // Just use the implicit TLS architecture
7784 // Need to generate someting similar to:
7785 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7787 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7788 // mov rcx, qword [rdx+rcx*8]
7789 // mov eax, .tls$:tlsvar
7790 // [rax+rcx] contains the address
7791 // Windows 64bit: gs:0x58
7792 // Windows 32bit: fs:__tls_array
7794 // If GV is an alias then use the aliasee for determining
7795 // thread-localness.
7796 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7797 GV = GA->resolveAliasedGlobal(false);
7798 DebugLoc dl = GA->getDebugLoc();
7799 SDValue Chain = DAG.getEntryNode();
7801 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7802 // %gs:0x58 (64-bit).
7803 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7804 ? Type::getInt8PtrTy(*DAG.getContext(),
7806 : Type::getInt32PtrTy(*DAG.getContext(),
7809 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7810 Subtarget->is64Bit()
7811 ? DAG.getIntPtrConstant(0x58)
7812 : DAG.getExternalSymbol("_tls_array",
7814 MachinePointerInfo(Ptr),
7815 false, false, false, 0);
7817 // Load the _tls_index variable
7818 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7819 if (Subtarget->is64Bit())
7820 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7821 IDX, MachinePointerInfo(), MVT::i32,
7824 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7825 false, false, false, 0);
7827 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7829 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7831 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7832 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7833 false, false, false, 0);
7835 // Get the offset of start of .tls section
7836 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7837 GA->getValueType(0),
7838 GA->getOffset(), X86II::MO_SECREL);
7839 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7841 // The address of the thread local variable is the add of the thread
7842 // pointer with the offset of the variable.
7843 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7846 llvm_unreachable("TLS not implemented for this target.");
7849 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7850 /// and take a 2 x i32 value to shift plus a shift amount.
7851 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7852 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7853 EVT VT = Op.getValueType();
7854 unsigned VTBits = VT.getSizeInBits();
7855 DebugLoc dl = Op.getDebugLoc();
7856 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7857 SDValue ShOpLo = Op.getOperand(0);
7858 SDValue ShOpHi = Op.getOperand(1);
7859 SDValue ShAmt = Op.getOperand(2);
7860 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7861 DAG.getConstant(VTBits - 1, MVT::i8))
7862 : DAG.getConstant(0, VT);
7865 if (Op.getOpcode() == ISD::SHL_PARTS) {
7866 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7867 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7869 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7870 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7873 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7874 DAG.getConstant(VTBits, MVT::i8));
7875 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7876 AndNode, DAG.getConstant(0, MVT::i8));
7879 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7880 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7881 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7883 if (Op.getOpcode() == ISD::SHL_PARTS) {
7884 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7885 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7887 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7888 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7891 SDValue Ops[2] = { Lo, Hi };
7892 return DAG.getMergeValues(Ops, 2, dl);
7895 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7896 SelectionDAG &DAG) const {
7897 EVT SrcVT = Op.getOperand(0).getValueType();
7899 if (SrcVT.isVector())
7902 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7903 "Unknown SINT_TO_FP to lower!");
7905 // These are really Legal; return the operand so the caller accepts it as
7907 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7909 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7910 Subtarget->is64Bit()) {
7914 DebugLoc dl = Op.getDebugLoc();
7915 unsigned Size = SrcVT.getSizeInBits()/8;
7916 MachineFunction &MF = DAG.getMachineFunction();
7917 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7918 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7919 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7921 MachinePointerInfo::getFixedStack(SSFI),
7923 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7926 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7928 SelectionDAG &DAG) const {
7930 DebugLoc DL = Op.getDebugLoc();
7932 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7934 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7936 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7938 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7940 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7941 MachineMemOperand *MMO;
7943 int SSFI = FI->getIndex();
7945 DAG.getMachineFunction()
7946 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7947 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7949 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7950 StackSlot = StackSlot.getOperand(1);
7952 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7953 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7955 Tys, Ops, array_lengthof(Ops),
7959 Chain = Result.getValue(1);
7960 SDValue InFlag = Result.getValue(2);
7962 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7963 // shouldn't be necessary except that RFP cannot be live across
7964 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7965 MachineFunction &MF = DAG.getMachineFunction();
7966 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7967 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7968 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7969 Tys = DAG.getVTList(MVT::Other);
7971 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7973 MachineMemOperand *MMO =
7974 DAG.getMachineFunction()
7975 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7976 MachineMemOperand::MOStore, SSFISize, SSFISize);
7978 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7979 Ops, array_lengthof(Ops),
7980 Op.getValueType(), MMO);
7981 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7982 MachinePointerInfo::getFixedStack(SSFI),
7983 false, false, false, 0);
7989 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7990 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7991 SelectionDAG &DAG) const {
7992 // This algorithm is not obvious. Here it is what we're trying to output:
7995 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7996 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8000 pshufd $0x4e, %xmm0, %xmm1
8005 DebugLoc dl = Op.getDebugLoc();
8006 LLVMContext *Context = DAG.getContext();
8008 // Build some magic constants.
8009 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8010 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8011 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8013 SmallVector<Constant*,2> CV1;
8015 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8017 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8018 Constant *C1 = ConstantVector::get(CV1);
8019 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8021 // Load the 64-bit value into an XMM register.
8022 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8024 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8025 MachinePointerInfo::getConstantPool(),
8026 false, false, false, 16);
8027 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8028 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8031 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8032 MachinePointerInfo::getConstantPool(),
8033 false, false, false, 16);
8034 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8035 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8038 if (Subtarget->hasSSE3()) {
8039 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8040 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8042 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8043 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8045 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8046 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8050 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8051 DAG.getIntPtrConstant(0));
8054 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8055 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8056 SelectionDAG &DAG) const {
8057 DebugLoc dl = Op.getDebugLoc();
8058 // FP constant to bias correct the final result.
8059 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8062 // Load the 32-bit value into an XMM register.
8063 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8066 // Zero out the upper parts of the register.
8067 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8069 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8070 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8071 DAG.getIntPtrConstant(0));
8073 // Or the load with the bias.
8074 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8075 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8076 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8078 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8079 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8080 MVT::v2f64, Bias)));
8081 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8082 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8083 DAG.getIntPtrConstant(0));
8085 // Subtract the bias.
8086 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8088 // Handle final rounding.
8089 EVT DestVT = Op.getValueType();
8091 if (DestVT.bitsLT(MVT::f64))
8092 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8093 DAG.getIntPtrConstant(0));
8094 if (DestVT.bitsGT(MVT::f64))
8095 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8097 // Handle final rounding.
8101 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8102 SelectionDAG &DAG) const {
8103 SDValue N0 = Op.getOperand(0);
8104 EVT SVT = N0.getValueType();
8105 DebugLoc dl = Op.getDebugLoc();
8107 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8108 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8109 "Custom UINT_TO_FP is not supported!");
8111 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8112 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8113 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8116 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8117 SelectionDAG &DAG) const {
8118 SDValue N0 = Op.getOperand(0);
8119 DebugLoc dl = Op.getDebugLoc();
8121 if (Op.getValueType().isVector())
8122 return lowerUINT_TO_FP_vec(Op, DAG);
8124 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8125 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8126 // the optimization here.
8127 if (DAG.SignBitIsZero(N0))
8128 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8130 EVT SrcVT = N0.getValueType();
8131 EVT DstVT = Op.getValueType();
8132 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8133 return LowerUINT_TO_FP_i64(Op, DAG);
8134 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8135 return LowerUINT_TO_FP_i32(Op, DAG);
8136 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8139 // Make a 64-bit buffer, and use it to build an FILD.
8140 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8141 if (SrcVT == MVT::i32) {
8142 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8143 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8144 getPointerTy(), StackSlot, WordOff);
8145 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8146 StackSlot, MachinePointerInfo(),
8148 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8149 OffsetSlot, MachinePointerInfo(),
8151 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8155 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8156 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8157 StackSlot, MachinePointerInfo(),
8159 // For i64 source, we need to add the appropriate power of 2 if the input
8160 // was negative. This is the same as the optimization in
8161 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8162 // we must be careful to do the computation in x87 extended precision, not
8163 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8164 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8165 MachineMemOperand *MMO =
8166 DAG.getMachineFunction()
8167 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8168 MachineMemOperand::MOLoad, 8, 8);
8170 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8171 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8172 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8175 APInt FF(32, 0x5F800000ULL);
8177 // Check whether the sign bit is set.
8178 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8179 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8182 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8183 SDValue FudgePtr = DAG.getConstantPool(
8184 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8187 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8188 SDValue Zero = DAG.getIntPtrConstant(0);
8189 SDValue Four = DAG.getIntPtrConstant(4);
8190 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8192 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8194 // Load the value out, extending it from f32 to f80.
8195 // FIXME: Avoid the extend by constructing the right constant pool?
8196 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8197 FudgePtr, MachinePointerInfo::getConstantPool(),
8198 MVT::f32, false, false, 4);
8199 // Extend everything to 80 bits to force it to be done on x87.
8200 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8201 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8204 std::pair<SDValue,SDValue> X86TargetLowering::
8205 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8206 DebugLoc DL = Op.getDebugLoc();
8208 EVT DstTy = Op.getValueType();
8210 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8211 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8215 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8216 DstTy.getSimpleVT() >= MVT::i16 &&
8217 "Unknown FP_TO_INT to lower!");
8219 // These are really Legal.
8220 if (DstTy == MVT::i32 &&
8221 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8222 return std::make_pair(SDValue(), SDValue());
8223 if (Subtarget->is64Bit() &&
8224 DstTy == MVT::i64 &&
8225 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8226 return std::make_pair(SDValue(), SDValue());
8228 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8229 // stack slot, or into the FTOL runtime function.
8230 MachineFunction &MF = DAG.getMachineFunction();
8231 unsigned MemSize = DstTy.getSizeInBits()/8;
8232 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8233 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8236 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8237 Opc = X86ISD::WIN_FTOL;
8239 switch (DstTy.getSimpleVT().SimpleTy) {
8240 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8241 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8242 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8243 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8246 SDValue Chain = DAG.getEntryNode();
8247 SDValue Value = Op.getOperand(0);
8248 EVT TheVT = Op.getOperand(0).getValueType();
8249 // FIXME This causes a redundant load/store if the SSE-class value is already
8250 // in memory, such as if it is on the callstack.
8251 if (isScalarFPTypeInSSEReg(TheVT)) {
8252 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8253 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8254 MachinePointerInfo::getFixedStack(SSFI),
8256 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8258 Chain, StackSlot, DAG.getValueType(TheVT)
8261 MachineMemOperand *MMO =
8262 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8263 MachineMemOperand::MOLoad, MemSize, MemSize);
8264 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8266 Chain = Value.getValue(1);
8267 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8268 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8271 MachineMemOperand *MMO =
8272 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8273 MachineMemOperand::MOStore, MemSize, MemSize);
8275 if (Opc != X86ISD::WIN_FTOL) {
8276 // Build the FP_TO_INT*_IN_MEM
8277 SDValue Ops[] = { Chain, Value, StackSlot };
8278 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8279 Ops, 3, DstTy, MMO);
8280 return std::make_pair(FIST, StackSlot);
8282 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8283 DAG.getVTList(MVT::Other, MVT::Glue),
8285 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8286 MVT::i32, ftol.getValue(1));
8287 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8288 MVT::i32, eax.getValue(2));
8289 SDValue Ops[] = { eax, edx };
8290 SDValue pair = IsReplace
8291 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8292 : DAG.getMergeValues(Ops, 2, DL);
8293 return std::make_pair(pair, SDValue());
8297 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8298 const X86Subtarget *Subtarget) {
8299 MVT VT = Op->getValueType(0).getSimpleVT();
8300 SDValue In = Op->getOperand(0);
8301 MVT InVT = In.getValueType().getSimpleVT();
8302 DebugLoc dl = Op->getDebugLoc();
8304 // Optimize vectors in AVX mode:
8307 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8308 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8309 // Concat upper and lower parts.
8312 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8313 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8314 // Concat upper and lower parts.
8317 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8318 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8321 if (Subtarget->hasInt256())
8322 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8324 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8325 SDValue Undef = DAG.getUNDEF(InVT);
8326 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8327 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8328 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8330 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8331 VT.getVectorNumElements()/2);
8333 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8334 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8336 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8339 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8340 SelectionDAG &DAG) const {
8341 if (Subtarget->hasFp256()) {
8342 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8349 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8350 SelectionDAG &DAG) const {
8351 DebugLoc DL = Op.getDebugLoc();
8352 MVT VT = Op.getValueType().getSimpleVT();
8353 SDValue In = Op.getOperand(0);
8354 MVT SVT = In.getValueType().getSimpleVT();
8356 if (Subtarget->hasFp256()) {
8357 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8362 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8363 VT.getVectorNumElements() != SVT.getVectorNumElements())
8366 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8368 // AVX2 has better support of integer extending.
8369 if (Subtarget->hasInt256())
8370 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8372 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8373 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8374 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8375 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8376 DAG.getUNDEF(MVT::v8i16),
8379 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8382 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8383 DebugLoc DL = Op.getDebugLoc();
8384 MVT VT = Op.getValueType().getSimpleVT();
8385 SDValue In = Op.getOperand(0);
8386 MVT SVT = In.getValueType().getSimpleVT();
8388 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8389 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8390 if (Subtarget->hasInt256()) {
8391 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8392 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8393 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8395 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8396 DAG.getIntPtrConstant(0));
8399 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8400 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8401 DAG.getIntPtrConstant(0));
8402 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8403 DAG.getIntPtrConstant(2));
8405 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8406 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8409 static const int ShufMask1[] = {0, 2, 0, 0};
8410 SDValue Undef = DAG.getUNDEF(VT);
8411 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8412 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8414 // The MOVLHPS mask:
8415 static const int ShufMask2[] = {0, 1, 4, 5};
8416 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8419 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8420 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8421 if (Subtarget->hasInt256()) {
8422 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8424 SmallVector<SDValue,32> pshufbMask;
8425 for (unsigned i = 0; i < 2; ++i) {
8426 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8427 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8428 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8429 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8430 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8431 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8432 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8433 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8434 for (unsigned j = 0; j < 8; ++j)
8435 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8437 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8438 &pshufbMask[0], 32);
8439 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8440 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8442 static const int ShufMask[] = {0, 2, -1, -1};
8443 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8445 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8446 DAG.getIntPtrConstant(0));
8447 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8450 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8451 DAG.getIntPtrConstant(0));
8453 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8454 DAG.getIntPtrConstant(4));
8456 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8457 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8460 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8461 -1, -1, -1, -1, -1, -1, -1, -1};
8463 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8464 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8465 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8467 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8468 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8470 // The MOVLHPS Mask:
8471 static const int ShufMask2[] = {0, 1, 4, 5};
8472 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8473 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8476 // Handle truncation of V256 to V128 using shuffles.
8477 if (!VT.is128BitVector() || !SVT.is256BitVector())
8480 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8482 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8484 unsigned NumElems = VT.getVectorNumElements();
8485 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8488 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8489 // Prepare truncation shuffle mask
8490 for (unsigned i = 0; i != NumElems; ++i)
8492 SDValue V = DAG.getVectorShuffle(NVT, DL,
8493 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8494 DAG.getUNDEF(NVT), &MaskVec[0]);
8495 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8496 DAG.getIntPtrConstant(0));
8499 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8500 SelectionDAG &DAG) const {
8501 MVT VT = Op.getValueType().getSimpleVT();
8502 if (VT.isVector()) {
8503 if (VT == MVT::v8i16)
8504 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8505 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8506 MVT::v8i32, Op.getOperand(0)));
8510 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8511 /*IsSigned=*/ true, /*IsReplace=*/ false);
8512 SDValue FIST = Vals.first, StackSlot = Vals.second;
8513 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8514 if (FIST.getNode() == 0) return Op;
8516 if (StackSlot.getNode())
8518 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8519 FIST, StackSlot, MachinePointerInfo(),
8520 false, false, false, 0);
8522 // The node is the result.
8526 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8527 SelectionDAG &DAG) const {
8528 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8529 /*IsSigned=*/ false, /*IsReplace=*/ false);
8530 SDValue FIST = Vals.first, StackSlot = Vals.second;
8531 assert(FIST.getNode() && "Unexpected failure");
8533 if (StackSlot.getNode())
8535 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8536 FIST, StackSlot, MachinePointerInfo(),
8537 false, false, false, 0);
8539 // The node is the result.
8543 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8544 SelectionDAG &DAG) const {
8545 DebugLoc DL = Op.getDebugLoc();
8546 MVT VT = Op.getValueType().getSimpleVT();
8547 SDValue In = Op.getOperand(0);
8548 MVT SVT = In.getValueType().getSimpleVT();
8550 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8552 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8553 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8554 In, DAG.getUNDEF(SVT)));
8557 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8558 LLVMContext *Context = DAG.getContext();
8559 DebugLoc dl = Op.getDebugLoc();
8560 MVT VT = Op.getValueType().getSimpleVT();
8562 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8563 if (VT.isVector()) {
8564 EltVT = VT.getVectorElementType();
8565 NumElts = VT.getVectorNumElements();
8568 if (EltVT == MVT::f64)
8569 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8571 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8572 C = ConstantVector::getSplat(NumElts, C);
8573 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8574 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8575 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8576 MachinePointerInfo::getConstantPool(),
8577 false, false, false, Alignment);
8578 if (VT.isVector()) {
8579 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8580 return DAG.getNode(ISD::BITCAST, dl, VT,
8581 DAG.getNode(ISD::AND, dl, ANDVT,
8582 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8584 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8586 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8589 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8590 LLVMContext *Context = DAG.getContext();
8591 DebugLoc dl = Op.getDebugLoc();
8592 MVT VT = Op.getValueType().getSimpleVT();
8594 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8595 if (VT.isVector()) {
8596 EltVT = VT.getVectorElementType();
8597 NumElts = VT.getVectorNumElements();
8600 if (EltVT == MVT::f64)
8601 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8603 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8604 C = ConstantVector::getSplat(NumElts, C);
8605 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8606 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8607 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8608 MachinePointerInfo::getConstantPool(),
8609 false, false, false, Alignment);
8610 if (VT.isVector()) {
8611 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8612 return DAG.getNode(ISD::BITCAST, dl, VT,
8613 DAG.getNode(ISD::XOR, dl, XORVT,
8614 DAG.getNode(ISD::BITCAST, dl, XORVT,
8616 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8619 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8622 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8623 LLVMContext *Context = DAG.getContext();
8624 SDValue Op0 = Op.getOperand(0);
8625 SDValue Op1 = Op.getOperand(1);
8626 DebugLoc dl = Op.getDebugLoc();
8627 MVT VT = Op.getValueType().getSimpleVT();
8628 MVT SrcVT = Op1.getValueType().getSimpleVT();
8630 // If second operand is smaller, extend it first.
8631 if (SrcVT.bitsLT(VT)) {
8632 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8635 // And if it is bigger, shrink it first.
8636 if (SrcVT.bitsGT(VT)) {
8637 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8641 // At this point the operands and the result should have the same
8642 // type, and that won't be f80 since that is not custom lowered.
8644 // First get the sign bit of second operand.
8645 SmallVector<Constant*,4> CV;
8646 if (SrcVT == MVT::f64) {
8647 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8648 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8650 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8651 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8652 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8653 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8655 Constant *C = ConstantVector::get(CV);
8656 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8657 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8658 MachinePointerInfo::getConstantPool(),
8659 false, false, false, 16);
8660 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8662 // Shift sign bit right or left if the two operands have different types.
8663 if (SrcVT.bitsGT(VT)) {
8664 // Op0 is MVT::f32, Op1 is MVT::f64.
8665 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8666 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8667 DAG.getConstant(32, MVT::i32));
8668 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8669 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8670 DAG.getIntPtrConstant(0));
8673 // Clear first operand sign bit.
8675 if (VT == MVT::f64) {
8676 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8677 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8679 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8680 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8681 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8682 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8684 C = ConstantVector::get(CV);
8685 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8686 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8687 MachinePointerInfo::getConstantPool(),
8688 false, false, false, 16);
8689 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8691 // Or the value with the sign bit.
8692 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8695 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8696 SDValue N0 = Op.getOperand(0);
8697 DebugLoc dl = Op.getDebugLoc();
8698 MVT VT = Op.getValueType().getSimpleVT();
8700 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8701 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8702 DAG.getConstant(1, VT));
8703 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8706 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8708 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8709 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8711 if (!Subtarget->hasSSE41())
8714 if (!Op->hasOneUse())
8717 SDNode *N = Op.getNode();
8718 DebugLoc DL = N->getDebugLoc();
8720 SmallVector<SDValue, 8> Opnds;
8721 DenseMap<SDValue, unsigned> VecInMap;
8722 EVT VT = MVT::Other;
8724 // Recognize a special case where a vector is casted into wide integer to
8726 Opnds.push_back(N->getOperand(0));
8727 Opnds.push_back(N->getOperand(1));
8729 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8730 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8731 // BFS traverse all OR'd operands.
8732 if (I->getOpcode() == ISD::OR) {
8733 Opnds.push_back(I->getOperand(0));
8734 Opnds.push_back(I->getOperand(1));
8735 // Re-evaluate the number of nodes to be traversed.
8736 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8740 // Quit if a non-EXTRACT_VECTOR_ELT
8741 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8744 // Quit if without a constant index.
8745 SDValue Idx = I->getOperand(1);
8746 if (!isa<ConstantSDNode>(Idx))
8749 SDValue ExtractedFromVec = I->getOperand(0);
8750 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8751 if (M == VecInMap.end()) {
8752 VT = ExtractedFromVec.getValueType();
8753 // Quit if not 128/256-bit vector.
8754 if (!VT.is128BitVector() && !VT.is256BitVector())
8756 // Quit if not the same type.
8757 if (VecInMap.begin() != VecInMap.end() &&
8758 VT != VecInMap.begin()->first.getValueType())
8760 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8762 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8765 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8766 "Not extracted from 128-/256-bit vector.");
8768 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8769 SmallVector<SDValue, 8> VecIns;
8771 for (DenseMap<SDValue, unsigned>::const_iterator
8772 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8773 // Quit if not all elements are used.
8774 if (I->second != FullMask)
8776 VecIns.push_back(I->first);
8779 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8781 // Cast all vectors into TestVT for PTEST.
8782 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8783 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8785 // If more than one full vectors are evaluated, OR them first before PTEST.
8786 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8787 // Each iteration will OR 2 nodes and append the result until there is only
8788 // 1 node left, i.e. the final OR'd value of all vectors.
8789 SDValue LHS = VecIns[Slot];
8790 SDValue RHS = VecIns[Slot + 1];
8791 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8794 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8795 VecIns.back(), VecIns.back());
8798 /// Emit nodes that will be selected as "test Op0,Op0", or something
8800 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8801 SelectionDAG &DAG) const {
8802 DebugLoc dl = Op.getDebugLoc();
8804 // CF and OF aren't always set the way we want. Determine which
8805 // of these we need.
8806 bool NeedCF = false;
8807 bool NeedOF = false;
8810 case X86::COND_A: case X86::COND_AE:
8811 case X86::COND_B: case X86::COND_BE:
8814 case X86::COND_G: case X86::COND_GE:
8815 case X86::COND_L: case X86::COND_LE:
8816 case X86::COND_O: case X86::COND_NO:
8821 // See if we can use the EFLAGS value from the operand instead of
8822 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8823 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8824 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8825 // Emit a CMP with 0, which is the TEST pattern.
8826 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8827 DAG.getConstant(0, Op.getValueType()));
8829 unsigned Opcode = 0;
8830 unsigned NumOperands = 0;
8832 // Truncate operations may prevent the merge of the SETCC instruction
8833 // and the arithmetic intruction before it. Attempt to truncate the operands
8834 // of the arithmetic instruction and use a reduced bit-width instruction.
8835 bool NeedTruncation = false;
8836 SDValue ArithOp = Op;
8837 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8838 SDValue Arith = Op->getOperand(0);
8839 // Both the trunc and the arithmetic op need to have one user each.
8840 if (Arith->hasOneUse())
8841 switch (Arith.getOpcode()) {
8848 NeedTruncation = true;
8854 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8855 // which may be the result of a CAST. We use the variable 'Op', which is the
8856 // non-casted variable when we check for possible users.
8857 switch (ArithOp.getOpcode()) {
8859 // Due to an isel shortcoming, be conservative if this add is likely to be
8860 // selected as part of a load-modify-store instruction. When the root node
8861 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8862 // uses of other nodes in the match, such as the ADD in this case. This
8863 // leads to the ADD being left around and reselected, with the result being
8864 // two adds in the output. Alas, even if none our users are stores, that
8865 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8866 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8867 // climbing the DAG back to the root, and it doesn't seem to be worth the
8869 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8870 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8871 if (UI->getOpcode() != ISD::CopyToReg &&
8872 UI->getOpcode() != ISD::SETCC &&
8873 UI->getOpcode() != ISD::STORE)
8876 if (ConstantSDNode *C =
8877 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8878 // An add of one will be selected as an INC.
8879 if (C->getAPIntValue() == 1) {
8880 Opcode = X86ISD::INC;
8885 // An add of negative one (subtract of one) will be selected as a DEC.
8886 if (C->getAPIntValue().isAllOnesValue()) {
8887 Opcode = X86ISD::DEC;
8893 // Otherwise use a regular EFLAGS-setting add.
8894 Opcode = X86ISD::ADD;
8898 // If the primary and result isn't used, don't bother using X86ISD::AND,
8899 // because a TEST instruction will be better.
8900 bool NonFlagUse = false;
8901 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8902 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8904 unsigned UOpNo = UI.getOperandNo();
8905 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8906 // Look pass truncate.
8907 UOpNo = User->use_begin().getOperandNo();
8908 User = *User->use_begin();
8911 if (User->getOpcode() != ISD::BRCOND &&
8912 User->getOpcode() != ISD::SETCC &&
8913 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8926 // Due to the ISEL shortcoming noted above, be conservative if this op is
8927 // likely to be selected as part of a load-modify-store instruction.
8928 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8929 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8930 if (UI->getOpcode() == ISD::STORE)
8933 // Otherwise use a regular EFLAGS-setting instruction.
8934 switch (ArithOp.getOpcode()) {
8935 default: llvm_unreachable("unexpected operator!");
8936 case ISD::SUB: Opcode = X86ISD::SUB; break;
8937 case ISD::XOR: Opcode = X86ISD::XOR; break;
8938 case ISD::AND: Opcode = X86ISD::AND; break;
8940 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8941 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8942 if (EFLAGS.getNode())
8945 Opcode = X86ISD::OR;
8959 return SDValue(Op.getNode(), 1);
8965 // If we found that truncation is beneficial, perform the truncation and
8967 if (NeedTruncation) {
8968 EVT VT = Op.getValueType();
8969 SDValue WideVal = Op->getOperand(0);
8970 EVT WideVT = WideVal.getValueType();
8971 unsigned ConvertedOp = 0;
8972 // Use a target machine opcode to prevent further DAGCombine
8973 // optimizations that may separate the arithmetic operations
8974 // from the setcc node.
8975 switch (WideVal.getOpcode()) {
8977 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8978 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8979 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8980 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8981 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8986 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8987 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8988 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8989 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8995 // Emit a CMP with 0, which is the TEST pattern.
8996 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8997 DAG.getConstant(0, Op.getValueType()));
8999 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9000 SmallVector<SDValue, 4> Ops;
9001 for (unsigned i = 0; i != NumOperands; ++i)
9002 Ops.push_back(Op.getOperand(i));
9004 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9005 DAG.ReplaceAllUsesWith(Op, New);
9006 return SDValue(New.getNode(), 1);
9009 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9011 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9012 SelectionDAG &DAG) const {
9013 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9014 if (C->getAPIntValue() == 0)
9015 return EmitTest(Op0, X86CC, DAG);
9017 DebugLoc dl = Op0.getDebugLoc();
9018 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9019 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9020 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9021 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9022 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9024 return SDValue(Sub.getNode(), 1);
9026 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9029 /// Convert a comparison if required by the subtarget.
9030 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9031 SelectionDAG &DAG) const {
9032 // If the subtarget does not support the FUCOMI instruction, floating-point
9033 // comparisons have to be converted.
9034 if (Subtarget->hasCMov() ||
9035 Cmp.getOpcode() != X86ISD::CMP ||
9036 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9037 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9040 // The instruction selector will select an FUCOM instruction instead of
9041 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9042 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9043 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9044 DebugLoc dl = Cmp.getDebugLoc();
9045 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9046 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9047 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9048 DAG.getConstant(8, MVT::i8));
9049 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9050 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9053 static bool isAllOnes(SDValue V) {
9054 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9055 return C && C->isAllOnesValue();
9058 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9059 /// if it's possible.
9060 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9061 DebugLoc dl, SelectionDAG &DAG) const {
9062 SDValue Op0 = And.getOperand(0);
9063 SDValue Op1 = And.getOperand(1);
9064 if (Op0.getOpcode() == ISD::TRUNCATE)
9065 Op0 = Op0.getOperand(0);
9066 if (Op1.getOpcode() == ISD::TRUNCATE)
9067 Op1 = Op1.getOperand(0);
9070 if (Op1.getOpcode() == ISD::SHL)
9071 std::swap(Op0, Op1);
9072 if (Op0.getOpcode() == ISD::SHL) {
9073 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9074 if (And00C->getZExtValue() == 1) {
9075 // If we looked past a truncate, check that it's only truncating away
9077 unsigned BitWidth = Op0.getValueSizeInBits();
9078 unsigned AndBitWidth = And.getValueSizeInBits();
9079 if (BitWidth > AndBitWidth) {
9081 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9082 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9086 RHS = Op0.getOperand(1);
9088 } else if (Op1.getOpcode() == ISD::Constant) {
9089 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9090 uint64_t AndRHSVal = AndRHS->getZExtValue();
9091 SDValue AndLHS = Op0;
9093 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9094 LHS = AndLHS.getOperand(0);
9095 RHS = AndLHS.getOperand(1);
9098 // Use BT if the immediate can't be encoded in a TEST instruction.
9099 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9101 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9105 if (LHS.getNode()) {
9106 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9107 // the condition code later.
9108 bool Invert = false;
9109 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9111 LHS = LHS.getOperand(0);
9114 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9115 // instruction. Since the shift amount is in-range-or-undefined, we know
9116 // that doing a bittest on the i32 value is ok. We extend to i32 because
9117 // the encoding for the i16 version is larger than the i32 version.
9118 // Also promote i16 to i32 for performance / code size reason.
9119 if (LHS.getValueType() == MVT::i8 ||
9120 LHS.getValueType() == MVT::i16)
9121 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9123 // If the operand types disagree, extend the shift amount to match. Since
9124 // BT ignores high bits (like shifts) we can use anyextend.
9125 if (LHS.getValueType() != RHS.getValueType())
9126 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9128 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9129 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9130 // Flip the condition if the LHS was a not instruction
9132 Cond = X86::GetOppositeBranchCondition(Cond);
9133 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9134 DAG.getConstant(Cond, MVT::i8), BT);
9140 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9141 // ones, and then concatenate the result back.
9142 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9143 MVT VT = Op.getValueType().getSimpleVT();
9145 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9146 "Unsupported value type for operation");
9148 unsigned NumElems = VT.getVectorNumElements();
9149 DebugLoc dl = Op.getDebugLoc();
9150 SDValue CC = Op.getOperand(2);
9152 // Extract the LHS vectors
9153 SDValue LHS = Op.getOperand(0);
9154 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9155 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9157 // Extract the RHS vectors
9158 SDValue RHS = Op.getOperand(1);
9159 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9160 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9162 // Issue the operation on the smaller types and concatenate the result back
9163 MVT EltVT = VT.getVectorElementType();
9164 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9165 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9166 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9167 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9170 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9171 SelectionDAG &DAG) {
9173 SDValue Op0 = Op.getOperand(0);
9174 SDValue Op1 = Op.getOperand(1);
9175 SDValue CC = Op.getOperand(2);
9176 MVT VT = Op.getValueType().getSimpleVT();
9177 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9178 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9179 DebugLoc dl = Op.getDebugLoc();
9183 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9184 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9190 // SSE Condition code mapping:
9199 switch (SetCCOpcode) {
9200 default: llvm_unreachable("Unexpected SETCC condition");
9202 case ISD::SETEQ: SSECC = 0; break;
9204 case ISD::SETGT: Swap = true; // Fallthrough
9206 case ISD::SETOLT: SSECC = 1; break;
9208 case ISD::SETGE: Swap = true; // Fallthrough
9210 case ISD::SETOLE: SSECC = 2; break;
9211 case ISD::SETUO: SSECC = 3; break;
9213 case ISD::SETNE: SSECC = 4; break;
9214 case ISD::SETULE: Swap = true; // Fallthrough
9215 case ISD::SETUGE: SSECC = 5; break;
9216 case ISD::SETULT: Swap = true; // Fallthrough
9217 case ISD::SETUGT: SSECC = 6; break;
9218 case ISD::SETO: SSECC = 7; break;
9220 case ISD::SETONE: SSECC = 8; break;
9223 std::swap(Op0, Op1);
9225 // In the two special cases we can't handle, emit two comparisons.
9228 unsigned CombineOpc;
9229 if (SetCCOpcode == ISD::SETUEQ) {
9230 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9232 assert(SetCCOpcode == ISD::SETONE);
9233 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9236 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9237 DAG.getConstant(CC0, MVT::i8));
9238 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9239 DAG.getConstant(CC1, MVT::i8));
9240 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9242 // Handle all other FP comparisons here.
9243 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9244 DAG.getConstant(SSECC, MVT::i8));
9247 // Break 256-bit integer vector compare into smaller ones.
9248 if (VT.is256BitVector() && !Subtarget->hasInt256())
9249 return Lower256IntVSETCC(Op, DAG);
9251 // We are handling one of the integer comparisons here. Since SSE only has
9252 // GT and EQ comparisons for integer, swapping operands and multiple
9253 // operations may be required for some comparisons.
9255 bool Swap = false, Invert = false, FlipSigns = false;
9257 switch (SetCCOpcode) {
9258 default: llvm_unreachable("Unexpected SETCC condition");
9259 case ISD::SETNE: Invert = true;
9260 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9261 case ISD::SETLT: Swap = true;
9262 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9263 case ISD::SETGE: Swap = true;
9264 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9265 case ISD::SETULT: Swap = true;
9266 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9267 case ISD::SETUGE: Swap = true;
9268 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9271 std::swap(Op0, Op1);
9273 // Check that the operation in question is available (most are plain SSE2,
9274 // but PCMPGTQ and PCMPEQQ have different requirements).
9275 if (VT == MVT::v2i64) {
9276 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9278 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9279 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9280 // pcmpeqd + pshufd + pand.
9281 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9283 // First cast everything to the right type,
9284 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9285 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9288 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9290 // Make sure the lower and upper halves are both all-ones.
9291 const int Mask[] = { 1, 0, 3, 2 };
9292 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9293 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9296 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9298 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9302 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9303 // bits of the inputs before performing those operations.
9305 EVT EltVT = VT.getVectorElementType();
9306 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9308 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9309 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9311 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9312 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9315 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9317 // If the logical-not of the result is required, perform that now.
9319 Result = DAG.getNOT(dl, Result, VT);
9324 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9326 MVT VT = Op.getValueType().getSimpleVT();
9328 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9330 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9331 SDValue Op0 = Op.getOperand(0);
9332 SDValue Op1 = Op.getOperand(1);
9333 DebugLoc dl = Op.getDebugLoc();
9334 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9336 // Optimize to BT if possible.
9337 // Lower (X & (1 << N)) == 0 to BT(X, N).
9338 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9339 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9340 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9341 Op1.getOpcode() == ISD::Constant &&
9342 cast<ConstantSDNode>(Op1)->isNullValue() &&
9343 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9344 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9345 if (NewSetCC.getNode())
9349 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9351 if (Op1.getOpcode() == ISD::Constant &&
9352 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9353 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9354 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9356 // If the input is a setcc, then reuse the input setcc or use a new one with
9357 // the inverted condition.
9358 if (Op0.getOpcode() == X86ISD::SETCC) {
9359 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9360 bool Invert = (CC == ISD::SETNE) ^
9361 cast<ConstantSDNode>(Op1)->isNullValue();
9362 if (!Invert) return Op0;
9364 CCode = X86::GetOppositeBranchCondition(CCode);
9365 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9366 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9370 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9371 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9372 if (X86CC == X86::COND_INVALID)
9375 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9376 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9377 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9378 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9381 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9382 static bool isX86LogicalCmp(SDValue Op) {
9383 unsigned Opc = Op.getNode()->getOpcode();
9384 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9385 Opc == X86ISD::SAHF)
9387 if (Op.getResNo() == 1 &&
9388 (Opc == X86ISD::ADD ||
9389 Opc == X86ISD::SUB ||
9390 Opc == X86ISD::ADC ||
9391 Opc == X86ISD::SBB ||
9392 Opc == X86ISD::SMUL ||
9393 Opc == X86ISD::UMUL ||
9394 Opc == X86ISD::INC ||
9395 Opc == X86ISD::DEC ||
9396 Opc == X86ISD::OR ||
9397 Opc == X86ISD::XOR ||
9398 Opc == X86ISD::AND))
9401 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9407 static bool isZero(SDValue V) {
9408 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9409 return C && C->isNullValue();
9412 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9413 if (V.getOpcode() != ISD::TRUNCATE)
9416 SDValue VOp0 = V.getOperand(0);
9417 unsigned InBits = VOp0.getValueSizeInBits();
9418 unsigned Bits = V.getValueSizeInBits();
9419 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9422 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9423 bool addTest = true;
9424 SDValue Cond = Op.getOperand(0);
9425 SDValue Op1 = Op.getOperand(1);
9426 SDValue Op2 = Op.getOperand(2);
9427 DebugLoc DL = Op.getDebugLoc();
9430 if (Cond.getOpcode() == ISD::SETCC) {
9431 SDValue NewCond = LowerSETCC(Cond, DAG);
9432 if (NewCond.getNode())
9436 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9437 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9438 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9439 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9440 if (Cond.getOpcode() == X86ISD::SETCC &&
9441 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9442 isZero(Cond.getOperand(1).getOperand(1))) {
9443 SDValue Cmp = Cond.getOperand(1);
9445 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9447 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9448 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9449 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9451 SDValue CmpOp0 = Cmp.getOperand(0);
9452 // Apply further optimizations for special cases
9453 // (select (x != 0), -1, 0) -> neg & sbb
9454 // (select (x == 0), 0, -1) -> neg & sbb
9455 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9456 if (YC->isNullValue() &&
9457 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9458 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9459 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9460 DAG.getConstant(0, CmpOp0.getValueType()),
9462 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9463 DAG.getConstant(X86::COND_B, MVT::i8),
9464 SDValue(Neg.getNode(), 1));
9468 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9469 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9470 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9472 SDValue Res = // Res = 0 or -1.
9473 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9474 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9476 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9477 Res = DAG.getNOT(DL, Res, Res.getValueType());
9479 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9480 if (N2C == 0 || !N2C->isNullValue())
9481 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9486 // Look past (and (setcc_carry (cmp ...)), 1).
9487 if (Cond.getOpcode() == ISD::AND &&
9488 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9489 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9490 if (C && C->getAPIntValue() == 1)
9491 Cond = Cond.getOperand(0);
9494 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9495 // setting operand in place of the X86ISD::SETCC.
9496 unsigned CondOpcode = Cond.getOpcode();
9497 if (CondOpcode == X86ISD::SETCC ||
9498 CondOpcode == X86ISD::SETCC_CARRY) {
9499 CC = Cond.getOperand(0);
9501 SDValue Cmp = Cond.getOperand(1);
9502 unsigned Opc = Cmp.getOpcode();
9503 MVT VT = Op.getValueType().getSimpleVT();
9505 bool IllegalFPCMov = false;
9506 if (VT.isFloatingPoint() && !VT.isVector() &&
9507 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9508 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9510 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9511 Opc == X86ISD::BT) { // FIXME
9515 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9516 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9517 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9518 Cond.getOperand(0).getValueType() != MVT::i8)) {
9519 SDValue LHS = Cond.getOperand(0);
9520 SDValue RHS = Cond.getOperand(1);
9524 switch (CondOpcode) {
9525 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9526 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9527 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9528 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9529 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9530 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9531 default: llvm_unreachable("unexpected overflowing operator");
9533 if (CondOpcode == ISD::UMULO)
9534 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9537 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9539 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9541 if (CondOpcode == ISD::UMULO)
9542 Cond = X86Op.getValue(2);
9544 Cond = X86Op.getValue(1);
9546 CC = DAG.getConstant(X86Cond, MVT::i8);
9551 // Look pass the truncate if the high bits are known zero.
9552 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9553 Cond = Cond.getOperand(0);
9555 // We know the result of AND is compared against zero. Try to match
9557 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9558 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9559 if (NewSetCC.getNode()) {
9560 CC = NewSetCC.getOperand(0);
9561 Cond = NewSetCC.getOperand(1);
9568 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9569 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9572 // a < b ? -1 : 0 -> RES = ~setcc_carry
9573 // a < b ? 0 : -1 -> RES = setcc_carry
9574 // a >= b ? -1 : 0 -> RES = setcc_carry
9575 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9576 if (Cond.getOpcode() == X86ISD::SUB) {
9577 Cond = ConvertCmpIfNecessary(Cond, DAG);
9578 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9580 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9581 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9582 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9583 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9584 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9585 return DAG.getNOT(DL, Res, Res.getValueType());
9590 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9591 // widen the cmov and push the truncate through. This avoids introducing a new
9592 // branch during isel and doesn't add any extensions.
9593 if (Op.getValueType() == MVT::i8 &&
9594 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9595 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9596 if (T1.getValueType() == T2.getValueType() &&
9597 // Blacklist CopyFromReg to avoid partial register stalls.
9598 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9599 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9600 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9601 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9605 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9606 // condition is true.
9607 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9608 SDValue Ops[] = { Op2, Op1, CC, Cond };
9609 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9612 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9613 SelectionDAG &DAG) const {
9614 MVT VT = Op->getValueType(0).getSimpleVT();
9615 SDValue In = Op->getOperand(0);
9616 MVT InVT = In.getValueType().getSimpleVT();
9617 DebugLoc dl = Op->getDebugLoc();
9619 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9620 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9623 if (Subtarget->hasInt256())
9624 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9626 // Optimize vectors in AVX mode
9627 // Sign extend v8i16 to v8i32 and
9630 // Divide input vector into two parts
9631 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9632 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9633 // concat the vectors to original VT
9635 unsigned NumElems = InVT.getVectorNumElements();
9636 SDValue Undef = DAG.getUNDEF(InVT);
9638 SmallVector<int,8> ShufMask1(NumElems, -1);
9639 for (unsigned i = 0; i != NumElems/2; ++i)
9642 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9644 SmallVector<int,8> ShufMask2(NumElems, -1);
9645 for (unsigned i = 0; i != NumElems/2; ++i)
9646 ShufMask2[i] = i + NumElems/2;
9648 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9650 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9651 VT.getVectorNumElements()/2);
9653 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9654 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9656 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9659 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9660 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9661 // from the AND / OR.
9662 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9663 Opc = Op.getOpcode();
9664 if (Opc != ISD::OR && Opc != ISD::AND)
9666 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9667 Op.getOperand(0).hasOneUse() &&
9668 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9669 Op.getOperand(1).hasOneUse());
9672 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9673 // 1 and that the SETCC node has a single use.
9674 static bool isXor1OfSetCC(SDValue Op) {
9675 if (Op.getOpcode() != ISD::XOR)
9677 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9678 if (N1C && N1C->getAPIntValue() == 1) {
9679 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9680 Op.getOperand(0).hasOneUse();
9685 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9686 bool addTest = true;
9687 SDValue Chain = Op.getOperand(0);
9688 SDValue Cond = Op.getOperand(1);
9689 SDValue Dest = Op.getOperand(2);
9690 DebugLoc dl = Op.getDebugLoc();
9692 bool Inverted = false;
9694 if (Cond.getOpcode() == ISD::SETCC) {
9695 // Check for setcc([su]{add,sub,mul}o == 0).
9696 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9697 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9698 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9699 Cond.getOperand(0).getResNo() == 1 &&
9700 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9701 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9702 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9703 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9704 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9705 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9707 Cond = Cond.getOperand(0);
9709 SDValue NewCond = LowerSETCC(Cond, DAG);
9710 if (NewCond.getNode())
9715 // FIXME: LowerXALUO doesn't handle these!!
9716 else if (Cond.getOpcode() == X86ISD::ADD ||
9717 Cond.getOpcode() == X86ISD::SUB ||
9718 Cond.getOpcode() == X86ISD::SMUL ||
9719 Cond.getOpcode() == X86ISD::UMUL)
9720 Cond = LowerXALUO(Cond, DAG);
9723 // Look pass (and (setcc_carry (cmp ...)), 1).
9724 if (Cond.getOpcode() == ISD::AND &&
9725 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9726 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9727 if (C && C->getAPIntValue() == 1)
9728 Cond = Cond.getOperand(0);
9731 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9732 // setting operand in place of the X86ISD::SETCC.
9733 unsigned CondOpcode = Cond.getOpcode();
9734 if (CondOpcode == X86ISD::SETCC ||
9735 CondOpcode == X86ISD::SETCC_CARRY) {
9736 CC = Cond.getOperand(0);
9738 SDValue Cmp = Cond.getOperand(1);
9739 unsigned Opc = Cmp.getOpcode();
9740 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9741 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9745 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9749 // These can only come from an arithmetic instruction with overflow,
9750 // e.g. SADDO, UADDO.
9751 Cond = Cond.getNode()->getOperand(1);
9757 CondOpcode = Cond.getOpcode();
9758 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9759 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9760 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9761 Cond.getOperand(0).getValueType() != MVT::i8)) {
9762 SDValue LHS = Cond.getOperand(0);
9763 SDValue RHS = Cond.getOperand(1);
9767 switch (CondOpcode) {
9768 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9769 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9770 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9771 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9772 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9773 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9774 default: llvm_unreachable("unexpected overflowing operator");
9777 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9778 if (CondOpcode == ISD::UMULO)
9779 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9782 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9784 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9786 if (CondOpcode == ISD::UMULO)
9787 Cond = X86Op.getValue(2);
9789 Cond = X86Op.getValue(1);
9791 CC = DAG.getConstant(X86Cond, MVT::i8);
9795 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9796 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9797 if (CondOpc == ISD::OR) {
9798 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9799 // two branches instead of an explicit OR instruction with a
9801 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9802 isX86LogicalCmp(Cmp)) {
9803 CC = Cond.getOperand(0).getOperand(0);
9804 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9805 Chain, Dest, CC, Cmp);
9806 CC = Cond.getOperand(1).getOperand(0);
9810 } else { // ISD::AND
9811 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9812 // two branches instead of an explicit AND instruction with a
9813 // separate test. However, we only do this if this block doesn't
9814 // have a fall-through edge, because this requires an explicit
9815 // jmp when the condition is false.
9816 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9817 isX86LogicalCmp(Cmp) &&
9818 Op.getNode()->hasOneUse()) {
9819 X86::CondCode CCode =
9820 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9821 CCode = X86::GetOppositeBranchCondition(CCode);
9822 CC = DAG.getConstant(CCode, MVT::i8);
9823 SDNode *User = *Op.getNode()->use_begin();
9824 // Look for an unconditional branch following this conditional branch.
9825 // We need this because we need to reverse the successors in order
9826 // to implement FCMP_OEQ.
9827 if (User->getOpcode() == ISD::BR) {
9828 SDValue FalseBB = User->getOperand(1);
9830 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9831 assert(NewBR == User);
9835 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9836 Chain, Dest, CC, Cmp);
9837 X86::CondCode CCode =
9838 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9839 CCode = X86::GetOppositeBranchCondition(CCode);
9840 CC = DAG.getConstant(CCode, MVT::i8);
9846 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9847 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9848 // It should be transformed during dag combiner except when the condition
9849 // is set by a arithmetics with overflow node.
9850 X86::CondCode CCode =
9851 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9852 CCode = X86::GetOppositeBranchCondition(CCode);
9853 CC = DAG.getConstant(CCode, MVT::i8);
9854 Cond = Cond.getOperand(0).getOperand(1);
9856 } else if (Cond.getOpcode() == ISD::SETCC &&
9857 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9858 // For FCMP_OEQ, we can emit
9859 // two branches instead of an explicit AND instruction with a
9860 // separate test. However, we only do this if this block doesn't
9861 // have a fall-through edge, because this requires an explicit
9862 // jmp when the condition is false.
9863 if (Op.getNode()->hasOneUse()) {
9864 SDNode *User = *Op.getNode()->use_begin();
9865 // Look for an unconditional branch following this conditional branch.
9866 // We need this because we need to reverse the successors in order
9867 // to implement FCMP_OEQ.
9868 if (User->getOpcode() == ISD::BR) {
9869 SDValue FalseBB = User->getOperand(1);
9871 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9872 assert(NewBR == User);
9876 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9877 Cond.getOperand(0), Cond.getOperand(1));
9878 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9879 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9880 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9881 Chain, Dest, CC, Cmp);
9882 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9887 } else if (Cond.getOpcode() == ISD::SETCC &&
9888 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9889 // For FCMP_UNE, we can emit
9890 // two branches instead of an explicit AND instruction with a
9891 // separate test. However, we only do this if this block doesn't
9892 // have a fall-through edge, because this requires an explicit
9893 // jmp when the condition is false.
9894 if (Op.getNode()->hasOneUse()) {
9895 SDNode *User = *Op.getNode()->use_begin();
9896 // Look for an unconditional branch following this conditional branch.
9897 // We need this because we need to reverse the successors in order
9898 // to implement FCMP_UNE.
9899 if (User->getOpcode() == ISD::BR) {
9900 SDValue FalseBB = User->getOperand(1);
9902 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9903 assert(NewBR == User);
9906 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9907 Cond.getOperand(0), Cond.getOperand(1));
9908 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9909 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9910 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9911 Chain, Dest, CC, Cmp);
9912 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9922 // Look pass the truncate if the high bits are known zero.
9923 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9924 Cond = Cond.getOperand(0);
9926 // We know the result of AND is compared against zero. Try to match
9928 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9929 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9930 if (NewSetCC.getNode()) {
9931 CC = NewSetCC.getOperand(0);
9932 Cond = NewSetCC.getOperand(1);
9939 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9940 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9942 Cond = ConvertCmpIfNecessary(Cond, DAG);
9943 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9944 Chain, Dest, CC, Cond);
9947 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9948 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9949 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9950 // that the guard pages used by the OS virtual memory manager are allocated in
9951 // correct sequence.
9953 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9954 SelectionDAG &DAG) const {
9955 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9956 getTargetMachine().Options.EnableSegmentedStacks) &&
9957 "This should be used only on Windows targets or when segmented stacks "
9959 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9960 DebugLoc dl = Op.getDebugLoc();
9963 SDValue Chain = Op.getOperand(0);
9964 SDValue Size = Op.getOperand(1);
9965 // FIXME: Ensure alignment here
9967 bool Is64Bit = Subtarget->is64Bit();
9968 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9970 if (getTargetMachine().Options.EnableSegmentedStacks) {
9971 MachineFunction &MF = DAG.getMachineFunction();
9972 MachineRegisterInfo &MRI = MF.getRegInfo();
9975 // The 64 bit implementation of segmented stacks needs to clobber both r10
9976 // r11. This makes it impossible to use it along with nested parameters.
9977 const Function *F = MF.getFunction();
9979 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9981 if (I->hasNestAttr())
9982 report_fatal_error("Cannot use segmented stacks with functions that "
9983 "have nested arguments.");
9986 const TargetRegisterClass *AddrRegClass =
9987 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9988 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9989 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9990 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9991 DAG.getRegister(Vreg, SPTy));
9992 SDValue Ops1[2] = { Value, Chain };
9993 return DAG.getMergeValues(Ops1, 2, dl);
9996 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9998 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9999 Flag = Chain.getValue(1);
10000 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10002 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10003 Flag = Chain.getValue(1);
10005 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10008 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10009 return DAG.getMergeValues(Ops1, 2, dl);
10013 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10014 MachineFunction &MF = DAG.getMachineFunction();
10015 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10017 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10018 DebugLoc DL = Op.getDebugLoc();
10020 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10021 // vastart just stores the address of the VarArgsFrameIndex slot into the
10022 // memory location argument.
10023 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10025 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10026 MachinePointerInfo(SV), false, false, 0);
10030 // gp_offset (0 - 6 * 8)
10031 // fp_offset (48 - 48 + 8 * 16)
10032 // overflow_arg_area (point to parameters coming in memory).
10034 SmallVector<SDValue, 8> MemOps;
10035 SDValue FIN = Op.getOperand(1);
10037 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10038 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10040 FIN, MachinePointerInfo(SV), false, false, 0);
10041 MemOps.push_back(Store);
10044 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10045 FIN, DAG.getIntPtrConstant(4));
10046 Store = DAG.getStore(Op.getOperand(0), DL,
10047 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10049 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10050 MemOps.push_back(Store);
10052 // Store ptr to overflow_arg_area
10053 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10054 FIN, DAG.getIntPtrConstant(4));
10055 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10057 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10058 MachinePointerInfo(SV, 8),
10060 MemOps.push_back(Store);
10062 // Store ptr to reg_save_area.
10063 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10064 FIN, DAG.getIntPtrConstant(8));
10065 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10067 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10068 MachinePointerInfo(SV, 16), false, false, 0);
10069 MemOps.push_back(Store);
10070 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10071 &MemOps[0], MemOps.size());
10074 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10075 assert(Subtarget->is64Bit() &&
10076 "LowerVAARG only handles 64-bit va_arg!");
10077 assert((Subtarget->isTargetLinux() ||
10078 Subtarget->isTargetDarwin()) &&
10079 "Unhandled target in LowerVAARG");
10080 assert(Op.getNode()->getNumOperands() == 4);
10081 SDValue Chain = Op.getOperand(0);
10082 SDValue SrcPtr = Op.getOperand(1);
10083 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10084 unsigned Align = Op.getConstantOperandVal(3);
10085 DebugLoc dl = Op.getDebugLoc();
10087 EVT ArgVT = Op.getNode()->getValueType(0);
10088 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10089 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10092 // Decide which area this value should be read from.
10093 // TODO: Implement the AMD64 ABI in its entirety. This simple
10094 // selection mechanism works only for the basic types.
10095 if (ArgVT == MVT::f80) {
10096 llvm_unreachable("va_arg for f80 not yet implemented");
10097 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10098 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10099 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10100 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10102 llvm_unreachable("Unhandled argument type in LowerVAARG");
10105 if (ArgMode == 2) {
10106 // Sanity Check: Make sure using fp_offset makes sense.
10107 assert(!getTargetMachine().Options.UseSoftFloat &&
10108 !(DAG.getMachineFunction()
10109 .getFunction()->getAttributes()
10110 .hasAttribute(AttributeSet::FunctionIndex,
10111 Attribute::NoImplicitFloat)) &&
10112 Subtarget->hasSSE1());
10115 // Insert VAARG_64 node into the DAG
10116 // VAARG_64 returns two values: Variable Argument Address, Chain
10117 SmallVector<SDValue, 11> InstOps;
10118 InstOps.push_back(Chain);
10119 InstOps.push_back(SrcPtr);
10120 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10121 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10122 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10123 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10124 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10125 VTs, &InstOps[0], InstOps.size(),
10127 MachinePointerInfo(SV),
10129 /*Volatile=*/false,
10131 /*WriteMem=*/true);
10132 Chain = VAARG.getValue(1);
10134 // Load the next argument and return it
10135 return DAG.getLoad(ArgVT, dl,
10138 MachinePointerInfo(),
10139 false, false, false, 0);
10142 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10143 SelectionDAG &DAG) {
10144 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10145 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10146 SDValue Chain = Op.getOperand(0);
10147 SDValue DstPtr = Op.getOperand(1);
10148 SDValue SrcPtr = Op.getOperand(2);
10149 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10150 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10151 DebugLoc DL = Op.getDebugLoc();
10153 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10154 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10156 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10159 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10160 // may or may not be a constant. Takes immediate version of shift as input.
10161 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10162 SDValue SrcOp, SDValue ShAmt,
10163 SelectionDAG &DAG) {
10164 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10166 if (isa<ConstantSDNode>(ShAmt)) {
10167 // Constant may be a TargetConstant. Use a regular constant.
10168 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10170 default: llvm_unreachable("Unknown target vector shift node");
10171 case X86ISD::VSHLI:
10172 case X86ISD::VSRLI:
10173 case X86ISD::VSRAI:
10174 return DAG.getNode(Opc, dl, VT, SrcOp,
10175 DAG.getConstant(ShiftAmt, MVT::i32));
10179 // Change opcode to non-immediate version
10181 default: llvm_unreachable("Unknown target vector shift node");
10182 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10183 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10184 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10187 // Need to build a vector containing shift amount
10188 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10191 ShOps[1] = DAG.getConstant(0, MVT::i32);
10192 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10193 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10195 // The return type has to be a 128-bit type with the same element
10196 // type as the input type.
10197 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10198 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10200 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10201 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10204 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10205 DebugLoc dl = Op.getDebugLoc();
10206 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10208 default: return SDValue(); // Don't custom lower most intrinsics.
10209 // Comparison intrinsics.
10210 case Intrinsic::x86_sse_comieq_ss:
10211 case Intrinsic::x86_sse_comilt_ss:
10212 case Intrinsic::x86_sse_comile_ss:
10213 case Intrinsic::x86_sse_comigt_ss:
10214 case Intrinsic::x86_sse_comige_ss:
10215 case Intrinsic::x86_sse_comineq_ss:
10216 case Intrinsic::x86_sse_ucomieq_ss:
10217 case Intrinsic::x86_sse_ucomilt_ss:
10218 case Intrinsic::x86_sse_ucomile_ss:
10219 case Intrinsic::x86_sse_ucomigt_ss:
10220 case Intrinsic::x86_sse_ucomige_ss:
10221 case Intrinsic::x86_sse_ucomineq_ss:
10222 case Intrinsic::x86_sse2_comieq_sd:
10223 case Intrinsic::x86_sse2_comilt_sd:
10224 case Intrinsic::x86_sse2_comile_sd:
10225 case Intrinsic::x86_sse2_comigt_sd:
10226 case Intrinsic::x86_sse2_comige_sd:
10227 case Intrinsic::x86_sse2_comineq_sd:
10228 case Intrinsic::x86_sse2_ucomieq_sd:
10229 case Intrinsic::x86_sse2_ucomilt_sd:
10230 case Intrinsic::x86_sse2_ucomile_sd:
10231 case Intrinsic::x86_sse2_ucomigt_sd:
10232 case Intrinsic::x86_sse2_ucomige_sd:
10233 case Intrinsic::x86_sse2_ucomineq_sd: {
10237 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10238 case Intrinsic::x86_sse_comieq_ss:
10239 case Intrinsic::x86_sse2_comieq_sd:
10240 Opc = X86ISD::COMI;
10243 case Intrinsic::x86_sse_comilt_ss:
10244 case Intrinsic::x86_sse2_comilt_sd:
10245 Opc = X86ISD::COMI;
10248 case Intrinsic::x86_sse_comile_ss:
10249 case Intrinsic::x86_sse2_comile_sd:
10250 Opc = X86ISD::COMI;
10253 case Intrinsic::x86_sse_comigt_ss:
10254 case Intrinsic::x86_sse2_comigt_sd:
10255 Opc = X86ISD::COMI;
10258 case Intrinsic::x86_sse_comige_ss:
10259 case Intrinsic::x86_sse2_comige_sd:
10260 Opc = X86ISD::COMI;
10263 case Intrinsic::x86_sse_comineq_ss:
10264 case Intrinsic::x86_sse2_comineq_sd:
10265 Opc = X86ISD::COMI;
10268 case Intrinsic::x86_sse_ucomieq_ss:
10269 case Intrinsic::x86_sse2_ucomieq_sd:
10270 Opc = X86ISD::UCOMI;
10273 case Intrinsic::x86_sse_ucomilt_ss:
10274 case Intrinsic::x86_sse2_ucomilt_sd:
10275 Opc = X86ISD::UCOMI;
10278 case Intrinsic::x86_sse_ucomile_ss:
10279 case Intrinsic::x86_sse2_ucomile_sd:
10280 Opc = X86ISD::UCOMI;
10283 case Intrinsic::x86_sse_ucomigt_ss:
10284 case Intrinsic::x86_sse2_ucomigt_sd:
10285 Opc = X86ISD::UCOMI;
10288 case Intrinsic::x86_sse_ucomige_ss:
10289 case Intrinsic::x86_sse2_ucomige_sd:
10290 Opc = X86ISD::UCOMI;
10293 case Intrinsic::x86_sse_ucomineq_ss:
10294 case Intrinsic::x86_sse2_ucomineq_sd:
10295 Opc = X86ISD::UCOMI;
10300 SDValue LHS = Op.getOperand(1);
10301 SDValue RHS = Op.getOperand(2);
10302 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10303 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10304 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10305 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10306 DAG.getConstant(X86CC, MVT::i8), Cond);
10307 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10310 // Arithmetic intrinsics.
10311 case Intrinsic::x86_sse2_pmulu_dq:
10312 case Intrinsic::x86_avx2_pmulu_dq:
10313 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10314 Op.getOperand(1), Op.getOperand(2));
10316 // SSE2/AVX2 sub with unsigned saturation intrinsics
10317 case Intrinsic::x86_sse2_psubus_b:
10318 case Intrinsic::x86_sse2_psubus_w:
10319 case Intrinsic::x86_avx2_psubus_b:
10320 case Intrinsic::x86_avx2_psubus_w:
10321 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10322 Op.getOperand(1), Op.getOperand(2));
10324 // SSE3/AVX horizontal add/sub intrinsics
10325 case Intrinsic::x86_sse3_hadd_ps:
10326 case Intrinsic::x86_sse3_hadd_pd:
10327 case Intrinsic::x86_avx_hadd_ps_256:
10328 case Intrinsic::x86_avx_hadd_pd_256:
10329 case Intrinsic::x86_sse3_hsub_ps:
10330 case Intrinsic::x86_sse3_hsub_pd:
10331 case Intrinsic::x86_avx_hsub_ps_256:
10332 case Intrinsic::x86_avx_hsub_pd_256:
10333 case Intrinsic::x86_ssse3_phadd_w_128:
10334 case Intrinsic::x86_ssse3_phadd_d_128:
10335 case Intrinsic::x86_avx2_phadd_w:
10336 case Intrinsic::x86_avx2_phadd_d:
10337 case Intrinsic::x86_ssse3_phsub_w_128:
10338 case Intrinsic::x86_ssse3_phsub_d_128:
10339 case Intrinsic::x86_avx2_phsub_w:
10340 case Intrinsic::x86_avx2_phsub_d: {
10343 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10344 case Intrinsic::x86_sse3_hadd_ps:
10345 case Intrinsic::x86_sse3_hadd_pd:
10346 case Intrinsic::x86_avx_hadd_ps_256:
10347 case Intrinsic::x86_avx_hadd_pd_256:
10348 Opcode = X86ISD::FHADD;
10350 case Intrinsic::x86_sse3_hsub_ps:
10351 case Intrinsic::x86_sse3_hsub_pd:
10352 case Intrinsic::x86_avx_hsub_ps_256:
10353 case Intrinsic::x86_avx_hsub_pd_256:
10354 Opcode = X86ISD::FHSUB;
10356 case Intrinsic::x86_ssse3_phadd_w_128:
10357 case Intrinsic::x86_ssse3_phadd_d_128:
10358 case Intrinsic::x86_avx2_phadd_w:
10359 case Intrinsic::x86_avx2_phadd_d:
10360 Opcode = X86ISD::HADD;
10362 case Intrinsic::x86_ssse3_phsub_w_128:
10363 case Intrinsic::x86_ssse3_phsub_d_128:
10364 case Intrinsic::x86_avx2_phsub_w:
10365 case Intrinsic::x86_avx2_phsub_d:
10366 Opcode = X86ISD::HSUB;
10369 return DAG.getNode(Opcode, dl, Op.getValueType(),
10370 Op.getOperand(1), Op.getOperand(2));
10373 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10374 case Intrinsic::x86_sse2_pmaxu_b:
10375 case Intrinsic::x86_sse41_pmaxuw:
10376 case Intrinsic::x86_sse41_pmaxud:
10377 case Intrinsic::x86_avx2_pmaxu_b:
10378 case Intrinsic::x86_avx2_pmaxu_w:
10379 case Intrinsic::x86_avx2_pmaxu_d:
10380 case Intrinsic::x86_sse2_pminu_b:
10381 case Intrinsic::x86_sse41_pminuw:
10382 case Intrinsic::x86_sse41_pminud:
10383 case Intrinsic::x86_avx2_pminu_b:
10384 case Intrinsic::x86_avx2_pminu_w:
10385 case Intrinsic::x86_avx2_pminu_d:
10386 case Intrinsic::x86_sse41_pmaxsb:
10387 case Intrinsic::x86_sse2_pmaxs_w:
10388 case Intrinsic::x86_sse41_pmaxsd:
10389 case Intrinsic::x86_avx2_pmaxs_b:
10390 case Intrinsic::x86_avx2_pmaxs_w:
10391 case Intrinsic::x86_avx2_pmaxs_d:
10392 case Intrinsic::x86_sse41_pminsb:
10393 case Intrinsic::x86_sse2_pmins_w:
10394 case Intrinsic::x86_sse41_pminsd:
10395 case Intrinsic::x86_avx2_pmins_b:
10396 case Intrinsic::x86_avx2_pmins_w:
10397 case Intrinsic::x86_avx2_pmins_d: {
10400 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10401 case Intrinsic::x86_sse2_pmaxu_b:
10402 case Intrinsic::x86_sse41_pmaxuw:
10403 case Intrinsic::x86_sse41_pmaxud:
10404 case Intrinsic::x86_avx2_pmaxu_b:
10405 case Intrinsic::x86_avx2_pmaxu_w:
10406 case Intrinsic::x86_avx2_pmaxu_d:
10407 Opcode = X86ISD::UMAX;
10409 case Intrinsic::x86_sse2_pminu_b:
10410 case Intrinsic::x86_sse41_pminuw:
10411 case Intrinsic::x86_sse41_pminud:
10412 case Intrinsic::x86_avx2_pminu_b:
10413 case Intrinsic::x86_avx2_pminu_w:
10414 case Intrinsic::x86_avx2_pminu_d:
10415 Opcode = X86ISD::UMIN;
10417 case Intrinsic::x86_sse41_pmaxsb:
10418 case Intrinsic::x86_sse2_pmaxs_w:
10419 case Intrinsic::x86_sse41_pmaxsd:
10420 case Intrinsic::x86_avx2_pmaxs_b:
10421 case Intrinsic::x86_avx2_pmaxs_w:
10422 case Intrinsic::x86_avx2_pmaxs_d:
10423 Opcode = X86ISD::SMAX;
10425 case Intrinsic::x86_sse41_pminsb:
10426 case Intrinsic::x86_sse2_pmins_w:
10427 case Intrinsic::x86_sse41_pminsd:
10428 case Intrinsic::x86_avx2_pmins_b:
10429 case Intrinsic::x86_avx2_pmins_w:
10430 case Intrinsic::x86_avx2_pmins_d:
10431 Opcode = X86ISD::SMIN;
10434 return DAG.getNode(Opcode, dl, Op.getValueType(),
10435 Op.getOperand(1), Op.getOperand(2));
10438 // SSE/SSE2/AVX floating point max/min intrinsics.
10439 case Intrinsic::x86_sse_max_ps:
10440 case Intrinsic::x86_sse2_max_pd:
10441 case Intrinsic::x86_avx_max_ps_256:
10442 case Intrinsic::x86_avx_max_pd_256:
10443 case Intrinsic::x86_sse_min_ps:
10444 case Intrinsic::x86_sse2_min_pd:
10445 case Intrinsic::x86_avx_min_ps_256:
10446 case Intrinsic::x86_avx_min_pd_256: {
10449 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10450 case Intrinsic::x86_sse_max_ps:
10451 case Intrinsic::x86_sse2_max_pd:
10452 case Intrinsic::x86_avx_max_ps_256:
10453 case Intrinsic::x86_avx_max_pd_256:
10454 Opcode = X86ISD::FMAX;
10456 case Intrinsic::x86_sse_min_ps:
10457 case Intrinsic::x86_sse2_min_pd:
10458 case Intrinsic::x86_avx_min_ps_256:
10459 case Intrinsic::x86_avx_min_pd_256:
10460 Opcode = X86ISD::FMIN;
10463 return DAG.getNode(Opcode, dl, Op.getValueType(),
10464 Op.getOperand(1), Op.getOperand(2));
10467 // AVX2 variable shift intrinsics
10468 case Intrinsic::x86_avx2_psllv_d:
10469 case Intrinsic::x86_avx2_psllv_q:
10470 case Intrinsic::x86_avx2_psllv_d_256:
10471 case Intrinsic::x86_avx2_psllv_q_256:
10472 case Intrinsic::x86_avx2_psrlv_d:
10473 case Intrinsic::x86_avx2_psrlv_q:
10474 case Intrinsic::x86_avx2_psrlv_d_256:
10475 case Intrinsic::x86_avx2_psrlv_q_256:
10476 case Intrinsic::x86_avx2_psrav_d:
10477 case Intrinsic::x86_avx2_psrav_d_256: {
10480 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10481 case Intrinsic::x86_avx2_psllv_d:
10482 case Intrinsic::x86_avx2_psllv_q:
10483 case Intrinsic::x86_avx2_psllv_d_256:
10484 case Intrinsic::x86_avx2_psllv_q_256:
10487 case Intrinsic::x86_avx2_psrlv_d:
10488 case Intrinsic::x86_avx2_psrlv_q:
10489 case Intrinsic::x86_avx2_psrlv_d_256:
10490 case Intrinsic::x86_avx2_psrlv_q_256:
10493 case Intrinsic::x86_avx2_psrav_d:
10494 case Intrinsic::x86_avx2_psrav_d_256:
10498 return DAG.getNode(Opcode, dl, Op.getValueType(),
10499 Op.getOperand(1), Op.getOperand(2));
10502 case Intrinsic::x86_ssse3_pshuf_b_128:
10503 case Intrinsic::x86_avx2_pshuf_b:
10504 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10505 Op.getOperand(1), Op.getOperand(2));
10507 case Intrinsic::x86_ssse3_psign_b_128:
10508 case Intrinsic::x86_ssse3_psign_w_128:
10509 case Intrinsic::x86_ssse3_psign_d_128:
10510 case Intrinsic::x86_avx2_psign_b:
10511 case Intrinsic::x86_avx2_psign_w:
10512 case Intrinsic::x86_avx2_psign_d:
10513 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10514 Op.getOperand(1), Op.getOperand(2));
10516 case Intrinsic::x86_sse41_insertps:
10517 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10518 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10520 case Intrinsic::x86_avx_vperm2f128_ps_256:
10521 case Intrinsic::x86_avx_vperm2f128_pd_256:
10522 case Intrinsic::x86_avx_vperm2f128_si_256:
10523 case Intrinsic::x86_avx2_vperm2i128:
10524 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10525 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10527 case Intrinsic::x86_avx2_permd:
10528 case Intrinsic::x86_avx2_permps:
10529 // Operands intentionally swapped. Mask is last operand to intrinsic,
10530 // but second operand for node/intruction.
10531 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10532 Op.getOperand(2), Op.getOperand(1));
10534 case Intrinsic::x86_sse_sqrt_ps:
10535 case Intrinsic::x86_sse2_sqrt_pd:
10536 case Intrinsic::x86_avx_sqrt_ps_256:
10537 case Intrinsic::x86_avx_sqrt_pd_256:
10538 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10540 // ptest and testp intrinsics. The intrinsic these come from are designed to
10541 // return an integer value, not just an instruction so lower it to the ptest
10542 // or testp pattern and a setcc for the result.
10543 case Intrinsic::x86_sse41_ptestz:
10544 case Intrinsic::x86_sse41_ptestc:
10545 case Intrinsic::x86_sse41_ptestnzc:
10546 case Intrinsic::x86_avx_ptestz_256:
10547 case Intrinsic::x86_avx_ptestc_256:
10548 case Intrinsic::x86_avx_ptestnzc_256:
10549 case Intrinsic::x86_avx_vtestz_ps:
10550 case Intrinsic::x86_avx_vtestc_ps:
10551 case Intrinsic::x86_avx_vtestnzc_ps:
10552 case Intrinsic::x86_avx_vtestz_pd:
10553 case Intrinsic::x86_avx_vtestc_pd:
10554 case Intrinsic::x86_avx_vtestnzc_pd:
10555 case Intrinsic::x86_avx_vtestz_ps_256:
10556 case Intrinsic::x86_avx_vtestc_ps_256:
10557 case Intrinsic::x86_avx_vtestnzc_ps_256:
10558 case Intrinsic::x86_avx_vtestz_pd_256:
10559 case Intrinsic::x86_avx_vtestc_pd_256:
10560 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10561 bool IsTestPacked = false;
10564 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10565 case Intrinsic::x86_avx_vtestz_ps:
10566 case Intrinsic::x86_avx_vtestz_pd:
10567 case Intrinsic::x86_avx_vtestz_ps_256:
10568 case Intrinsic::x86_avx_vtestz_pd_256:
10569 IsTestPacked = true; // Fallthrough
10570 case Intrinsic::x86_sse41_ptestz:
10571 case Intrinsic::x86_avx_ptestz_256:
10573 X86CC = X86::COND_E;
10575 case Intrinsic::x86_avx_vtestc_ps:
10576 case Intrinsic::x86_avx_vtestc_pd:
10577 case Intrinsic::x86_avx_vtestc_ps_256:
10578 case Intrinsic::x86_avx_vtestc_pd_256:
10579 IsTestPacked = true; // Fallthrough
10580 case Intrinsic::x86_sse41_ptestc:
10581 case Intrinsic::x86_avx_ptestc_256:
10583 X86CC = X86::COND_B;
10585 case Intrinsic::x86_avx_vtestnzc_ps:
10586 case Intrinsic::x86_avx_vtestnzc_pd:
10587 case Intrinsic::x86_avx_vtestnzc_ps_256:
10588 case Intrinsic::x86_avx_vtestnzc_pd_256:
10589 IsTestPacked = true; // Fallthrough
10590 case Intrinsic::x86_sse41_ptestnzc:
10591 case Intrinsic::x86_avx_ptestnzc_256:
10593 X86CC = X86::COND_A;
10597 SDValue LHS = Op.getOperand(1);
10598 SDValue RHS = Op.getOperand(2);
10599 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10600 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10601 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10602 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10603 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10606 // SSE/AVX shift intrinsics
10607 case Intrinsic::x86_sse2_psll_w:
10608 case Intrinsic::x86_sse2_psll_d:
10609 case Intrinsic::x86_sse2_psll_q:
10610 case Intrinsic::x86_avx2_psll_w:
10611 case Intrinsic::x86_avx2_psll_d:
10612 case Intrinsic::x86_avx2_psll_q:
10613 case Intrinsic::x86_sse2_psrl_w:
10614 case Intrinsic::x86_sse2_psrl_d:
10615 case Intrinsic::x86_sse2_psrl_q:
10616 case Intrinsic::x86_avx2_psrl_w:
10617 case Intrinsic::x86_avx2_psrl_d:
10618 case Intrinsic::x86_avx2_psrl_q:
10619 case Intrinsic::x86_sse2_psra_w:
10620 case Intrinsic::x86_sse2_psra_d:
10621 case Intrinsic::x86_avx2_psra_w:
10622 case Intrinsic::x86_avx2_psra_d: {
10625 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10626 case Intrinsic::x86_sse2_psll_w:
10627 case Intrinsic::x86_sse2_psll_d:
10628 case Intrinsic::x86_sse2_psll_q:
10629 case Intrinsic::x86_avx2_psll_w:
10630 case Intrinsic::x86_avx2_psll_d:
10631 case Intrinsic::x86_avx2_psll_q:
10632 Opcode = X86ISD::VSHL;
10634 case Intrinsic::x86_sse2_psrl_w:
10635 case Intrinsic::x86_sse2_psrl_d:
10636 case Intrinsic::x86_sse2_psrl_q:
10637 case Intrinsic::x86_avx2_psrl_w:
10638 case Intrinsic::x86_avx2_psrl_d:
10639 case Intrinsic::x86_avx2_psrl_q:
10640 Opcode = X86ISD::VSRL;
10642 case Intrinsic::x86_sse2_psra_w:
10643 case Intrinsic::x86_sse2_psra_d:
10644 case Intrinsic::x86_avx2_psra_w:
10645 case Intrinsic::x86_avx2_psra_d:
10646 Opcode = X86ISD::VSRA;
10649 return DAG.getNode(Opcode, dl, Op.getValueType(),
10650 Op.getOperand(1), Op.getOperand(2));
10653 // SSE/AVX immediate shift intrinsics
10654 case Intrinsic::x86_sse2_pslli_w:
10655 case Intrinsic::x86_sse2_pslli_d:
10656 case Intrinsic::x86_sse2_pslli_q:
10657 case Intrinsic::x86_avx2_pslli_w:
10658 case Intrinsic::x86_avx2_pslli_d:
10659 case Intrinsic::x86_avx2_pslli_q:
10660 case Intrinsic::x86_sse2_psrli_w:
10661 case Intrinsic::x86_sse2_psrli_d:
10662 case Intrinsic::x86_sse2_psrli_q:
10663 case Intrinsic::x86_avx2_psrli_w:
10664 case Intrinsic::x86_avx2_psrli_d:
10665 case Intrinsic::x86_avx2_psrli_q:
10666 case Intrinsic::x86_sse2_psrai_w:
10667 case Intrinsic::x86_sse2_psrai_d:
10668 case Intrinsic::x86_avx2_psrai_w:
10669 case Intrinsic::x86_avx2_psrai_d: {
10672 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10673 case Intrinsic::x86_sse2_pslli_w:
10674 case Intrinsic::x86_sse2_pslli_d:
10675 case Intrinsic::x86_sse2_pslli_q:
10676 case Intrinsic::x86_avx2_pslli_w:
10677 case Intrinsic::x86_avx2_pslli_d:
10678 case Intrinsic::x86_avx2_pslli_q:
10679 Opcode = X86ISD::VSHLI;
10681 case Intrinsic::x86_sse2_psrli_w:
10682 case Intrinsic::x86_sse2_psrli_d:
10683 case Intrinsic::x86_sse2_psrli_q:
10684 case Intrinsic::x86_avx2_psrli_w:
10685 case Intrinsic::x86_avx2_psrli_d:
10686 case Intrinsic::x86_avx2_psrli_q:
10687 Opcode = X86ISD::VSRLI;
10689 case Intrinsic::x86_sse2_psrai_w:
10690 case Intrinsic::x86_sse2_psrai_d:
10691 case Intrinsic::x86_avx2_psrai_w:
10692 case Intrinsic::x86_avx2_psrai_d:
10693 Opcode = X86ISD::VSRAI;
10696 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10697 Op.getOperand(1), Op.getOperand(2), DAG);
10700 case Intrinsic::x86_sse42_pcmpistria128:
10701 case Intrinsic::x86_sse42_pcmpestria128:
10702 case Intrinsic::x86_sse42_pcmpistric128:
10703 case Intrinsic::x86_sse42_pcmpestric128:
10704 case Intrinsic::x86_sse42_pcmpistrio128:
10705 case Intrinsic::x86_sse42_pcmpestrio128:
10706 case Intrinsic::x86_sse42_pcmpistris128:
10707 case Intrinsic::x86_sse42_pcmpestris128:
10708 case Intrinsic::x86_sse42_pcmpistriz128:
10709 case Intrinsic::x86_sse42_pcmpestriz128: {
10713 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10714 case Intrinsic::x86_sse42_pcmpistria128:
10715 Opcode = X86ISD::PCMPISTRI;
10716 X86CC = X86::COND_A;
10718 case Intrinsic::x86_sse42_pcmpestria128:
10719 Opcode = X86ISD::PCMPESTRI;
10720 X86CC = X86::COND_A;
10722 case Intrinsic::x86_sse42_pcmpistric128:
10723 Opcode = X86ISD::PCMPISTRI;
10724 X86CC = X86::COND_B;
10726 case Intrinsic::x86_sse42_pcmpestric128:
10727 Opcode = X86ISD::PCMPESTRI;
10728 X86CC = X86::COND_B;
10730 case Intrinsic::x86_sse42_pcmpistrio128:
10731 Opcode = X86ISD::PCMPISTRI;
10732 X86CC = X86::COND_O;
10734 case Intrinsic::x86_sse42_pcmpestrio128:
10735 Opcode = X86ISD::PCMPESTRI;
10736 X86CC = X86::COND_O;
10738 case Intrinsic::x86_sse42_pcmpistris128:
10739 Opcode = X86ISD::PCMPISTRI;
10740 X86CC = X86::COND_S;
10742 case Intrinsic::x86_sse42_pcmpestris128:
10743 Opcode = X86ISD::PCMPESTRI;
10744 X86CC = X86::COND_S;
10746 case Intrinsic::x86_sse42_pcmpistriz128:
10747 Opcode = X86ISD::PCMPISTRI;
10748 X86CC = X86::COND_E;
10750 case Intrinsic::x86_sse42_pcmpestriz128:
10751 Opcode = X86ISD::PCMPESTRI;
10752 X86CC = X86::COND_E;
10755 SmallVector<SDValue, 5> NewOps;
10756 NewOps.append(Op->op_begin()+1, Op->op_end());
10757 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10758 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10759 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10760 DAG.getConstant(X86CC, MVT::i8),
10761 SDValue(PCMP.getNode(), 1));
10762 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10765 case Intrinsic::x86_sse42_pcmpistri128:
10766 case Intrinsic::x86_sse42_pcmpestri128: {
10768 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10769 Opcode = X86ISD::PCMPISTRI;
10771 Opcode = X86ISD::PCMPESTRI;
10773 SmallVector<SDValue, 5> NewOps;
10774 NewOps.append(Op->op_begin()+1, Op->op_end());
10775 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10776 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10778 case Intrinsic::x86_fma_vfmadd_ps:
10779 case Intrinsic::x86_fma_vfmadd_pd:
10780 case Intrinsic::x86_fma_vfmsub_ps:
10781 case Intrinsic::x86_fma_vfmsub_pd:
10782 case Intrinsic::x86_fma_vfnmadd_ps:
10783 case Intrinsic::x86_fma_vfnmadd_pd:
10784 case Intrinsic::x86_fma_vfnmsub_ps:
10785 case Intrinsic::x86_fma_vfnmsub_pd:
10786 case Intrinsic::x86_fma_vfmaddsub_ps:
10787 case Intrinsic::x86_fma_vfmaddsub_pd:
10788 case Intrinsic::x86_fma_vfmsubadd_ps:
10789 case Intrinsic::x86_fma_vfmsubadd_pd:
10790 case Intrinsic::x86_fma_vfmadd_ps_256:
10791 case Intrinsic::x86_fma_vfmadd_pd_256:
10792 case Intrinsic::x86_fma_vfmsub_ps_256:
10793 case Intrinsic::x86_fma_vfmsub_pd_256:
10794 case Intrinsic::x86_fma_vfnmadd_ps_256:
10795 case Intrinsic::x86_fma_vfnmadd_pd_256:
10796 case Intrinsic::x86_fma_vfnmsub_ps_256:
10797 case Intrinsic::x86_fma_vfnmsub_pd_256:
10798 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10799 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10800 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10801 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10804 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10805 case Intrinsic::x86_fma_vfmadd_ps:
10806 case Intrinsic::x86_fma_vfmadd_pd:
10807 case Intrinsic::x86_fma_vfmadd_ps_256:
10808 case Intrinsic::x86_fma_vfmadd_pd_256:
10809 Opc = X86ISD::FMADD;
10811 case Intrinsic::x86_fma_vfmsub_ps:
10812 case Intrinsic::x86_fma_vfmsub_pd:
10813 case Intrinsic::x86_fma_vfmsub_ps_256:
10814 case Intrinsic::x86_fma_vfmsub_pd_256:
10815 Opc = X86ISD::FMSUB;
10817 case Intrinsic::x86_fma_vfnmadd_ps:
10818 case Intrinsic::x86_fma_vfnmadd_pd:
10819 case Intrinsic::x86_fma_vfnmadd_ps_256:
10820 case Intrinsic::x86_fma_vfnmadd_pd_256:
10821 Opc = X86ISD::FNMADD;
10823 case Intrinsic::x86_fma_vfnmsub_ps:
10824 case Intrinsic::x86_fma_vfnmsub_pd:
10825 case Intrinsic::x86_fma_vfnmsub_ps_256:
10826 case Intrinsic::x86_fma_vfnmsub_pd_256:
10827 Opc = X86ISD::FNMSUB;
10829 case Intrinsic::x86_fma_vfmaddsub_ps:
10830 case Intrinsic::x86_fma_vfmaddsub_pd:
10831 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10832 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10833 Opc = X86ISD::FMADDSUB;
10835 case Intrinsic::x86_fma_vfmsubadd_ps:
10836 case Intrinsic::x86_fma_vfmsubadd_pd:
10837 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10838 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10839 Opc = X86ISD::FMSUBADD;
10843 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10844 Op.getOperand(2), Op.getOperand(3));
10849 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10850 DebugLoc dl = Op.getDebugLoc();
10851 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10853 default: return SDValue(); // Don't custom lower most intrinsics.
10855 // RDRAND intrinsics.
10856 case Intrinsic::x86_rdrand_16:
10857 case Intrinsic::x86_rdrand_32:
10858 case Intrinsic::x86_rdrand_64: {
10859 // Emit the node with the right value type.
10860 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10861 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10863 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10864 // return the value from Rand, which is always 0, casted to i32.
10865 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10866 DAG.getConstant(1, Op->getValueType(1)),
10867 DAG.getConstant(X86::COND_B, MVT::i32),
10868 SDValue(Result.getNode(), 1) };
10869 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10870 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10873 // Return { result, isValid, chain }.
10874 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10875 SDValue(Result.getNode(), 2));
10880 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10881 SelectionDAG &DAG) const {
10882 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10883 MFI->setReturnAddressIsTaken(true);
10885 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10886 DebugLoc dl = Op.getDebugLoc();
10887 EVT PtrVT = getPointerTy();
10890 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10892 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10893 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10894 DAG.getNode(ISD::ADD, dl, PtrVT,
10895 FrameAddr, Offset),
10896 MachinePointerInfo(), false, false, false, 0);
10899 // Just load the return address.
10900 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10901 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10902 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10905 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10906 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10907 MFI->setFrameAddressIsTaken(true);
10909 EVT VT = Op.getValueType();
10910 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10911 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10912 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10913 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10915 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10916 MachinePointerInfo(),
10917 false, false, false, 0);
10921 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10922 SelectionDAG &DAG) const {
10923 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10926 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10927 SDValue Chain = Op.getOperand(0);
10928 SDValue Offset = Op.getOperand(1);
10929 SDValue Handler = Op.getOperand(2);
10930 DebugLoc dl = Op.getDebugLoc();
10932 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10933 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10935 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10937 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10938 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10939 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10940 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10942 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10944 return DAG.getNode(X86ISD::EH_RETURN, dl,
10946 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10949 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10950 SelectionDAG &DAG) const {
10951 DebugLoc DL = Op.getDebugLoc();
10952 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10953 DAG.getVTList(MVT::i32, MVT::Other),
10954 Op.getOperand(0), Op.getOperand(1));
10957 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10958 SelectionDAG &DAG) const {
10959 DebugLoc DL = Op.getDebugLoc();
10960 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10961 Op.getOperand(0), Op.getOperand(1));
10964 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10965 return Op.getOperand(0);
10968 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10969 SelectionDAG &DAG) const {
10970 SDValue Root = Op.getOperand(0);
10971 SDValue Trmp = Op.getOperand(1); // trampoline
10972 SDValue FPtr = Op.getOperand(2); // nested function
10973 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10974 DebugLoc dl = Op.getDebugLoc();
10976 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10977 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10979 if (Subtarget->is64Bit()) {
10980 SDValue OutChains[6];
10982 // Large code-model.
10983 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10984 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10986 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10987 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10989 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10991 // Load the pointer to the nested function into R11.
10992 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10993 SDValue Addr = Trmp;
10994 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10995 Addr, MachinePointerInfo(TrmpAddr),
10998 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10999 DAG.getConstant(2, MVT::i64));
11000 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11001 MachinePointerInfo(TrmpAddr, 2),
11004 // Load the 'nest' parameter value into R10.
11005 // R10 is specified in X86CallingConv.td
11006 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11007 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11008 DAG.getConstant(10, MVT::i64));
11009 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11010 Addr, MachinePointerInfo(TrmpAddr, 10),
11013 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11014 DAG.getConstant(12, MVT::i64));
11015 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11016 MachinePointerInfo(TrmpAddr, 12),
11019 // Jump to the nested function.
11020 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11021 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11022 DAG.getConstant(20, MVT::i64));
11023 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11024 Addr, MachinePointerInfo(TrmpAddr, 20),
11027 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11028 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11029 DAG.getConstant(22, MVT::i64));
11030 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11031 MachinePointerInfo(TrmpAddr, 22),
11034 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11036 const Function *Func =
11037 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11038 CallingConv::ID CC = Func->getCallingConv();
11043 llvm_unreachable("Unsupported calling convention");
11044 case CallingConv::C:
11045 case CallingConv::X86_StdCall: {
11046 // Pass 'nest' parameter in ECX.
11047 // Must be kept in sync with X86CallingConv.td
11048 NestReg = X86::ECX;
11050 // Check that ECX wasn't needed by an 'inreg' parameter.
11051 FunctionType *FTy = Func->getFunctionType();
11052 const AttributeSet &Attrs = Func->getAttributes();
11054 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11055 unsigned InRegCount = 0;
11058 for (FunctionType::param_iterator I = FTy->param_begin(),
11059 E = FTy->param_end(); I != E; ++I, ++Idx)
11060 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11061 // FIXME: should only count parameters that are lowered to integers.
11062 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11064 if (InRegCount > 2) {
11065 report_fatal_error("Nest register in use - reduce number of inreg"
11071 case CallingConv::X86_FastCall:
11072 case CallingConv::X86_ThisCall:
11073 case CallingConv::Fast:
11074 // Pass 'nest' parameter in EAX.
11075 // Must be kept in sync with X86CallingConv.td
11076 NestReg = X86::EAX;
11080 SDValue OutChains[4];
11081 SDValue Addr, Disp;
11083 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11084 DAG.getConstant(10, MVT::i32));
11085 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11087 // This is storing the opcode for MOV32ri.
11088 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11089 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11090 OutChains[0] = DAG.getStore(Root, dl,
11091 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11092 Trmp, MachinePointerInfo(TrmpAddr),
11095 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11096 DAG.getConstant(1, MVT::i32));
11097 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11098 MachinePointerInfo(TrmpAddr, 1),
11101 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11102 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11103 DAG.getConstant(5, MVT::i32));
11104 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11105 MachinePointerInfo(TrmpAddr, 5),
11108 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11109 DAG.getConstant(6, MVT::i32));
11110 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11111 MachinePointerInfo(TrmpAddr, 6),
11114 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11118 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11119 SelectionDAG &DAG) const {
11121 The rounding mode is in bits 11:10 of FPSR, and has the following
11123 00 Round to nearest
11128 FLT_ROUNDS, on the other hand, expects the following:
11135 To perform the conversion, we do:
11136 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11139 MachineFunction &MF = DAG.getMachineFunction();
11140 const TargetMachine &TM = MF.getTarget();
11141 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11142 unsigned StackAlignment = TFI.getStackAlignment();
11143 EVT VT = Op.getValueType();
11144 DebugLoc DL = Op.getDebugLoc();
11146 // Save FP Control Word to stack slot
11147 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11148 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11150 MachineMemOperand *MMO =
11151 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11152 MachineMemOperand::MOStore, 2, 2);
11154 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11155 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11156 DAG.getVTList(MVT::Other),
11157 Ops, 2, MVT::i16, MMO);
11159 // Load FP Control Word from stack slot
11160 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11161 MachinePointerInfo(), false, false, false, 0);
11163 // Transform as necessary
11165 DAG.getNode(ISD::SRL, DL, MVT::i16,
11166 DAG.getNode(ISD::AND, DL, MVT::i16,
11167 CWD, DAG.getConstant(0x800, MVT::i16)),
11168 DAG.getConstant(11, MVT::i8));
11170 DAG.getNode(ISD::SRL, DL, MVT::i16,
11171 DAG.getNode(ISD::AND, DL, MVT::i16,
11172 CWD, DAG.getConstant(0x400, MVT::i16)),
11173 DAG.getConstant(9, MVT::i8));
11176 DAG.getNode(ISD::AND, DL, MVT::i16,
11177 DAG.getNode(ISD::ADD, DL, MVT::i16,
11178 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11179 DAG.getConstant(1, MVT::i16)),
11180 DAG.getConstant(3, MVT::i16));
11182 return DAG.getNode((VT.getSizeInBits() < 16 ?
11183 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11186 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11187 EVT VT = Op.getValueType();
11189 unsigned NumBits = VT.getSizeInBits();
11190 DebugLoc dl = Op.getDebugLoc();
11192 Op = Op.getOperand(0);
11193 if (VT == MVT::i8) {
11194 // Zero extend to i32 since there is not an i8 bsr.
11196 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11199 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11200 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11201 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11203 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11206 DAG.getConstant(NumBits+NumBits-1, OpVT),
11207 DAG.getConstant(X86::COND_E, MVT::i8),
11210 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11212 // Finally xor with NumBits-1.
11213 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11216 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11220 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11221 EVT VT = Op.getValueType();
11223 unsigned NumBits = VT.getSizeInBits();
11224 DebugLoc dl = Op.getDebugLoc();
11226 Op = Op.getOperand(0);
11227 if (VT == MVT::i8) {
11228 // Zero extend to i32 since there is not an i8 bsr.
11230 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11233 // Issue a bsr (scan bits in reverse).
11234 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11235 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11237 // And xor with NumBits-1.
11238 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11241 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11245 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11246 EVT VT = Op.getValueType();
11247 unsigned NumBits = VT.getSizeInBits();
11248 DebugLoc dl = Op.getDebugLoc();
11249 Op = Op.getOperand(0);
11251 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11252 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11253 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11255 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11258 DAG.getConstant(NumBits, VT),
11259 DAG.getConstant(X86::COND_E, MVT::i8),
11262 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11265 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11266 // ones, and then concatenate the result back.
11267 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11268 EVT VT = Op.getValueType();
11270 assert(VT.is256BitVector() && VT.isInteger() &&
11271 "Unsupported value type for operation");
11273 unsigned NumElems = VT.getVectorNumElements();
11274 DebugLoc dl = Op.getDebugLoc();
11276 // Extract the LHS vectors
11277 SDValue LHS = Op.getOperand(0);
11278 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11279 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11281 // Extract the RHS vectors
11282 SDValue RHS = Op.getOperand(1);
11283 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11284 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11286 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11287 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11289 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11290 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11291 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11294 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11295 assert(Op.getValueType().is256BitVector() &&
11296 Op.getValueType().isInteger() &&
11297 "Only handle AVX 256-bit vector integer operation");
11298 return Lower256IntArith(Op, DAG);
11301 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11302 assert(Op.getValueType().is256BitVector() &&
11303 Op.getValueType().isInteger() &&
11304 "Only handle AVX 256-bit vector integer operation");
11305 return Lower256IntArith(Op, DAG);
11308 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11309 SelectionDAG &DAG) {
11310 DebugLoc dl = Op.getDebugLoc();
11311 EVT VT = Op.getValueType();
11313 // Decompose 256-bit ops into smaller 128-bit ops.
11314 if (VT.is256BitVector() && !Subtarget->hasInt256())
11315 return Lower256IntArith(Op, DAG);
11317 SDValue A = Op.getOperand(0);
11318 SDValue B = Op.getOperand(1);
11320 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11321 if (VT == MVT::v4i32) {
11322 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11323 "Should not custom lower when pmuldq is available!");
11325 // Extract the odd parts.
11326 const int UnpackMask[] = { 1, -1, 3, -1 };
11327 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11328 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11330 // Multiply the even parts.
11331 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11332 // Now multiply odd parts.
11333 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11335 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11336 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11338 // Merge the two vectors back together with a shuffle. This expands into 2
11340 const int ShufMask[] = { 0, 4, 2, 6 };
11341 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11344 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11345 "Only know how to lower V2I64/V4I64 multiply");
11347 // Ahi = psrlqi(a, 32);
11348 // Bhi = psrlqi(b, 32);
11350 // AloBlo = pmuludq(a, b);
11351 // AloBhi = pmuludq(a, Bhi);
11352 // AhiBlo = pmuludq(Ahi, b);
11354 // AloBhi = psllqi(AloBhi, 32);
11355 // AhiBlo = psllqi(AhiBlo, 32);
11356 // return AloBlo + AloBhi + AhiBlo;
11358 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11360 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11361 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11363 // Bit cast to 32-bit vectors for MULUDQ
11364 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11365 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11366 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11367 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11368 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11370 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11371 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11372 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11374 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11375 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11377 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11378 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11381 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11382 EVT VT = Op.getValueType();
11383 EVT EltTy = VT.getVectorElementType();
11384 unsigned NumElts = VT.getVectorNumElements();
11385 SDValue N0 = Op.getOperand(0);
11386 DebugLoc dl = Op.getDebugLoc();
11388 // Lower sdiv X, pow2-const.
11389 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11393 APInt SplatValue, SplatUndef;
11394 unsigned MinSplatBits;
11396 if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11399 if ((SplatValue != 0) &&
11400 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11401 unsigned lg2 = SplatValue.countTrailingZeros();
11402 // Splat the sign bit.
11403 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11404 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11405 // Add (N0 < 0) ? abs2 - 1 : 0;
11406 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11407 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11408 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11409 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11410 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11412 // If we're dividing by a positive value, we're done. Otherwise, we must
11413 // negate the result.
11414 if (SplatValue.isNonNegative())
11417 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11418 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11419 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11424 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11426 EVT VT = Op.getValueType();
11427 DebugLoc dl = Op.getDebugLoc();
11428 SDValue R = Op.getOperand(0);
11429 SDValue Amt = Op.getOperand(1);
11430 LLVMContext *Context = DAG.getContext();
11432 if (!Subtarget->hasSSE2())
11435 // Optimize shl/srl/sra with constant shift amount.
11436 if (isSplatVector(Amt.getNode())) {
11437 SDValue SclrAmt = Amt->getOperand(0);
11438 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11439 uint64_t ShiftAmt = C->getZExtValue();
11441 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11442 (Subtarget->hasInt256() &&
11443 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11444 if (Op.getOpcode() == ISD::SHL)
11445 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11446 DAG.getConstant(ShiftAmt, MVT::i32));
11447 if (Op.getOpcode() == ISD::SRL)
11448 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11449 DAG.getConstant(ShiftAmt, MVT::i32));
11450 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11451 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11452 DAG.getConstant(ShiftAmt, MVT::i32));
11455 if (VT == MVT::v16i8) {
11456 if (Op.getOpcode() == ISD::SHL) {
11457 // Make a large shift.
11458 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11459 DAG.getConstant(ShiftAmt, MVT::i32));
11460 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11461 // Zero out the rightmost bits.
11462 SmallVector<SDValue, 16> V(16,
11463 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11465 return DAG.getNode(ISD::AND, dl, VT, SHL,
11466 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11468 if (Op.getOpcode() == ISD::SRL) {
11469 // Make a large shift.
11470 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11471 DAG.getConstant(ShiftAmt, MVT::i32));
11472 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11473 // Zero out the leftmost bits.
11474 SmallVector<SDValue, 16> V(16,
11475 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11477 return DAG.getNode(ISD::AND, dl, VT, SRL,
11478 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11480 if (Op.getOpcode() == ISD::SRA) {
11481 if (ShiftAmt == 7) {
11482 // R s>> 7 === R s< 0
11483 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11484 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11487 // R s>> a === ((R u>> a) ^ m) - m
11488 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11489 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11491 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11492 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11493 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11496 llvm_unreachable("Unknown shift opcode.");
11499 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11500 if (Op.getOpcode() == ISD::SHL) {
11501 // Make a large shift.
11502 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11503 DAG.getConstant(ShiftAmt, MVT::i32));
11504 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11505 // Zero out the rightmost bits.
11506 SmallVector<SDValue, 32> V(32,
11507 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11509 return DAG.getNode(ISD::AND, dl, VT, SHL,
11510 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11512 if (Op.getOpcode() == ISD::SRL) {
11513 // Make a large shift.
11514 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11515 DAG.getConstant(ShiftAmt, MVT::i32));
11516 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11517 // Zero out the leftmost bits.
11518 SmallVector<SDValue, 32> V(32,
11519 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11521 return DAG.getNode(ISD::AND, dl, VT, SRL,
11522 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11524 if (Op.getOpcode() == ISD::SRA) {
11525 if (ShiftAmt == 7) {
11526 // R s>> 7 === R s< 0
11527 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11528 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11531 // R s>> a === ((R u>> a) ^ m) - m
11532 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11533 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11535 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11536 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11537 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11540 llvm_unreachable("Unknown shift opcode.");
11545 // Lower SHL with variable shift amount.
11546 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11547 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11548 DAG.getConstant(23, MVT::i32));
11550 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11551 Constant *C = ConstantDataVector::get(*Context, CV);
11552 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11553 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11554 MachinePointerInfo::getConstantPool(),
11555 false, false, false, 16);
11557 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11558 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11559 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11560 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11562 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11563 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11566 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11567 DAG.getConstant(5, MVT::i32));
11568 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11570 // Turn 'a' into a mask suitable for VSELECT
11571 SDValue VSelM = DAG.getConstant(0x80, VT);
11572 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11573 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11575 SDValue CM1 = DAG.getConstant(0x0f, VT);
11576 SDValue CM2 = DAG.getConstant(0x3f, VT);
11578 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11579 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11580 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11581 DAG.getConstant(4, MVT::i32), DAG);
11582 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11583 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11586 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11587 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11588 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11590 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11591 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11592 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11593 DAG.getConstant(2, MVT::i32), DAG);
11594 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11595 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11598 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11599 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11600 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11602 // return VSELECT(r, r+r, a);
11603 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11604 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11608 // Decompose 256-bit shifts into smaller 128-bit shifts.
11609 if (VT.is256BitVector()) {
11610 unsigned NumElems = VT.getVectorNumElements();
11611 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11612 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11614 // Extract the two vectors
11615 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11616 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11618 // Recreate the shift amount vectors
11619 SDValue Amt1, Amt2;
11620 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11621 // Constant shift amount
11622 SmallVector<SDValue, 4> Amt1Csts;
11623 SmallVector<SDValue, 4> Amt2Csts;
11624 for (unsigned i = 0; i != NumElems/2; ++i)
11625 Amt1Csts.push_back(Amt->getOperand(i));
11626 for (unsigned i = NumElems/2; i != NumElems; ++i)
11627 Amt2Csts.push_back(Amt->getOperand(i));
11629 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11630 &Amt1Csts[0], NumElems/2);
11631 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11632 &Amt2Csts[0], NumElems/2);
11634 // Variable shift amount
11635 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11636 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11639 // Issue new vector shifts for the smaller types
11640 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11641 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11643 // Concatenate the result back
11644 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11650 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11651 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11652 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11653 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11654 // has only one use.
11655 SDNode *N = Op.getNode();
11656 SDValue LHS = N->getOperand(0);
11657 SDValue RHS = N->getOperand(1);
11658 unsigned BaseOp = 0;
11660 DebugLoc DL = Op.getDebugLoc();
11661 switch (Op.getOpcode()) {
11662 default: llvm_unreachable("Unknown ovf instruction!");
11664 // A subtract of one will be selected as a INC. Note that INC doesn't
11665 // set CF, so we can't do this for UADDO.
11666 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11668 BaseOp = X86ISD::INC;
11669 Cond = X86::COND_O;
11672 BaseOp = X86ISD::ADD;
11673 Cond = X86::COND_O;
11676 BaseOp = X86ISD::ADD;
11677 Cond = X86::COND_B;
11680 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11681 // set CF, so we can't do this for USUBO.
11682 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11684 BaseOp = X86ISD::DEC;
11685 Cond = X86::COND_O;
11688 BaseOp = X86ISD::SUB;
11689 Cond = X86::COND_O;
11692 BaseOp = X86ISD::SUB;
11693 Cond = X86::COND_B;
11696 BaseOp = X86ISD::SMUL;
11697 Cond = X86::COND_O;
11699 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11700 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11702 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11705 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11706 DAG.getConstant(X86::COND_O, MVT::i32),
11707 SDValue(Sum.getNode(), 2));
11709 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11713 // Also sets EFLAGS.
11714 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11715 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11718 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11719 DAG.getConstant(Cond, MVT::i32),
11720 SDValue(Sum.getNode(), 1));
11722 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11725 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11726 SelectionDAG &DAG) const {
11727 DebugLoc dl = Op.getDebugLoc();
11728 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11729 EVT VT = Op.getValueType();
11731 if (!Subtarget->hasSSE2() || !VT.isVector())
11734 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11735 ExtraVT.getScalarType().getSizeInBits();
11736 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11738 switch (VT.getSimpleVT().SimpleTy) {
11739 default: return SDValue();
11742 if (!Subtarget->hasFp256())
11744 if (!Subtarget->hasInt256()) {
11745 // needs to be split
11746 unsigned NumElems = VT.getVectorNumElements();
11748 // Extract the LHS vectors
11749 SDValue LHS = Op.getOperand(0);
11750 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11751 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11753 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11754 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11756 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11757 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11758 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11760 SDValue Extra = DAG.getValueType(ExtraVT);
11762 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11763 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11765 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11770 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11771 Op.getOperand(0), ShAmt, DAG);
11772 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11777 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11778 SelectionDAG &DAG) {
11779 DebugLoc dl = Op.getDebugLoc();
11781 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11782 // There isn't any reason to disable it if the target processor supports it.
11783 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11784 SDValue Chain = Op.getOperand(0);
11785 SDValue Zero = DAG.getConstant(0, MVT::i32);
11787 DAG.getRegister(X86::ESP, MVT::i32), // Base
11788 DAG.getTargetConstant(1, MVT::i8), // Scale
11789 DAG.getRegister(0, MVT::i32), // Index
11790 DAG.getTargetConstant(0, MVT::i32), // Disp
11791 DAG.getRegister(0, MVT::i32), // Segment.
11796 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11797 array_lengthof(Ops));
11798 return SDValue(Res, 0);
11801 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11803 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11805 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11806 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11807 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11808 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11810 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11811 if (!Op1 && !Op2 && !Op3 && Op4)
11812 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11814 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11815 if (Op1 && !Op2 && !Op3 && !Op4)
11816 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11818 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11820 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11823 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11824 SelectionDAG &DAG) {
11825 DebugLoc dl = Op.getDebugLoc();
11826 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11827 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11828 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11829 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11831 // The only fence that needs an instruction is a sequentially-consistent
11832 // cross-thread fence.
11833 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11834 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11835 // no-sse2). There isn't any reason to disable it if the target processor
11837 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11838 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11840 SDValue Chain = Op.getOperand(0);
11841 SDValue Zero = DAG.getConstant(0, MVT::i32);
11843 DAG.getRegister(X86::ESP, MVT::i32), // Base
11844 DAG.getTargetConstant(1, MVT::i8), // Scale
11845 DAG.getRegister(0, MVT::i32), // Index
11846 DAG.getTargetConstant(0, MVT::i32), // Disp
11847 DAG.getRegister(0, MVT::i32), // Segment.
11852 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11853 array_lengthof(Ops));
11854 return SDValue(Res, 0);
11857 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11858 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11861 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11862 SelectionDAG &DAG) {
11863 EVT T = Op.getValueType();
11864 DebugLoc DL = Op.getDebugLoc();
11867 switch(T.getSimpleVT().SimpleTy) {
11868 default: llvm_unreachable("Invalid value type!");
11869 case MVT::i8: Reg = X86::AL; size = 1; break;
11870 case MVT::i16: Reg = X86::AX; size = 2; break;
11871 case MVT::i32: Reg = X86::EAX; size = 4; break;
11873 assert(Subtarget->is64Bit() && "Node not type legal!");
11874 Reg = X86::RAX; size = 8;
11877 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11878 Op.getOperand(2), SDValue());
11879 SDValue Ops[] = { cpIn.getValue(0),
11882 DAG.getTargetConstant(size, MVT::i8),
11883 cpIn.getValue(1) };
11884 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11885 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11886 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11889 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11893 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11894 SelectionDAG &DAG) {
11895 assert(Subtarget->is64Bit() && "Result not type legalized?");
11896 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11897 SDValue TheChain = Op.getOperand(0);
11898 DebugLoc dl = Op.getDebugLoc();
11899 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11900 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11901 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11903 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11904 DAG.getConstant(32, MVT::i8));
11906 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11909 return DAG.getMergeValues(Ops, 2, dl);
11912 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11913 EVT SrcVT = Op.getOperand(0).getValueType();
11914 EVT DstVT = Op.getValueType();
11915 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11916 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11917 assert((DstVT == MVT::i64 ||
11918 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11919 "Unexpected custom BITCAST");
11920 // i64 <=> MMX conversions are Legal.
11921 if (SrcVT==MVT::i64 && DstVT.isVector())
11923 if (DstVT==MVT::i64 && SrcVT.isVector())
11925 // MMX <=> MMX conversions are Legal.
11926 if (SrcVT.isVector() && DstVT.isVector())
11928 // All other conversions need to be expanded.
11932 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11933 SDNode *Node = Op.getNode();
11934 DebugLoc dl = Node->getDebugLoc();
11935 EVT T = Node->getValueType(0);
11936 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11937 DAG.getConstant(0, T), Node->getOperand(2));
11938 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11939 cast<AtomicSDNode>(Node)->getMemoryVT(),
11940 Node->getOperand(0),
11941 Node->getOperand(1), negOp,
11942 cast<AtomicSDNode>(Node)->getSrcValue(),
11943 cast<AtomicSDNode>(Node)->getAlignment(),
11944 cast<AtomicSDNode>(Node)->getOrdering(),
11945 cast<AtomicSDNode>(Node)->getSynchScope());
11948 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11949 SDNode *Node = Op.getNode();
11950 DebugLoc dl = Node->getDebugLoc();
11951 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11953 // Convert seq_cst store -> xchg
11954 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11955 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11956 // (The only way to get a 16-byte store is cmpxchg16b)
11957 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11958 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11959 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11960 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11961 cast<AtomicSDNode>(Node)->getMemoryVT(),
11962 Node->getOperand(0),
11963 Node->getOperand(1), Node->getOperand(2),
11964 cast<AtomicSDNode>(Node)->getMemOperand(),
11965 cast<AtomicSDNode>(Node)->getOrdering(),
11966 cast<AtomicSDNode>(Node)->getSynchScope());
11967 return Swap.getValue(1);
11969 // Other atomic stores have a simple pattern.
11973 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11974 EVT VT = Op.getNode()->getValueType(0);
11976 // Let legalize expand this if it isn't a legal type yet.
11977 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11980 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11983 bool ExtraOp = false;
11984 switch (Op.getOpcode()) {
11985 default: llvm_unreachable("Invalid code");
11986 case ISD::ADDC: Opc = X86ISD::ADD; break;
11987 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11988 case ISD::SUBC: Opc = X86ISD::SUB; break;
11989 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11993 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11995 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11996 Op.getOperand(1), Op.getOperand(2));
11999 /// LowerOperation - Provide custom lowering hooks for some operations.
12001 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12002 switch (Op.getOpcode()) {
12003 default: llvm_unreachable("Should not custom lower this!");
12004 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12005 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
12006 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12007 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12008 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12009 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12010 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12011 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12012 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12013 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12014 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12015 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12016 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12017 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12018 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12019 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12020 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12021 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12022 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12023 case ISD::SHL_PARTS:
12024 case ISD::SRA_PARTS:
12025 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12026 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12027 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12028 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12029 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12030 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12031 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12032 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12033 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12034 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
12035 case ISD::FABS: return LowerFABS(Op, DAG);
12036 case ISD::FNEG: return LowerFNEG(Op, DAG);
12037 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12038 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12039 case ISD::SETCC: return LowerSETCC(Op, DAG);
12040 case ISD::SELECT: return LowerSELECT(Op, DAG);
12041 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12042 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12043 case ISD::VASTART: return LowerVASTART(Op, DAG);
12044 case ISD::VAARG: return LowerVAARG(Op, DAG);
12045 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12046 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12047 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12048 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12049 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12050 case ISD::FRAME_TO_ARGS_OFFSET:
12051 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12052 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12053 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12054 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12055 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12056 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12057 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12058 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12059 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12060 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12061 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12062 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12065 case ISD::SHL: return LowerShift(Op, DAG);
12071 case ISD::UMULO: return LowerXALUO(Op, DAG);
12072 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12073 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12077 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12078 case ISD::ADD: return LowerADD(Op, DAG);
12079 case ISD::SUB: return LowerSUB(Op, DAG);
12080 case ISD::SDIV: return LowerSDIV(Op, DAG);
12084 static void ReplaceATOMIC_LOAD(SDNode *Node,
12085 SmallVectorImpl<SDValue> &Results,
12086 SelectionDAG &DAG) {
12087 DebugLoc dl = Node->getDebugLoc();
12088 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12090 // Convert wide load -> cmpxchg8b/cmpxchg16b
12091 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12092 // (The only way to get a 16-byte load is cmpxchg16b)
12093 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12094 SDValue Zero = DAG.getConstant(0, VT);
12095 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12096 Node->getOperand(0),
12097 Node->getOperand(1), Zero, Zero,
12098 cast<AtomicSDNode>(Node)->getMemOperand(),
12099 cast<AtomicSDNode>(Node)->getOrdering(),
12100 cast<AtomicSDNode>(Node)->getSynchScope());
12101 Results.push_back(Swap.getValue(0));
12102 Results.push_back(Swap.getValue(1));
12106 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12107 SelectionDAG &DAG, unsigned NewOp) {
12108 DebugLoc dl = Node->getDebugLoc();
12109 assert (Node->getValueType(0) == MVT::i64 &&
12110 "Only know how to expand i64 atomics");
12112 SDValue Chain = Node->getOperand(0);
12113 SDValue In1 = Node->getOperand(1);
12114 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12115 Node->getOperand(2), DAG.getIntPtrConstant(0));
12116 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12117 Node->getOperand(2), DAG.getIntPtrConstant(1));
12118 SDValue Ops[] = { Chain, In1, In2L, In2H };
12119 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12121 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12122 cast<MemSDNode>(Node)->getMemOperand());
12123 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12124 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12125 Results.push_back(Result.getValue(2));
12128 /// ReplaceNodeResults - Replace a node with an illegal result type
12129 /// with a new node built out of custom code.
12130 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12131 SmallVectorImpl<SDValue>&Results,
12132 SelectionDAG &DAG) const {
12133 DebugLoc dl = N->getDebugLoc();
12134 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12135 switch (N->getOpcode()) {
12137 llvm_unreachable("Do not know how to custom type legalize this operation!");
12138 case ISD::SIGN_EXTEND_INREG:
12143 // We don't want to expand or promote these.
12145 case ISD::FP_TO_SINT:
12146 case ISD::FP_TO_UINT: {
12147 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12149 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12152 std::pair<SDValue,SDValue> Vals =
12153 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12154 SDValue FIST = Vals.first, StackSlot = Vals.second;
12155 if (FIST.getNode() != 0) {
12156 EVT VT = N->getValueType(0);
12157 // Return a load from the stack slot.
12158 if (StackSlot.getNode() != 0)
12159 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12160 MachinePointerInfo(),
12161 false, false, false, 0));
12163 Results.push_back(FIST);
12167 case ISD::UINT_TO_FP: {
12168 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12169 N->getValueType(0) != MVT::v2f32)
12171 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12173 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12175 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12176 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12177 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12178 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12179 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12180 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12183 case ISD::FP_ROUND: {
12184 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12186 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12187 Results.push_back(V);
12190 case ISD::READCYCLECOUNTER: {
12191 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12192 SDValue TheChain = N->getOperand(0);
12193 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12194 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12196 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12198 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12199 SDValue Ops[] = { eax, edx };
12200 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12201 Results.push_back(edx.getValue(1));
12204 case ISD::ATOMIC_CMP_SWAP: {
12205 EVT T = N->getValueType(0);
12206 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12207 bool Regs64bit = T == MVT::i128;
12208 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12209 SDValue cpInL, cpInH;
12210 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12211 DAG.getConstant(0, HalfT));
12212 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12213 DAG.getConstant(1, HalfT));
12214 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12215 Regs64bit ? X86::RAX : X86::EAX,
12217 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12218 Regs64bit ? X86::RDX : X86::EDX,
12219 cpInH, cpInL.getValue(1));
12220 SDValue swapInL, swapInH;
12221 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12222 DAG.getConstant(0, HalfT));
12223 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12224 DAG.getConstant(1, HalfT));
12225 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12226 Regs64bit ? X86::RBX : X86::EBX,
12227 swapInL, cpInH.getValue(1));
12228 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12229 Regs64bit ? X86::RCX : X86::ECX,
12230 swapInH, swapInL.getValue(1));
12231 SDValue Ops[] = { swapInH.getValue(0),
12233 swapInH.getValue(1) };
12234 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12235 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12236 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12237 X86ISD::LCMPXCHG8_DAG;
12238 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12240 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12241 Regs64bit ? X86::RAX : X86::EAX,
12242 HalfT, Result.getValue(1));
12243 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12244 Regs64bit ? X86::RDX : X86::EDX,
12245 HalfT, cpOutL.getValue(2));
12246 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12247 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12248 Results.push_back(cpOutH.getValue(1));
12251 case ISD::ATOMIC_LOAD_ADD:
12252 case ISD::ATOMIC_LOAD_AND:
12253 case ISD::ATOMIC_LOAD_NAND:
12254 case ISD::ATOMIC_LOAD_OR:
12255 case ISD::ATOMIC_LOAD_SUB:
12256 case ISD::ATOMIC_LOAD_XOR:
12257 case ISD::ATOMIC_LOAD_MAX:
12258 case ISD::ATOMIC_LOAD_MIN:
12259 case ISD::ATOMIC_LOAD_UMAX:
12260 case ISD::ATOMIC_LOAD_UMIN:
12261 case ISD::ATOMIC_SWAP: {
12263 switch (N->getOpcode()) {
12264 default: llvm_unreachable("Unexpected opcode");
12265 case ISD::ATOMIC_LOAD_ADD:
12266 Opc = X86ISD::ATOMADD64_DAG;
12268 case ISD::ATOMIC_LOAD_AND:
12269 Opc = X86ISD::ATOMAND64_DAG;
12271 case ISD::ATOMIC_LOAD_NAND:
12272 Opc = X86ISD::ATOMNAND64_DAG;
12274 case ISD::ATOMIC_LOAD_OR:
12275 Opc = X86ISD::ATOMOR64_DAG;
12277 case ISD::ATOMIC_LOAD_SUB:
12278 Opc = X86ISD::ATOMSUB64_DAG;
12280 case ISD::ATOMIC_LOAD_XOR:
12281 Opc = X86ISD::ATOMXOR64_DAG;
12283 case ISD::ATOMIC_LOAD_MAX:
12284 Opc = X86ISD::ATOMMAX64_DAG;
12286 case ISD::ATOMIC_LOAD_MIN:
12287 Opc = X86ISD::ATOMMIN64_DAG;
12289 case ISD::ATOMIC_LOAD_UMAX:
12290 Opc = X86ISD::ATOMUMAX64_DAG;
12292 case ISD::ATOMIC_LOAD_UMIN:
12293 Opc = X86ISD::ATOMUMIN64_DAG;
12295 case ISD::ATOMIC_SWAP:
12296 Opc = X86ISD::ATOMSWAP64_DAG;
12299 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12302 case ISD::ATOMIC_LOAD:
12303 ReplaceATOMIC_LOAD(N, Results, DAG);
12307 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12309 default: return NULL;
12310 case X86ISD::BSF: return "X86ISD::BSF";
12311 case X86ISD::BSR: return "X86ISD::BSR";
12312 case X86ISD::SHLD: return "X86ISD::SHLD";
12313 case X86ISD::SHRD: return "X86ISD::SHRD";
12314 case X86ISD::FAND: return "X86ISD::FAND";
12315 case X86ISD::FOR: return "X86ISD::FOR";
12316 case X86ISD::FXOR: return "X86ISD::FXOR";
12317 case X86ISD::FSRL: return "X86ISD::FSRL";
12318 case X86ISD::FILD: return "X86ISD::FILD";
12319 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12320 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12321 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12322 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12323 case X86ISD::FLD: return "X86ISD::FLD";
12324 case X86ISD::FST: return "X86ISD::FST";
12325 case X86ISD::CALL: return "X86ISD::CALL";
12326 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12327 case X86ISD::BT: return "X86ISD::BT";
12328 case X86ISD::CMP: return "X86ISD::CMP";
12329 case X86ISD::COMI: return "X86ISD::COMI";
12330 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12331 case X86ISD::SETCC: return "X86ISD::SETCC";
12332 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12333 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12334 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12335 case X86ISD::CMOV: return "X86ISD::CMOV";
12336 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12337 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12338 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12339 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12340 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12341 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12342 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12343 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12344 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12345 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12346 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12347 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12348 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12349 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12350 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12351 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12352 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12353 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12354 case X86ISD::HADD: return "X86ISD::HADD";
12355 case X86ISD::HSUB: return "X86ISD::HSUB";
12356 case X86ISD::FHADD: return "X86ISD::FHADD";
12357 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12358 case X86ISD::UMAX: return "X86ISD::UMAX";
12359 case X86ISD::UMIN: return "X86ISD::UMIN";
12360 case X86ISD::SMAX: return "X86ISD::SMAX";
12361 case X86ISD::SMIN: return "X86ISD::SMIN";
12362 case X86ISD::FMAX: return "X86ISD::FMAX";
12363 case X86ISD::FMIN: return "X86ISD::FMIN";
12364 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12365 case X86ISD::FMINC: return "X86ISD::FMINC";
12366 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12367 case X86ISD::FRCP: return "X86ISD::FRCP";
12368 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12369 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12370 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12371 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12372 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12373 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12374 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12375 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12376 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12377 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12378 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12379 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12380 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12381 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12382 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12383 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12384 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12385 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12386 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12387 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12388 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12389 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12390 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12391 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12392 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12393 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12394 case X86ISD::VSHL: return "X86ISD::VSHL";
12395 case X86ISD::VSRL: return "X86ISD::VSRL";
12396 case X86ISD::VSRA: return "X86ISD::VSRA";
12397 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12398 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12399 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12400 case X86ISD::CMPP: return "X86ISD::CMPP";
12401 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12402 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12403 case X86ISD::ADD: return "X86ISD::ADD";
12404 case X86ISD::SUB: return "X86ISD::SUB";
12405 case X86ISD::ADC: return "X86ISD::ADC";
12406 case X86ISD::SBB: return "X86ISD::SBB";
12407 case X86ISD::SMUL: return "X86ISD::SMUL";
12408 case X86ISD::UMUL: return "X86ISD::UMUL";
12409 case X86ISD::INC: return "X86ISD::INC";
12410 case X86ISD::DEC: return "X86ISD::DEC";
12411 case X86ISD::OR: return "X86ISD::OR";
12412 case X86ISD::XOR: return "X86ISD::XOR";
12413 case X86ISD::AND: return "X86ISD::AND";
12414 case X86ISD::BLSI: return "X86ISD::BLSI";
12415 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12416 case X86ISD::BLSR: return "X86ISD::BLSR";
12417 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12418 case X86ISD::PTEST: return "X86ISD::PTEST";
12419 case X86ISD::TESTP: return "X86ISD::TESTP";
12420 case X86ISD::PALIGN: return "X86ISD::PALIGN";
12421 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12422 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12423 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12424 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12425 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12426 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12427 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12428 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12429 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12430 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12431 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12432 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12433 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12434 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12435 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12436 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12437 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12438 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12439 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12440 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12441 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12442 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12443 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12444 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12445 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12446 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12447 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12448 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12449 case X86ISD::SAHF: return "X86ISD::SAHF";
12450 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12451 case X86ISD::FMADD: return "X86ISD::FMADD";
12452 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12453 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12454 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12455 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12456 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12457 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12458 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12462 // isLegalAddressingMode - Return true if the addressing mode represented
12463 // by AM is legal for this target, for a load/store of the specified type.
12464 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12466 // X86 supports extremely general addressing modes.
12467 CodeModel::Model M = getTargetMachine().getCodeModel();
12468 Reloc::Model R = getTargetMachine().getRelocationModel();
12470 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12471 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12476 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12478 // If a reference to this global requires an extra load, we can't fold it.
12479 if (isGlobalStubReference(GVFlags))
12482 // If BaseGV requires a register for the PIC base, we cannot also have a
12483 // BaseReg specified.
12484 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12487 // If lower 4G is not available, then we must use rip-relative addressing.
12488 if ((M != CodeModel::Small || R != Reloc::Static) &&
12489 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12493 switch (AM.Scale) {
12499 // These scales always work.
12504 // These scales are formed with basereg+scalereg. Only accept if there is
12509 default: // Other stuff never works.
12516 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12517 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12519 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12520 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12521 return NumBits1 > NumBits2;
12524 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12525 return isInt<32>(Imm);
12528 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12529 // Can also use sub to handle negated immediates.
12530 return isInt<32>(Imm);
12533 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12534 if (!VT1.isInteger() || !VT2.isInteger())
12536 unsigned NumBits1 = VT1.getSizeInBits();
12537 unsigned NumBits2 = VT2.getSizeInBits();
12538 return NumBits1 > NumBits2;
12541 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12542 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12543 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12546 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12547 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12548 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12551 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12552 EVT VT1 = Val.getValueType();
12553 if (isZExtFree(VT1, VT2))
12556 if (Val.getOpcode() != ISD::LOAD)
12559 if (!VT1.isSimple() || !VT1.isInteger() ||
12560 !VT2.isSimple() || !VT2.isInteger())
12563 switch (VT1.getSimpleVT().SimpleTy) {
12568 // X86 has 8, 16, and 32-bit zero-extending loads.
12575 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12576 // i16 instructions are longer (0x66 prefix) and potentially slower.
12577 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12580 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12581 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12582 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12583 /// are assumed to be legal.
12585 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12587 // Very little shuffling can be done for 64-bit vectors right now.
12588 if (VT.getSizeInBits() == 64)
12591 // FIXME: pshufb, blends, shifts.
12592 return (VT.getVectorNumElements() == 2 ||
12593 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12594 isMOVLMask(M, VT) ||
12595 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12596 isPSHUFDMask(M, VT) ||
12597 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12598 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12599 isPALIGNRMask(M, VT, Subtarget) ||
12600 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12601 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12602 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12603 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12607 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12609 unsigned NumElts = VT.getVectorNumElements();
12610 // FIXME: This collection of masks seems suspect.
12613 if (NumElts == 4 && VT.is128BitVector()) {
12614 return (isMOVLMask(Mask, VT) ||
12615 isCommutedMOVLMask(Mask, VT, true) ||
12616 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12617 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12622 //===----------------------------------------------------------------------===//
12623 // X86 Scheduler Hooks
12624 //===----------------------------------------------------------------------===//
12626 /// Utility function to emit xbegin specifying the start of an RTM region.
12627 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12628 const TargetInstrInfo *TII) {
12629 DebugLoc DL = MI->getDebugLoc();
12631 const BasicBlock *BB = MBB->getBasicBlock();
12632 MachineFunction::iterator I = MBB;
12635 // For the v = xbegin(), we generate
12646 MachineBasicBlock *thisMBB = MBB;
12647 MachineFunction *MF = MBB->getParent();
12648 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12649 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12650 MF->insert(I, mainMBB);
12651 MF->insert(I, sinkMBB);
12653 // Transfer the remainder of BB and its successor edges to sinkMBB.
12654 sinkMBB->splice(sinkMBB->begin(), MBB,
12655 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12656 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12660 // # fallthrough to mainMBB
12661 // # abortion to sinkMBB
12662 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12663 thisMBB->addSuccessor(mainMBB);
12664 thisMBB->addSuccessor(sinkMBB);
12668 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12669 mainMBB->addSuccessor(sinkMBB);
12672 // EAX is live into the sinkMBB
12673 sinkMBB->addLiveIn(X86::EAX);
12674 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12675 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12678 MI->eraseFromParent();
12682 // Get CMPXCHG opcode for the specified data type.
12683 static unsigned getCmpXChgOpcode(EVT VT) {
12684 switch (VT.getSimpleVT().SimpleTy) {
12685 case MVT::i8: return X86::LCMPXCHG8;
12686 case MVT::i16: return X86::LCMPXCHG16;
12687 case MVT::i32: return X86::LCMPXCHG32;
12688 case MVT::i64: return X86::LCMPXCHG64;
12692 llvm_unreachable("Invalid operand size!");
12695 // Get LOAD opcode for the specified data type.
12696 static unsigned getLoadOpcode(EVT VT) {
12697 switch (VT.getSimpleVT().SimpleTy) {
12698 case MVT::i8: return X86::MOV8rm;
12699 case MVT::i16: return X86::MOV16rm;
12700 case MVT::i32: return X86::MOV32rm;
12701 case MVT::i64: return X86::MOV64rm;
12705 llvm_unreachable("Invalid operand size!");
12708 // Get opcode of the non-atomic one from the specified atomic instruction.
12709 static unsigned getNonAtomicOpcode(unsigned Opc) {
12711 case X86::ATOMAND8: return X86::AND8rr;
12712 case X86::ATOMAND16: return X86::AND16rr;
12713 case X86::ATOMAND32: return X86::AND32rr;
12714 case X86::ATOMAND64: return X86::AND64rr;
12715 case X86::ATOMOR8: return X86::OR8rr;
12716 case X86::ATOMOR16: return X86::OR16rr;
12717 case X86::ATOMOR32: return X86::OR32rr;
12718 case X86::ATOMOR64: return X86::OR64rr;
12719 case X86::ATOMXOR8: return X86::XOR8rr;
12720 case X86::ATOMXOR16: return X86::XOR16rr;
12721 case X86::ATOMXOR32: return X86::XOR32rr;
12722 case X86::ATOMXOR64: return X86::XOR64rr;
12724 llvm_unreachable("Unhandled atomic-load-op opcode!");
12727 // Get opcode of the non-atomic one from the specified atomic instruction with
12729 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12730 unsigned &ExtraOpc) {
12732 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12733 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12734 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12735 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12736 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12737 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12738 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12739 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12740 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12741 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12742 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12743 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12744 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12745 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12746 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12747 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12748 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12749 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12750 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12751 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12753 llvm_unreachable("Unhandled atomic-load-op opcode!");
12756 // Get opcode of the non-atomic one from the specified atomic instruction for
12757 // 64-bit data type on 32-bit target.
12758 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12760 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12761 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12762 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12763 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12764 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12765 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12766 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12767 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12768 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12769 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12771 llvm_unreachable("Unhandled atomic-load-op opcode!");
12774 // Get opcode of the non-atomic one from the specified atomic instruction for
12775 // 64-bit data type on 32-bit target with extra opcode.
12776 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12778 unsigned &ExtraOpc) {
12780 case X86::ATOMNAND6432:
12781 ExtraOpc = X86::NOT32r;
12782 HiOpc = X86::AND32rr;
12783 return X86::AND32rr;
12785 llvm_unreachable("Unhandled atomic-load-op opcode!");
12788 // Get pseudo CMOV opcode from the specified data type.
12789 static unsigned getPseudoCMOVOpc(EVT VT) {
12790 switch (VT.getSimpleVT().SimpleTy) {
12791 case MVT::i8: return X86::CMOV_GR8;
12792 case MVT::i16: return X86::CMOV_GR16;
12793 case MVT::i32: return X86::CMOV_GR32;
12797 llvm_unreachable("Unknown CMOV opcode!");
12800 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12801 // They will be translated into a spin-loop or compare-exchange loop from
12804 // dst = atomic-fetch-op MI.addr, MI.val
12810 // EAX = LOAD MI.addr
12812 // t1 = OP MI.val, EAX
12813 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12818 MachineBasicBlock *
12819 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12820 MachineBasicBlock *MBB) const {
12821 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12822 DebugLoc DL = MI->getDebugLoc();
12824 MachineFunction *MF = MBB->getParent();
12825 MachineRegisterInfo &MRI = MF->getRegInfo();
12827 const BasicBlock *BB = MBB->getBasicBlock();
12828 MachineFunction::iterator I = MBB;
12831 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12832 "Unexpected number of operands");
12834 assert(MI->hasOneMemOperand() &&
12835 "Expected atomic-load-op to have one memoperand");
12837 // Memory Reference
12838 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12839 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12841 unsigned DstReg, SrcReg;
12842 unsigned MemOpndSlot;
12844 unsigned CurOp = 0;
12846 DstReg = MI->getOperand(CurOp++).getReg();
12847 MemOpndSlot = CurOp;
12848 CurOp += X86::AddrNumOperands;
12849 SrcReg = MI->getOperand(CurOp++).getReg();
12851 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12852 MVT::SimpleValueType VT = *RC->vt_begin();
12853 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12855 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12856 unsigned LOADOpc = getLoadOpcode(VT);
12858 // For the atomic load-arith operator, we generate
12861 // EAX = LOAD [MI.addr]
12863 // t1 = OP MI.val, EAX
12864 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12868 MachineBasicBlock *thisMBB = MBB;
12869 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12870 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12871 MF->insert(I, mainMBB);
12872 MF->insert(I, sinkMBB);
12874 MachineInstrBuilder MIB;
12876 // Transfer the remainder of BB and its successor edges to sinkMBB.
12877 sinkMBB->splice(sinkMBB->begin(), MBB,
12878 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12879 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12882 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12883 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12884 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12885 MIB.setMemRefs(MMOBegin, MMOEnd);
12887 thisMBB->addSuccessor(mainMBB);
12890 MachineBasicBlock *origMainMBB = mainMBB;
12891 mainMBB->addLiveIn(AccPhyReg);
12893 // Copy AccPhyReg as it is used more than once.
12894 unsigned AccReg = MRI.createVirtualRegister(RC);
12895 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12896 .addReg(AccPhyReg);
12898 unsigned t1 = MRI.createVirtualRegister(RC);
12899 unsigned Opc = MI->getOpcode();
12902 llvm_unreachable("Unhandled atomic-load-op opcode!");
12903 case X86::ATOMAND8:
12904 case X86::ATOMAND16:
12905 case X86::ATOMAND32:
12906 case X86::ATOMAND64:
12908 case X86::ATOMOR16:
12909 case X86::ATOMOR32:
12910 case X86::ATOMOR64:
12911 case X86::ATOMXOR8:
12912 case X86::ATOMXOR16:
12913 case X86::ATOMXOR32:
12914 case X86::ATOMXOR64: {
12915 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12916 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12920 case X86::ATOMNAND8:
12921 case X86::ATOMNAND16:
12922 case X86::ATOMNAND32:
12923 case X86::ATOMNAND64: {
12924 unsigned t2 = MRI.createVirtualRegister(RC);
12926 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12927 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12929 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12932 case X86::ATOMMAX8:
12933 case X86::ATOMMAX16:
12934 case X86::ATOMMAX32:
12935 case X86::ATOMMAX64:
12936 case X86::ATOMMIN8:
12937 case X86::ATOMMIN16:
12938 case X86::ATOMMIN32:
12939 case X86::ATOMMIN64:
12940 case X86::ATOMUMAX8:
12941 case X86::ATOMUMAX16:
12942 case X86::ATOMUMAX32:
12943 case X86::ATOMUMAX64:
12944 case X86::ATOMUMIN8:
12945 case X86::ATOMUMIN16:
12946 case X86::ATOMUMIN32:
12947 case X86::ATOMUMIN64: {
12949 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12951 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12955 if (Subtarget->hasCMov()) {
12956 if (VT != MVT::i8) {
12958 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12962 // Promote i8 to i32 to use CMOV32
12963 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12964 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12965 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12966 unsigned t2 = MRI.createVirtualRegister(RC32);
12968 unsigned Undef = MRI.createVirtualRegister(RC32);
12969 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12971 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12974 .addImm(X86::sub_8bit);
12975 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12978 .addImm(X86::sub_8bit);
12980 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12984 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12985 .addReg(t2, 0, X86::sub_8bit);
12988 // Use pseudo select and lower them.
12989 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12990 "Invalid atomic-load-op transformation!");
12991 unsigned SelOpc = getPseudoCMOVOpc(VT);
12992 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12993 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12994 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12995 .addReg(SrcReg).addReg(AccReg)
12997 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13003 // Copy AccPhyReg back from virtual register.
13004 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13007 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13008 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13009 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13011 MIB.setMemRefs(MMOBegin, MMOEnd);
13013 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13015 mainMBB->addSuccessor(origMainMBB);
13016 mainMBB->addSuccessor(sinkMBB);
13019 sinkMBB->addLiveIn(AccPhyReg);
13021 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13022 TII->get(TargetOpcode::COPY), DstReg)
13023 .addReg(AccPhyReg);
13025 MI->eraseFromParent();
13029 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13030 // instructions. They will be translated into a spin-loop or compare-exchange
13034 // dst = atomic-fetch-op MI.addr, MI.val
13040 // EAX = LOAD [MI.addr + 0]
13041 // EDX = LOAD [MI.addr + 4]
13043 // EBX = OP MI.val.lo, EAX
13044 // ECX = OP MI.val.hi, EDX
13045 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13050 MachineBasicBlock *
13051 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13052 MachineBasicBlock *MBB) const {
13053 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13054 DebugLoc DL = MI->getDebugLoc();
13056 MachineFunction *MF = MBB->getParent();
13057 MachineRegisterInfo &MRI = MF->getRegInfo();
13059 const BasicBlock *BB = MBB->getBasicBlock();
13060 MachineFunction::iterator I = MBB;
13063 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13064 "Unexpected number of operands");
13066 assert(MI->hasOneMemOperand() &&
13067 "Expected atomic-load-op32 to have one memoperand");
13069 // Memory Reference
13070 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13071 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13073 unsigned DstLoReg, DstHiReg;
13074 unsigned SrcLoReg, SrcHiReg;
13075 unsigned MemOpndSlot;
13077 unsigned CurOp = 0;
13079 DstLoReg = MI->getOperand(CurOp++).getReg();
13080 DstHiReg = MI->getOperand(CurOp++).getReg();
13081 MemOpndSlot = CurOp;
13082 CurOp += X86::AddrNumOperands;
13083 SrcLoReg = MI->getOperand(CurOp++).getReg();
13084 SrcHiReg = MI->getOperand(CurOp++).getReg();
13086 const TargetRegisterClass *RC = &X86::GR32RegClass;
13087 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13089 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13090 unsigned LOADOpc = X86::MOV32rm;
13092 // For the atomic load-arith operator, we generate
13095 // EAX = LOAD [MI.addr + 0]
13096 // EDX = LOAD [MI.addr + 4]
13098 // EBX = OP MI.vallo, EAX
13099 // ECX = OP MI.valhi, EDX
13100 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13104 MachineBasicBlock *thisMBB = MBB;
13105 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13106 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13107 MF->insert(I, mainMBB);
13108 MF->insert(I, sinkMBB);
13110 MachineInstrBuilder MIB;
13112 // Transfer the remainder of BB and its successor edges to sinkMBB.
13113 sinkMBB->splice(sinkMBB->begin(), MBB,
13114 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13115 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13119 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13120 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13121 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13122 MIB.setMemRefs(MMOBegin, MMOEnd);
13124 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13125 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13126 if (i == X86::AddrDisp)
13127 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13129 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13131 MIB.setMemRefs(MMOBegin, MMOEnd);
13133 thisMBB->addSuccessor(mainMBB);
13136 MachineBasicBlock *origMainMBB = mainMBB;
13137 mainMBB->addLiveIn(X86::EAX);
13138 mainMBB->addLiveIn(X86::EDX);
13140 // Copy EDX:EAX as they are used more than once.
13141 unsigned LoReg = MRI.createVirtualRegister(RC);
13142 unsigned HiReg = MRI.createVirtualRegister(RC);
13143 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13144 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13146 unsigned t1L = MRI.createVirtualRegister(RC);
13147 unsigned t1H = MRI.createVirtualRegister(RC);
13149 unsigned Opc = MI->getOpcode();
13152 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13153 case X86::ATOMAND6432:
13154 case X86::ATOMOR6432:
13155 case X86::ATOMXOR6432:
13156 case X86::ATOMADD6432:
13157 case X86::ATOMSUB6432: {
13159 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13160 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13161 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13164 case X86::ATOMNAND6432: {
13165 unsigned HiOpc, NOTOpc;
13166 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13167 unsigned t2L = MRI.createVirtualRegister(RC);
13168 unsigned t2H = MRI.createVirtualRegister(RC);
13169 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13170 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13171 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13172 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13175 case X86::ATOMMAX6432:
13176 case X86::ATOMMIN6432:
13177 case X86::ATOMUMAX6432:
13178 case X86::ATOMUMIN6432: {
13180 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13181 unsigned cL = MRI.createVirtualRegister(RC8);
13182 unsigned cH = MRI.createVirtualRegister(RC8);
13183 unsigned cL32 = MRI.createVirtualRegister(RC);
13184 unsigned cH32 = MRI.createVirtualRegister(RC);
13185 unsigned cc = MRI.createVirtualRegister(RC);
13186 // cl := cmp src_lo, lo
13187 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13188 .addReg(SrcLoReg).addReg(LoReg);
13189 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13190 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13191 // ch := cmp src_hi, hi
13192 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13193 .addReg(SrcHiReg).addReg(HiReg);
13194 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13195 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13196 // cc := if (src_hi == hi) ? cl : ch;
13197 if (Subtarget->hasCMov()) {
13198 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13199 .addReg(cH32).addReg(cL32);
13201 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13202 .addReg(cH32).addReg(cL32)
13203 .addImm(X86::COND_E);
13204 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13206 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13207 if (Subtarget->hasCMov()) {
13208 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13209 .addReg(SrcLoReg).addReg(LoReg);
13210 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13211 .addReg(SrcHiReg).addReg(HiReg);
13213 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13214 .addReg(SrcLoReg).addReg(LoReg)
13215 .addImm(X86::COND_NE);
13216 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13217 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13218 .addReg(SrcHiReg).addReg(HiReg)
13219 .addImm(X86::COND_NE);
13220 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13224 case X86::ATOMSWAP6432: {
13226 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13227 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13228 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13233 // Copy EDX:EAX back from HiReg:LoReg
13234 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13235 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13236 // Copy ECX:EBX from t1H:t1L
13237 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13238 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13240 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13241 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13242 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13243 MIB.setMemRefs(MMOBegin, MMOEnd);
13245 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13247 mainMBB->addSuccessor(origMainMBB);
13248 mainMBB->addSuccessor(sinkMBB);
13251 sinkMBB->addLiveIn(X86::EAX);
13252 sinkMBB->addLiveIn(X86::EDX);
13254 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13255 TII->get(TargetOpcode::COPY), DstLoReg)
13257 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13258 TII->get(TargetOpcode::COPY), DstHiReg)
13261 MI->eraseFromParent();
13265 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13266 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13267 // in the .td file.
13268 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13269 const TargetInstrInfo *TII) {
13271 switch (MI->getOpcode()) {
13272 default: llvm_unreachable("illegal opcode!");
13273 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13274 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13275 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13276 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13277 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13278 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13279 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13280 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13283 DebugLoc dl = MI->getDebugLoc();
13284 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13286 unsigned NumArgs = MI->getNumOperands();
13287 for (unsigned i = 1; i < NumArgs; ++i) {
13288 MachineOperand &Op = MI->getOperand(i);
13289 if (!(Op.isReg() && Op.isImplicit()))
13290 MIB.addOperand(Op);
13292 if (MI->hasOneMemOperand())
13293 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13295 BuildMI(*BB, MI, dl,
13296 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13297 .addReg(X86::XMM0);
13299 MI->eraseFromParent();
13303 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13304 // defs in an instruction pattern
13305 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13306 const TargetInstrInfo *TII) {
13308 switch (MI->getOpcode()) {
13309 default: llvm_unreachable("illegal opcode!");
13310 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13311 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13312 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13313 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13314 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13315 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13316 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13317 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13320 DebugLoc dl = MI->getDebugLoc();
13321 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13323 unsigned NumArgs = MI->getNumOperands(); // remove the results
13324 for (unsigned i = 1; i < NumArgs; ++i) {
13325 MachineOperand &Op = MI->getOperand(i);
13326 if (!(Op.isReg() && Op.isImplicit()))
13327 MIB.addOperand(Op);
13329 if (MI->hasOneMemOperand())
13330 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13332 BuildMI(*BB, MI, dl,
13333 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13336 MI->eraseFromParent();
13340 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13341 const TargetInstrInfo *TII,
13342 const X86Subtarget* Subtarget) {
13343 DebugLoc dl = MI->getDebugLoc();
13345 // Address into RAX/EAX, other two args into ECX, EDX.
13346 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13347 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13348 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13349 for (int i = 0; i < X86::AddrNumOperands; ++i)
13350 MIB.addOperand(MI->getOperand(i));
13352 unsigned ValOps = X86::AddrNumOperands;
13353 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13354 .addReg(MI->getOperand(ValOps).getReg());
13355 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13356 .addReg(MI->getOperand(ValOps+1).getReg());
13358 // The instruction doesn't actually take any operands though.
13359 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13361 MI->eraseFromParent(); // The pseudo is gone now.
13365 MachineBasicBlock *
13366 X86TargetLowering::EmitVAARG64WithCustomInserter(
13368 MachineBasicBlock *MBB) const {
13369 // Emit va_arg instruction on X86-64.
13371 // Operands to this pseudo-instruction:
13372 // 0 ) Output : destination address (reg)
13373 // 1-5) Input : va_list address (addr, i64mem)
13374 // 6 ) ArgSize : Size (in bytes) of vararg type
13375 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13376 // 8 ) Align : Alignment of type
13377 // 9 ) EFLAGS (implicit-def)
13379 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13380 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13382 unsigned DestReg = MI->getOperand(0).getReg();
13383 MachineOperand &Base = MI->getOperand(1);
13384 MachineOperand &Scale = MI->getOperand(2);
13385 MachineOperand &Index = MI->getOperand(3);
13386 MachineOperand &Disp = MI->getOperand(4);
13387 MachineOperand &Segment = MI->getOperand(5);
13388 unsigned ArgSize = MI->getOperand(6).getImm();
13389 unsigned ArgMode = MI->getOperand(7).getImm();
13390 unsigned Align = MI->getOperand(8).getImm();
13392 // Memory Reference
13393 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13394 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13395 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13397 // Machine Information
13398 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13399 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13400 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13401 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13402 DebugLoc DL = MI->getDebugLoc();
13404 // struct va_list {
13407 // i64 overflow_area (address)
13408 // i64 reg_save_area (address)
13410 // sizeof(va_list) = 24
13411 // alignment(va_list) = 8
13413 unsigned TotalNumIntRegs = 6;
13414 unsigned TotalNumXMMRegs = 8;
13415 bool UseGPOffset = (ArgMode == 1);
13416 bool UseFPOffset = (ArgMode == 2);
13417 unsigned MaxOffset = TotalNumIntRegs * 8 +
13418 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13420 /* Align ArgSize to a multiple of 8 */
13421 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13422 bool NeedsAlign = (Align > 8);
13424 MachineBasicBlock *thisMBB = MBB;
13425 MachineBasicBlock *overflowMBB;
13426 MachineBasicBlock *offsetMBB;
13427 MachineBasicBlock *endMBB;
13429 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13430 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13431 unsigned OffsetReg = 0;
13433 if (!UseGPOffset && !UseFPOffset) {
13434 // If we only pull from the overflow region, we don't create a branch.
13435 // We don't need to alter control flow.
13436 OffsetDestReg = 0; // unused
13437 OverflowDestReg = DestReg;
13440 overflowMBB = thisMBB;
13443 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13444 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13445 // If not, pull from overflow_area. (branch to overflowMBB)
13450 // offsetMBB overflowMBB
13455 // Registers for the PHI in endMBB
13456 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13457 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13459 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13460 MachineFunction *MF = MBB->getParent();
13461 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13462 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13463 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13465 MachineFunction::iterator MBBIter = MBB;
13468 // Insert the new basic blocks
13469 MF->insert(MBBIter, offsetMBB);
13470 MF->insert(MBBIter, overflowMBB);
13471 MF->insert(MBBIter, endMBB);
13473 // Transfer the remainder of MBB and its successor edges to endMBB.
13474 endMBB->splice(endMBB->begin(), thisMBB,
13475 llvm::next(MachineBasicBlock::iterator(MI)),
13477 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13479 // Make offsetMBB and overflowMBB successors of thisMBB
13480 thisMBB->addSuccessor(offsetMBB);
13481 thisMBB->addSuccessor(overflowMBB);
13483 // endMBB is a successor of both offsetMBB and overflowMBB
13484 offsetMBB->addSuccessor(endMBB);
13485 overflowMBB->addSuccessor(endMBB);
13487 // Load the offset value into a register
13488 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13489 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13493 .addDisp(Disp, UseFPOffset ? 4 : 0)
13494 .addOperand(Segment)
13495 .setMemRefs(MMOBegin, MMOEnd);
13497 // Check if there is enough room left to pull this argument.
13498 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13500 .addImm(MaxOffset + 8 - ArgSizeA8);
13502 // Branch to "overflowMBB" if offset >= max
13503 // Fall through to "offsetMBB" otherwise
13504 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13505 .addMBB(overflowMBB);
13508 // In offsetMBB, emit code to use the reg_save_area.
13510 assert(OffsetReg != 0);
13512 // Read the reg_save_area address.
13513 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13514 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13519 .addOperand(Segment)
13520 .setMemRefs(MMOBegin, MMOEnd);
13522 // Zero-extend the offset
13523 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13524 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13527 .addImm(X86::sub_32bit);
13529 // Add the offset to the reg_save_area to get the final address.
13530 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13531 .addReg(OffsetReg64)
13532 .addReg(RegSaveReg);
13534 // Compute the offset for the next argument
13535 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13536 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13538 .addImm(UseFPOffset ? 16 : 8);
13540 // Store it back into the va_list.
13541 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13545 .addDisp(Disp, UseFPOffset ? 4 : 0)
13546 .addOperand(Segment)
13547 .addReg(NextOffsetReg)
13548 .setMemRefs(MMOBegin, MMOEnd);
13551 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13556 // Emit code to use overflow area
13559 // Load the overflow_area address into a register.
13560 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13561 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13566 .addOperand(Segment)
13567 .setMemRefs(MMOBegin, MMOEnd);
13569 // If we need to align it, do so. Otherwise, just copy the address
13570 // to OverflowDestReg.
13572 // Align the overflow address
13573 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13574 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13576 // aligned_addr = (addr + (align-1)) & ~(align-1)
13577 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13578 .addReg(OverflowAddrReg)
13581 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13583 .addImm(~(uint64_t)(Align-1));
13585 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13586 .addReg(OverflowAddrReg);
13589 // Compute the next overflow address after this argument.
13590 // (the overflow address should be kept 8-byte aligned)
13591 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13592 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13593 .addReg(OverflowDestReg)
13594 .addImm(ArgSizeA8);
13596 // Store the new overflow address.
13597 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13602 .addOperand(Segment)
13603 .addReg(NextAddrReg)
13604 .setMemRefs(MMOBegin, MMOEnd);
13606 // If we branched, emit the PHI to the front of endMBB.
13608 BuildMI(*endMBB, endMBB->begin(), DL,
13609 TII->get(X86::PHI), DestReg)
13610 .addReg(OffsetDestReg).addMBB(offsetMBB)
13611 .addReg(OverflowDestReg).addMBB(overflowMBB);
13614 // Erase the pseudo instruction
13615 MI->eraseFromParent();
13620 MachineBasicBlock *
13621 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13623 MachineBasicBlock *MBB) const {
13624 // Emit code to save XMM registers to the stack. The ABI says that the
13625 // number of registers to save is given in %al, so it's theoretically
13626 // possible to do an indirect jump trick to avoid saving all of them,
13627 // however this code takes a simpler approach and just executes all
13628 // of the stores if %al is non-zero. It's less code, and it's probably
13629 // easier on the hardware branch predictor, and stores aren't all that
13630 // expensive anyway.
13632 // Create the new basic blocks. One block contains all the XMM stores,
13633 // and one block is the final destination regardless of whether any
13634 // stores were performed.
13635 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13636 MachineFunction *F = MBB->getParent();
13637 MachineFunction::iterator MBBIter = MBB;
13639 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13640 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13641 F->insert(MBBIter, XMMSaveMBB);
13642 F->insert(MBBIter, EndMBB);
13644 // Transfer the remainder of MBB and its successor edges to EndMBB.
13645 EndMBB->splice(EndMBB->begin(), MBB,
13646 llvm::next(MachineBasicBlock::iterator(MI)),
13648 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13650 // The original block will now fall through to the XMM save block.
13651 MBB->addSuccessor(XMMSaveMBB);
13652 // The XMMSaveMBB will fall through to the end block.
13653 XMMSaveMBB->addSuccessor(EndMBB);
13655 // Now add the instructions.
13656 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13657 DebugLoc DL = MI->getDebugLoc();
13659 unsigned CountReg = MI->getOperand(0).getReg();
13660 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13661 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13663 if (!Subtarget->isTargetWin64()) {
13664 // If %al is 0, branch around the XMM save block.
13665 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13666 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13667 MBB->addSuccessor(EndMBB);
13670 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13671 // In the XMM save block, save all the XMM argument registers.
13672 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13673 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13674 MachineMemOperand *MMO =
13675 F->getMachineMemOperand(
13676 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13677 MachineMemOperand::MOStore,
13678 /*Size=*/16, /*Align=*/16);
13679 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13680 .addFrameIndex(RegSaveFrameIndex)
13681 .addImm(/*Scale=*/1)
13682 .addReg(/*IndexReg=*/0)
13683 .addImm(/*Disp=*/Offset)
13684 .addReg(/*Segment=*/0)
13685 .addReg(MI->getOperand(i).getReg())
13686 .addMemOperand(MMO);
13689 MI->eraseFromParent(); // The pseudo instruction is gone now.
13694 // The EFLAGS operand of SelectItr might be missing a kill marker
13695 // because there were multiple uses of EFLAGS, and ISel didn't know
13696 // which to mark. Figure out whether SelectItr should have had a
13697 // kill marker, and set it if it should. Returns the correct kill
13699 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13700 MachineBasicBlock* BB,
13701 const TargetRegisterInfo* TRI) {
13702 // Scan forward through BB for a use/def of EFLAGS.
13703 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13704 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13705 const MachineInstr& mi = *miI;
13706 if (mi.readsRegister(X86::EFLAGS))
13708 if (mi.definesRegister(X86::EFLAGS))
13709 break; // Should have kill-flag - update below.
13712 // If we hit the end of the block, check whether EFLAGS is live into a
13714 if (miI == BB->end()) {
13715 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13716 sEnd = BB->succ_end();
13717 sItr != sEnd; ++sItr) {
13718 MachineBasicBlock* succ = *sItr;
13719 if (succ->isLiveIn(X86::EFLAGS))
13724 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13725 // out. SelectMI should have a kill flag on EFLAGS.
13726 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13730 MachineBasicBlock *
13731 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13732 MachineBasicBlock *BB) const {
13733 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13734 DebugLoc DL = MI->getDebugLoc();
13736 // To "insert" a SELECT_CC instruction, we actually have to insert the
13737 // diamond control-flow pattern. The incoming instruction knows the
13738 // destination vreg to set, the condition code register to branch on, the
13739 // true/false values to select between, and a branch opcode to use.
13740 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13741 MachineFunction::iterator It = BB;
13747 // cmpTY ccX, r1, r2
13749 // fallthrough --> copy0MBB
13750 MachineBasicBlock *thisMBB = BB;
13751 MachineFunction *F = BB->getParent();
13752 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13753 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13754 F->insert(It, copy0MBB);
13755 F->insert(It, sinkMBB);
13757 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13758 // live into the sink and copy blocks.
13759 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13760 if (!MI->killsRegister(X86::EFLAGS) &&
13761 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13762 copy0MBB->addLiveIn(X86::EFLAGS);
13763 sinkMBB->addLiveIn(X86::EFLAGS);
13766 // Transfer the remainder of BB and its successor edges to sinkMBB.
13767 sinkMBB->splice(sinkMBB->begin(), BB,
13768 llvm::next(MachineBasicBlock::iterator(MI)),
13770 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13772 // Add the true and fallthrough blocks as its successors.
13773 BB->addSuccessor(copy0MBB);
13774 BB->addSuccessor(sinkMBB);
13776 // Create the conditional branch instruction.
13778 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13779 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13782 // %FalseValue = ...
13783 // # fallthrough to sinkMBB
13784 copy0MBB->addSuccessor(sinkMBB);
13787 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13789 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13790 TII->get(X86::PHI), MI->getOperand(0).getReg())
13791 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13792 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13794 MI->eraseFromParent(); // The pseudo instruction is gone now.
13798 MachineBasicBlock *
13799 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13800 bool Is64Bit) const {
13801 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13802 DebugLoc DL = MI->getDebugLoc();
13803 MachineFunction *MF = BB->getParent();
13804 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13806 assert(getTargetMachine().Options.EnableSegmentedStacks);
13808 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13809 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13812 // ... [Till the alloca]
13813 // If stacklet is not large enough, jump to mallocMBB
13816 // Allocate by subtracting from RSP
13817 // Jump to continueMBB
13820 // Allocate by call to runtime
13824 // [rest of original BB]
13827 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13828 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13829 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13831 MachineRegisterInfo &MRI = MF->getRegInfo();
13832 const TargetRegisterClass *AddrRegClass =
13833 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13835 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13836 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13837 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13838 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13839 sizeVReg = MI->getOperand(1).getReg(),
13840 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13842 MachineFunction::iterator MBBIter = BB;
13845 MF->insert(MBBIter, bumpMBB);
13846 MF->insert(MBBIter, mallocMBB);
13847 MF->insert(MBBIter, continueMBB);
13849 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13850 (MachineBasicBlock::iterator(MI)), BB->end());
13851 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13853 // Add code to the main basic block to check if the stack limit has been hit,
13854 // and if so, jump to mallocMBB otherwise to bumpMBB.
13855 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13856 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13857 .addReg(tmpSPVReg).addReg(sizeVReg);
13858 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13859 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13860 .addReg(SPLimitVReg);
13861 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13863 // bumpMBB simply decreases the stack pointer, since we know the current
13864 // stacklet has enough space.
13865 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13866 .addReg(SPLimitVReg);
13867 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13868 .addReg(SPLimitVReg);
13869 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13871 // Calls into a routine in libgcc to allocate more space from the heap.
13872 const uint32_t *RegMask =
13873 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13875 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13877 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13878 .addExternalSymbol("__morestack_allocate_stack_space")
13879 .addRegMask(RegMask)
13880 .addReg(X86::RDI, RegState::Implicit)
13881 .addReg(X86::RAX, RegState::ImplicitDefine);
13883 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13885 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13886 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13887 .addExternalSymbol("__morestack_allocate_stack_space")
13888 .addRegMask(RegMask)
13889 .addReg(X86::EAX, RegState::ImplicitDefine);
13893 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13896 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13897 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13898 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13900 // Set up the CFG correctly.
13901 BB->addSuccessor(bumpMBB);
13902 BB->addSuccessor(mallocMBB);
13903 mallocMBB->addSuccessor(continueMBB);
13904 bumpMBB->addSuccessor(continueMBB);
13906 // Take care of the PHI nodes.
13907 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13908 MI->getOperand(0).getReg())
13909 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13910 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13912 // Delete the original pseudo instruction.
13913 MI->eraseFromParent();
13916 return continueMBB;
13919 MachineBasicBlock *
13920 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13921 MachineBasicBlock *BB) const {
13922 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13923 DebugLoc DL = MI->getDebugLoc();
13925 assert(!Subtarget->isTargetEnvMacho());
13927 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13928 // non-trivial part is impdef of ESP.
13930 if (Subtarget->isTargetWin64()) {
13931 if (Subtarget->isTargetCygMing()) {
13932 // ___chkstk(Mingw64):
13933 // Clobbers R10, R11, RAX and EFLAGS.
13935 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13936 .addExternalSymbol("___chkstk")
13937 .addReg(X86::RAX, RegState::Implicit)
13938 .addReg(X86::RSP, RegState::Implicit)
13939 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13940 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13941 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13943 // __chkstk(MSVCRT): does not update stack pointer.
13944 // Clobbers R10, R11 and EFLAGS.
13945 // FIXME: RAX(allocated size) might be reused and not killed.
13946 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13947 .addExternalSymbol("__chkstk")
13948 .addReg(X86::RAX, RegState::Implicit)
13949 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13950 // RAX has the offset to subtracted from RSP.
13951 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13956 const char *StackProbeSymbol =
13957 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13959 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13960 .addExternalSymbol(StackProbeSymbol)
13961 .addReg(X86::EAX, RegState::Implicit)
13962 .addReg(X86::ESP, RegState::Implicit)
13963 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13964 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13965 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13968 MI->eraseFromParent(); // The pseudo instruction is gone now.
13972 MachineBasicBlock *
13973 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13974 MachineBasicBlock *BB) const {
13975 // This is pretty easy. We're taking the value that we received from
13976 // our load from the relocation, sticking it in either RDI (x86-64)
13977 // or EAX and doing an indirect call. The return value will then
13978 // be in the normal return register.
13979 const X86InstrInfo *TII
13980 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13981 DebugLoc DL = MI->getDebugLoc();
13982 MachineFunction *F = BB->getParent();
13984 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13985 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13987 // Get a register mask for the lowered call.
13988 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13989 // proper register mask.
13990 const uint32_t *RegMask =
13991 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13992 if (Subtarget->is64Bit()) {
13993 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13994 TII->get(X86::MOV64rm), X86::RDI)
13996 .addImm(0).addReg(0)
13997 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13998 MI->getOperand(3).getTargetFlags())
14000 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14001 addDirectMem(MIB, X86::RDI);
14002 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14003 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14004 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14005 TII->get(X86::MOV32rm), X86::EAX)
14007 .addImm(0).addReg(0)
14008 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14009 MI->getOperand(3).getTargetFlags())
14011 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14012 addDirectMem(MIB, X86::EAX);
14013 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14015 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14016 TII->get(X86::MOV32rm), X86::EAX)
14017 .addReg(TII->getGlobalBaseReg(F))
14018 .addImm(0).addReg(0)
14019 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14020 MI->getOperand(3).getTargetFlags())
14022 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14023 addDirectMem(MIB, X86::EAX);
14024 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14027 MI->eraseFromParent(); // The pseudo instruction is gone now.
14031 MachineBasicBlock *
14032 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14033 MachineBasicBlock *MBB) const {
14034 DebugLoc DL = MI->getDebugLoc();
14035 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14037 MachineFunction *MF = MBB->getParent();
14038 MachineRegisterInfo &MRI = MF->getRegInfo();
14040 const BasicBlock *BB = MBB->getBasicBlock();
14041 MachineFunction::iterator I = MBB;
14044 // Memory Reference
14045 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14046 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14049 unsigned MemOpndSlot = 0;
14051 unsigned CurOp = 0;
14053 DstReg = MI->getOperand(CurOp++).getReg();
14054 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14055 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14056 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14057 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14059 MemOpndSlot = CurOp;
14061 MVT PVT = getPointerTy();
14062 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14063 "Invalid Pointer Size!");
14065 // For v = setjmp(buf), we generate
14068 // buf[LabelOffset] = restoreMBB
14069 // SjLjSetup restoreMBB
14075 // v = phi(main, restore)
14080 MachineBasicBlock *thisMBB = MBB;
14081 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14082 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14083 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14084 MF->insert(I, mainMBB);
14085 MF->insert(I, sinkMBB);
14086 MF->push_back(restoreMBB);
14088 MachineInstrBuilder MIB;
14090 // Transfer the remainder of BB and its successor edges to sinkMBB.
14091 sinkMBB->splice(sinkMBB->begin(), MBB,
14092 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14093 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14096 unsigned PtrStoreOpc = 0;
14097 unsigned LabelReg = 0;
14098 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14099 Reloc::Model RM = getTargetMachine().getRelocationModel();
14100 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14101 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14103 // Prepare IP either in reg or imm.
14104 if (!UseImmLabel) {
14105 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14106 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14107 LabelReg = MRI.createVirtualRegister(PtrRC);
14108 if (Subtarget->is64Bit()) {
14109 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14113 .addMBB(restoreMBB)
14116 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14117 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14118 .addReg(XII->getGlobalBaseReg(MF))
14121 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14125 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14127 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14128 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14129 if (i == X86::AddrDisp)
14130 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14132 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14135 MIB.addReg(LabelReg);
14137 MIB.addMBB(restoreMBB);
14138 MIB.setMemRefs(MMOBegin, MMOEnd);
14140 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14141 .addMBB(restoreMBB);
14142 MIB.addRegMask(RegInfo->getNoPreservedMask());
14143 thisMBB->addSuccessor(mainMBB);
14144 thisMBB->addSuccessor(restoreMBB);
14148 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14149 mainMBB->addSuccessor(sinkMBB);
14152 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14153 TII->get(X86::PHI), DstReg)
14154 .addReg(mainDstReg).addMBB(mainMBB)
14155 .addReg(restoreDstReg).addMBB(restoreMBB);
14158 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14159 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14160 restoreMBB->addSuccessor(sinkMBB);
14162 MI->eraseFromParent();
14166 MachineBasicBlock *
14167 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14168 MachineBasicBlock *MBB) const {
14169 DebugLoc DL = MI->getDebugLoc();
14170 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14172 MachineFunction *MF = MBB->getParent();
14173 MachineRegisterInfo &MRI = MF->getRegInfo();
14175 // Memory Reference
14176 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14177 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14179 MVT PVT = getPointerTy();
14180 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14181 "Invalid Pointer Size!");
14183 const TargetRegisterClass *RC =
14184 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14185 unsigned Tmp = MRI.createVirtualRegister(RC);
14186 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14187 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14188 unsigned SP = RegInfo->getStackRegister();
14190 MachineInstrBuilder MIB;
14192 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14193 const int64_t SPOffset = 2 * PVT.getStoreSize();
14195 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14196 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14199 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14200 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14201 MIB.addOperand(MI->getOperand(i));
14202 MIB.setMemRefs(MMOBegin, MMOEnd);
14204 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14205 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14206 if (i == X86::AddrDisp)
14207 MIB.addDisp(MI->getOperand(i), LabelOffset);
14209 MIB.addOperand(MI->getOperand(i));
14211 MIB.setMemRefs(MMOBegin, MMOEnd);
14213 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14214 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14215 if (i == X86::AddrDisp)
14216 MIB.addDisp(MI->getOperand(i), SPOffset);
14218 MIB.addOperand(MI->getOperand(i));
14220 MIB.setMemRefs(MMOBegin, MMOEnd);
14222 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14224 MI->eraseFromParent();
14228 MachineBasicBlock *
14229 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14230 MachineBasicBlock *BB) const {
14231 switch (MI->getOpcode()) {
14232 default: llvm_unreachable("Unexpected instr type to insert");
14233 case X86::TAILJMPd64:
14234 case X86::TAILJMPr64:
14235 case X86::TAILJMPm64:
14236 llvm_unreachable("TAILJMP64 would not be touched here.");
14237 case X86::TCRETURNdi64:
14238 case X86::TCRETURNri64:
14239 case X86::TCRETURNmi64:
14241 case X86::WIN_ALLOCA:
14242 return EmitLoweredWinAlloca(MI, BB);
14243 case X86::SEG_ALLOCA_32:
14244 return EmitLoweredSegAlloca(MI, BB, false);
14245 case X86::SEG_ALLOCA_64:
14246 return EmitLoweredSegAlloca(MI, BB, true);
14247 case X86::TLSCall_32:
14248 case X86::TLSCall_64:
14249 return EmitLoweredTLSCall(MI, BB);
14250 case X86::CMOV_GR8:
14251 case X86::CMOV_FR32:
14252 case X86::CMOV_FR64:
14253 case X86::CMOV_V4F32:
14254 case X86::CMOV_V2F64:
14255 case X86::CMOV_V2I64:
14256 case X86::CMOV_V8F32:
14257 case X86::CMOV_V4F64:
14258 case X86::CMOV_V4I64:
14259 case X86::CMOV_GR16:
14260 case X86::CMOV_GR32:
14261 case X86::CMOV_RFP32:
14262 case X86::CMOV_RFP64:
14263 case X86::CMOV_RFP80:
14264 return EmitLoweredSelect(MI, BB);
14266 case X86::FP32_TO_INT16_IN_MEM:
14267 case X86::FP32_TO_INT32_IN_MEM:
14268 case X86::FP32_TO_INT64_IN_MEM:
14269 case X86::FP64_TO_INT16_IN_MEM:
14270 case X86::FP64_TO_INT32_IN_MEM:
14271 case X86::FP64_TO_INT64_IN_MEM:
14272 case X86::FP80_TO_INT16_IN_MEM:
14273 case X86::FP80_TO_INT32_IN_MEM:
14274 case X86::FP80_TO_INT64_IN_MEM: {
14275 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14276 DebugLoc DL = MI->getDebugLoc();
14278 // Change the floating point control register to use "round towards zero"
14279 // mode when truncating to an integer value.
14280 MachineFunction *F = BB->getParent();
14281 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14282 addFrameReference(BuildMI(*BB, MI, DL,
14283 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14285 // Load the old value of the high byte of the control word...
14287 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14288 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14291 // Set the high part to be round to zero...
14292 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14295 // Reload the modified control word now...
14296 addFrameReference(BuildMI(*BB, MI, DL,
14297 TII->get(X86::FLDCW16m)), CWFrameIdx);
14299 // Restore the memory image of control word to original value
14300 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14303 // Get the X86 opcode to use.
14305 switch (MI->getOpcode()) {
14306 default: llvm_unreachable("illegal opcode!");
14307 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14308 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14309 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14310 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14311 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14312 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14313 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14314 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14315 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14319 MachineOperand &Op = MI->getOperand(0);
14321 AM.BaseType = X86AddressMode::RegBase;
14322 AM.Base.Reg = Op.getReg();
14324 AM.BaseType = X86AddressMode::FrameIndexBase;
14325 AM.Base.FrameIndex = Op.getIndex();
14327 Op = MI->getOperand(1);
14329 AM.Scale = Op.getImm();
14330 Op = MI->getOperand(2);
14332 AM.IndexReg = Op.getImm();
14333 Op = MI->getOperand(3);
14334 if (Op.isGlobal()) {
14335 AM.GV = Op.getGlobal();
14337 AM.Disp = Op.getImm();
14339 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14340 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14342 // Reload the original control word now.
14343 addFrameReference(BuildMI(*BB, MI, DL,
14344 TII->get(X86::FLDCW16m)), CWFrameIdx);
14346 MI->eraseFromParent(); // The pseudo instruction is gone now.
14349 // String/text processing lowering.
14350 case X86::PCMPISTRM128REG:
14351 case X86::VPCMPISTRM128REG:
14352 case X86::PCMPISTRM128MEM:
14353 case X86::VPCMPISTRM128MEM:
14354 case X86::PCMPESTRM128REG:
14355 case X86::VPCMPESTRM128REG:
14356 case X86::PCMPESTRM128MEM:
14357 case X86::VPCMPESTRM128MEM:
14358 assert(Subtarget->hasSSE42() &&
14359 "Target must have SSE4.2 or AVX features enabled");
14360 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14362 // String/text processing lowering.
14363 case X86::PCMPISTRIREG:
14364 case X86::VPCMPISTRIREG:
14365 case X86::PCMPISTRIMEM:
14366 case X86::VPCMPISTRIMEM:
14367 case X86::PCMPESTRIREG:
14368 case X86::VPCMPESTRIREG:
14369 case X86::PCMPESTRIMEM:
14370 case X86::VPCMPESTRIMEM:
14371 assert(Subtarget->hasSSE42() &&
14372 "Target must have SSE4.2 or AVX features enabled");
14373 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14375 // Thread synchronization.
14377 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14381 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14383 // Atomic Lowering.
14384 case X86::ATOMAND8:
14385 case X86::ATOMAND16:
14386 case X86::ATOMAND32:
14387 case X86::ATOMAND64:
14390 case X86::ATOMOR16:
14391 case X86::ATOMOR32:
14392 case X86::ATOMOR64:
14394 case X86::ATOMXOR16:
14395 case X86::ATOMXOR8:
14396 case X86::ATOMXOR32:
14397 case X86::ATOMXOR64:
14399 case X86::ATOMNAND8:
14400 case X86::ATOMNAND16:
14401 case X86::ATOMNAND32:
14402 case X86::ATOMNAND64:
14404 case X86::ATOMMAX8:
14405 case X86::ATOMMAX16:
14406 case X86::ATOMMAX32:
14407 case X86::ATOMMAX64:
14409 case X86::ATOMMIN8:
14410 case X86::ATOMMIN16:
14411 case X86::ATOMMIN32:
14412 case X86::ATOMMIN64:
14414 case X86::ATOMUMAX8:
14415 case X86::ATOMUMAX16:
14416 case X86::ATOMUMAX32:
14417 case X86::ATOMUMAX64:
14419 case X86::ATOMUMIN8:
14420 case X86::ATOMUMIN16:
14421 case X86::ATOMUMIN32:
14422 case X86::ATOMUMIN64:
14423 return EmitAtomicLoadArith(MI, BB);
14425 // This group does 64-bit operations on a 32-bit host.
14426 case X86::ATOMAND6432:
14427 case X86::ATOMOR6432:
14428 case X86::ATOMXOR6432:
14429 case X86::ATOMNAND6432:
14430 case X86::ATOMADD6432:
14431 case X86::ATOMSUB6432:
14432 case X86::ATOMMAX6432:
14433 case X86::ATOMMIN6432:
14434 case X86::ATOMUMAX6432:
14435 case X86::ATOMUMIN6432:
14436 case X86::ATOMSWAP6432:
14437 return EmitAtomicLoadArith6432(MI, BB);
14439 case X86::VASTART_SAVE_XMM_REGS:
14440 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14442 case X86::VAARG_64:
14443 return EmitVAARG64WithCustomInserter(MI, BB);
14445 case X86::EH_SjLj_SetJmp32:
14446 case X86::EH_SjLj_SetJmp64:
14447 return emitEHSjLjSetJmp(MI, BB);
14449 case X86::EH_SjLj_LongJmp32:
14450 case X86::EH_SjLj_LongJmp64:
14451 return emitEHSjLjLongJmp(MI, BB);
14455 //===----------------------------------------------------------------------===//
14456 // X86 Optimization Hooks
14457 //===----------------------------------------------------------------------===//
14459 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14462 const SelectionDAG &DAG,
14463 unsigned Depth) const {
14464 unsigned BitWidth = KnownZero.getBitWidth();
14465 unsigned Opc = Op.getOpcode();
14466 assert((Opc >= ISD::BUILTIN_OP_END ||
14467 Opc == ISD::INTRINSIC_WO_CHAIN ||
14468 Opc == ISD::INTRINSIC_W_CHAIN ||
14469 Opc == ISD::INTRINSIC_VOID) &&
14470 "Should use MaskedValueIsZero if you don't know whether Op"
14471 " is a target node!");
14473 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14487 // These nodes' second result is a boolean.
14488 if (Op.getResNo() == 0)
14491 case X86ISD::SETCC:
14492 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14494 case ISD::INTRINSIC_WO_CHAIN: {
14495 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14496 unsigned NumLoBits = 0;
14499 case Intrinsic::x86_sse_movmsk_ps:
14500 case Intrinsic::x86_avx_movmsk_ps_256:
14501 case Intrinsic::x86_sse2_movmsk_pd:
14502 case Intrinsic::x86_avx_movmsk_pd_256:
14503 case Intrinsic::x86_mmx_pmovmskb:
14504 case Intrinsic::x86_sse2_pmovmskb_128:
14505 case Intrinsic::x86_avx2_pmovmskb: {
14506 // High bits of movmskp{s|d}, pmovmskb are known zero.
14508 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14509 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14510 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14511 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14512 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14513 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14514 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14515 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14517 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14526 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14527 unsigned Depth) const {
14528 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14529 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14530 return Op.getValueType().getScalarType().getSizeInBits();
14536 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14537 /// node is a GlobalAddress + offset.
14538 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14539 const GlobalValue* &GA,
14540 int64_t &Offset) const {
14541 if (N->getOpcode() == X86ISD::Wrapper) {
14542 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14543 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14544 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14548 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14551 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14552 /// same as extracting the high 128-bit part of 256-bit vector and then
14553 /// inserting the result into the low part of a new 256-bit vector
14554 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14555 EVT VT = SVOp->getValueType(0);
14556 unsigned NumElems = VT.getVectorNumElements();
14558 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14559 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14560 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14561 SVOp->getMaskElt(j) >= 0)
14567 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14568 /// same as extracting the low 128-bit part of 256-bit vector and then
14569 /// inserting the result into the high part of a new 256-bit vector
14570 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14571 EVT VT = SVOp->getValueType(0);
14572 unsigned NumElems = VT.getVectorNumElements();
14574 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14575 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14576 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14577 SVOp->getMaskElt(j) >= 0)
14583 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14584 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14585 TargetLowering::DAGCombinerInfo &DCI,
14586 const X86Subtarget* Subtarget) {
14587 DebugLoc dl = N->getDebugLoc();
14588 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14589 SDValue V1 = SVOp->getOperand(0);
14590 SDValue V2 = SVOp->getOperand(1);
14591 EVT VT = SVOp->getValueType(0);
14592 unsigned NumElems = VT.getVectorNumElements();
14594 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14595 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14599 // V UNDEF BUILD_VECTOR UNDEF
14601 // CONCAT_VECTOR CONCAT_VECTOR
14604 // RESULT: V + zero extended
14606 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14607 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14608 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14611 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14614 // To match the shuffle mask, the first half of the mask should
14615 // be exactly the first vector, and all the rest a splat with the
14616 // first element of the second one.
14617 for (unsigned i = 0; i != NumElems/2; ++i)
14618 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14619 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14622 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14623 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14624 if (Ld->hasNUsesOfValue(1, 0)) {
14625 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14626 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14628 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14630 Ld->getPointerInfo(),
14631 Ld->getAlignment(),
14632 false/*isVolatile*/, true/*ReadMem*/,
14633 false/*WriteMem*/);
14635 // Make sure the newly-created LOAD is in the same position as Ld in
14636 // terms of dependency. We create a TokenFactor for Ld and ResNode,
14637 // and update uses of Ld's output chain to use the TokenFactor.
14638 if (Ld->hasAnyUseOfValue(1)) {
14639 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14640 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14641 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14642 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14643 SDValue(ResNode.getNode(), 1));
14646 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14650 // Emit a zeroed vector and insert the desired subvector on its
14652 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14653 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14654 return DCI.CombineTo(N, InsV);
14657 //===--------------------------------------------------------------------===//
14658 // Combine some shuffles into subvector extracts and inserts:
14661 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14662 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14663 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14664 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14665 return DCI.CombineTo(N, InsV);
14668 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14669 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14670 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14671 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14672 return DCI.CombineTo(N, InsV);
14678 /// PerformShuffleCombine - Performs several different shuffle combines.
14679 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14680 TargetLowering::DAGCombinerInfo &DCI,
14681 const X86Subtarget *Subtarget) {
14682 DebugLoc dl = N->getDebugLoc();
14683 EVT VT = N->getValueType(0);
14685 // Don't create instructions with illegal types after legalize types has run.
14686 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14687 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14690 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14691 if (Subtarget->hasFp256() && VT.is256BitVector() &&
14692 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14693 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14695 // Only handle 128 wide vector from here on.
14696 if (!VT.is128BitVector())
14699 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14700 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14701 // consecutive, non-overlapping, and in the right order.
14702 SmallVector<SDValue, 16> Elts;
14703 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14704 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14706 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14709 /// PerformTruncateCombine - Converts truncate operation to
14710 /// a sequence of vector shuffle operations.
14711 /// It is possible when we truncate 256-bit vector to 128-bit vector
14712 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14713 TargetLowering::DAGCombinerInfo &DCI,
14714 const X86Subtarget *Subtarget) {
14718 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14719 /// specific shuffle of a load can be folded into a single element load.
14720 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14721 /// shuffles have been customed lowered so we need to handle those here.
14722 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14723 TargetLowering::DAGCombinerInfo &DCI) {
14724 if (DCI.isBeforeLegalizeOps())
14727 SDValue InVec = N->getOperand(0);
14728 SDValue EltNo = N->getOperand(1);
14730 if (!isa<ConstantSDNode>(EltNo))
14733 EVT VT = InVec.getValueType();
14735 bool HasShuffleIntoBitcast = false;
14736 if (InVec.getOpcode() == ISD::BITCAST) {
14737 // Don't duplicate a load with other uses.
14738 if (!InVec.hasOneUse())
14740 EVT BCVT = InVec.getOperand(0).getValueType();
14741 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14743 InVec = InVec.getOperand(0);
14744 HasShuffleIntoBitcast = true;
14747 if (!isTargetShuffle(InVec.getOpcode()))
14750 // Don't duplicate a load with other uses.
14751 if (!InVec.hasOneUse())
14754 SmallVector<int, 16> ShuffleMask;
14756 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14760 // Select the input vector, guarding against out of range extract vector.
14761 unsigned NumElems = VT.getVectorNumElements();
14762 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14763 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14764 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14765 : InVec.getOperand(1);
14767 // If inputs to shuffle are the same for both ops, then allow 2 uses
14768 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14770 if (LdNode.getOpcode() == ISD::BITCAST) {
14771 // Don't duplicate a load with other uses.
14772 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14775 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14776 LdNode = LdNode.getOperand(0);
14779 if (!ISD::isNormalLoad(LdNode.getNode()))
14782 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14784 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14787 if (HasShuffleIntoBitcast) {
14788 // If there's a bitcast before the shuffle, check if the load type and
14789 // alignment is valid.
14790 unsigned Align = LN0->getAlignment();
14791 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14792 unsigned NewAlign = TLI.getDataLayout()->
14793 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14795 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14799 // All checks match so transform back to vector_shuffle so that DAG combiner
14800 // can finish the job
14801 DebugLoc dl = N->getDebugLoc();
14803 // Create shuffle node taking into account the case that its a unary shuffle
14804 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14805 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14806 InVec.getOperand(0), Shuffle,
14808 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14809 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14813 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14814 /// generation and convert it from being a bunch of shuffles and extracts
14815 /// to a simple store and scalar loads to extract the elements.
14816 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14817 TargetLowering::DAGCombinerInfo &DCI) {
14818 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14819 if (NewOp.getNode())
14822 SDValue InputVector = N->getOperand(0);
14823 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14824 // from mmx to v2i32 has a single usage.
14825 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14826 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14827 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14828 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14829 N->getValueType(0),
14830 InputVector.getNode()->getOperand(0));
14832 // Only operate on vectors of 4 elements, where the alternative shuffling
14833 // gets to be more expensive.
14834 if (InputVector.getValueType() != MVT::v4i32)
14837 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14838 // single use which is a sign-extend or zero-extend, and all elements are
14840 SmallVector<SDNode *, 4> Uses;
14841 unsigned ExtractedElements = 0;
14842 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14843 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14844 if (UI.getUse().getResNo() != InputVector.getResNo())
14847 SDNode *Extract = *UI;
14848 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14851 if (Extract->getValueType(0) != MVT::i32)
14853 if (!Extract->hasOneUse())
14855 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14856 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14858 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14861 // Record which element was extracted.
14862 ExtractedElements |=
14863 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14865 Uses.push_back(Extract);
14868 // If not all the elements were used, this may not be worthwhile.
14869 if (ExtractedElements != 15)
14872 // Ok, we've now decided to do the transformation.
14873 DebugLoc dl = InputVector.getDebugLoc();
14875 // Store the value to a temporary stack slot.
14876 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14877 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14878 MachinePointerInfo(), false, false, 0);
14880 // Replace each use (extract) with a load of the appropriate element.
14881 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14882 UE = Uses.end(); UI != UE; ++UI) {
14883 SDNode *Extract = *UI;
14885 // cOMpute the element's address.
14886 SDValue Idx = Extract->getOperand(1);
14888 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14889 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14890 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14891 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14893 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14894 StackPtr, OffsetVal);
14896 // Load the scalar.
14897 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14898 ScalarAddr, MachinePointerInfo(),
14899 false, false, false, 0);
14901 // Replace the exact with the load.
14902 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14905 // The replacement was made in place; don't return anything.
14909 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14910 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14911 SDValue RHS, SelectionDAG &DAG,
14912 const X86Subtarget *Subtarget) {
14913 if (!VT.isVector())
14916 switch (VT.getSimpleVT().SimpleTy) {
14921 if (!Subtarget->hasAVX2())
14926 if (!Subtarget->hasSSE2())
14930 // SSE2 has only a small subset of the operations.
14931 bool hasUnsigned = Subtarget->hasSSE41() ||
14932 (Subtarget->hasSSE2() && VT == MVT::v16i8);
14933 bool hasSigned = Subtarget->hasSSE41() ||
14934 (Subtarget->hasSSE2() && VT == MVT::v8i16);
14936 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14938 // Check for x CC y ? x : y.
14939 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14940 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14945 return hasUnsigned ? X86ISD::UMIN : 0;
14948 return hasUnsigned ? X86ISD::UMAX : 0;
14951 return hasSigned ? X86ISD::SMIN : 0;
14954 return hasSigned ? X86ISD::SMAX : 0;
14956 // Check for x CC y ? y : x -- a min/max with reversed arms.
14957 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14958 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14963 return hasUnsigned ? X86ISD::UMAX : 0;
14966 return hasUnsigned ? X86ISD::UMIN : 0;
14969 return hasSigned ? X86ISD::SMAX : 0;
14972 return hasSigned ? X86ISD::SMIN : 0;
14979 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14981 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14982 TargetLowering::DAGCombinerInfo &DCI,
14983 const X86Subtarget *Subtarget) {
14984 DebugLoc DL = N->getDebugLoc();
14985 SDValue Cond = N->getOperand(0);
14986 // Get the LHS/RHS of the select.
14987 SDValue LHS = N->getOperand(1);
14988 SDValue RHS = N->getOperand(2);
14989 EVT VT = LHS.getValueType();
14991 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14992 // instructions match the semantics of the common C idiom x<y?x:y but not
14993 // x<=y?x:y, because of how they handle negative zero (which can be
14994 // ignored in unsafe-math mode).
14995 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14996 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14997 (Subtarget->hasSSE2() ||
14998 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14999 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15001 unsigned Opcode = 0;
15002 // Check for x CC y ? x : y.
15003 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15004 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15008 // Converting this to a min would handle NaNs incorrectly, and swapping
15009 // the operands would cause it to handle comparisons between positive
15010 // and negative zero incorrectly.
15011 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15012 if (!DAG.getTarget().Options.UnsafeFPMath &&
15013 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15015 std::swap(LHS, RHS);
15017 Opcode = X86ISD::FMIN;
15020 // Converting this to a min would handle comparisons between positive
15021 // and negative zero incorrectly.
15022 if (!DAG.getTarget().Options.UnsafeFPMath &&
15023 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15025 Opcode = X86ISD::FMIN;
15028 // Converting this to a min would handle both negative zeros and NaNs
15029 // incorrectly, but we can swap the operands to fix both.
15030 std::swap(LHS, RHS);
15034 Opcode = X86ISD::FMIN;
15038 // Converting this to a max would handle comparisons between positive
15039 // and negative zero incorrectly.
15040 if (!DAG.getTarget().Options.UnsafeFPMath &&
15041 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15043 Opcode = X86ISD::FMAX;
15046 // Converting this to a max would handle NaNs incorrectly, and swapping
15047 // the operands would cause it to handle comparisons between positive
15048 // and negative zero incorrectly.
15049 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15050 if (!DAG.getTarget().Options.UnsafeFPMath &&
15051 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15053 std::swap(LHS, RHS);
15055 Opcode = X86ISD::FMAX;
15058 // Converting this to a max would handle both negative zeros and NaNs
15059 // incorrectly, but we can swap the operands to fix both.
15060 std::swap(LHS, RHS);
15064 Opcode = X86ISD::FMAX;
15067 // Check for x CC y ? y : x -- a min/max with reversed arms.
15068 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15069 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15073 // Converting this to a min would handle comparisons between positive
15074 // and negative zero incorrectly, and swapping the operands would
15075 // cause it to handle NaNs incorrectly.
15076 if (!DAG.getTarget().Options.UnsafeFPMath &&
15077 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15078 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15080 std::swap(LHS, RHS);
15082 Opcode = X86ISD::FMIN;
15085 // Converting this to a min would handle NaNs incorrectly.
15086 if (!DAG.getTarget().Options.UnsafeFPMath &&
15087 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15089 Opcode = X86ISD::FMIN;
15092 // Converting this to a min would handle both negative zeros and NaNs
15093 // incorrectly, but we can swap the operands to fix both.
15094 std::swap(LHS, RHS);
15098 Opcode = X86ISD::FMIN;
15102 // Converting this to a max would handle NaNs incorrectly.
15103 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15105 Opcode = X86ISD::FMAX;
15108 // Converting this to a max would handle comparisons between positive
15109 // and negative zero incorrectly, and swapping the operands would
15110 // cause it to handle NaNs incorrectly.
15111 if (!DAG.getTarget().Options.UnsafeFPMath &&
15112 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15113 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15115 std::swap(LHS, RHS);
15117 Opcode = X86ISD::FMAX;
15120 // Converting this to a max would handle both negative zeros and NaNs
15121 // incorrectly, but we can swap the operands to fix both.
15122 std::swap(LHS, RHS);
15126 Opcode = X86ISD::FMAX;
15132 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15135 // If this is a select between two integer constants, try to do some
15137 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15138 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15139 // Don't do this for crazy integer types.
15140 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15141 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15142 // so that TrueC (the true value) is larger than FalseC.
15143 bool NeedsCondInvert = false;
15145 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15146 // Efficiently invertible.
15147 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15148 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15149 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15150 NeedsCondInvert = true;
15151 std::swap(TrueC, FalseC);
15154 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15155 if (FalseC->getAPIntValue() == 0 &&
15156 TrueC->getAPIntValue().isPowerOf2()) {
15157 if (NeedsCondInvert) // Invert the condition if needed.
15158 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15159 DAG.getConstant(1, Cond.getValueType()));
15161 // Zero extend the condition if needed.
15162 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15164 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15165 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15166 DAG.getConstant(ShAmt, MVT::i8));
15169 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15170 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15171 if (NeedsCondInvert) // Invert the condition if needed.
15172 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15173 DAG.getConstant(1, Cond.getValueType()));
15175 // Zero extend the condition if needed.
15176 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15177 FalseC->getValueType(0), Cond);
15178 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15179 SDValue(FalseC, 0));
15182 // Optimize cases that will turn into an LEA instruction. This requires
15183 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15184 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15185 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15186 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15188 bool isFastMultiplier = false;
15190 switch ((unsigned char)Diff) {
15192 case 1: // result = add base, cond
15193 case 2: // result = lea base( , cond*2)
15194 case 3: // result = lea base(cond, cond*2)
15195 case 4: // result = lea base( , cond*4)
15196 case 5: // result = lea base(cond, cond*4)
15197 case 8: // result = lea base( , cond*8)
15198 case 9: // result = lea base(cond, cond*8)
15199 isFastMultiplier = true;
15204 if (isFastMultiplier) {
15205 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15206 if (NeedsCondInvert) // Invert the condition if needed.
15207 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15208 DAG.getConstant(1, Cond.getValueType()));
15210 // Zero extend the condition if needed.
15211 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15213 // Scale the condition by the difference.
15215 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15216 DAG.getConstant(Diff, Cond.getValueType()));
15218 // Add the base if non-zero.
15219 if (FalseC->getAPIntValue() != 0)
15220 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15221 SDValue(FalseC, 0));
15228 // Canonicalize max and min:
15229 // (x > y) ? x : y -> (x >= y) ? x : y
15230 // (x < y) ? x : y -> (x <= y) ? x : y
15231 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15232 // the need for an extra compare
15233 // against zero. e.g.
15234 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15236 // testl %edi, %edi
15238 // cmovgl %edi, %eax
15242 // cmovsl %eax, %edi
15243 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15244 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15245 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15246 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15251 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15252 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15253 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15254 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15259 // Match VSELECTs into subs with unsigned saturation.
15260 if (!DCI.isBeforeLegalize() &&
15261 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15262 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15263 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15264 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15265 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15267 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15268 // left side invert the predicate to simplify logic below.
15270 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15272 CC = ISD::getSetCCInverse(CC, true);
15273 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15277 if (Other.getNode() && Other->getNumOperands() == 2 &&
15278 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15279 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15280 SDValue CondRHS = Cond->getOperand(1);
15282 // Look for a general sub with unsigned saturation first.
15283 // x >= y ? x-y : 0 --> subus x, y
15284 // x > y ? x-y : 0 --> subus x, y
15285 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15286 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15287 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15289 // If the RHS is a constant we have to reverse the const canonicalization.
15290 // x > C-1 ? x+-C : 0 --> subus x, C
15291 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15292 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15293 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15294 if (CondRHS.getConstantOperandVal(0) == -A-1) {
15295 SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15296 DAG.getConstant(-A, VT.getScalarType()));
15297 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15298 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15299 V.data(), V.size()));
15303 // Another special case: If C was a sign bit, the sub has been
15304 // canonicalized into a xor.
15305 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15306 // it's safe to decanonicalize the xor?
15307 // x s< 0 ? x^C : 0 --> subus x, C
15308 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15309 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15310 isSplatVector(OpRHS.getNode())) {
15311 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15313 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15318 // Try to match a min/max vector operation.
15319 if (!DCI.isBeforeLegalize() &&
15320 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15321 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15322 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15324 // If we know that this node is legal then we know that it is going to be
15325 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15326 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15327 // to simplify previous instructions.
15328 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15329 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15330 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15331 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15333 // Don't optimize vector selects that map to mask-registers.
15337 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15338 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15340 APInt KnownZero, KnownOne;
15341 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15342 DCI.isBeforeLegalizeOps());
15343 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15344 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15345 DCI.CommitTargetLoweringOpt(TLO);
15351 // Check whether a boolean test is testing a boolean value generated by
15352 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15355 // Simplify the following patterns:
15356 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15357 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15358 // to (Op EFLAGS Cond)
15360 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15361 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15362 // to (Op EFLAGS !Cond)
15364 // where Op could be BRCOND or CMOV.
15366 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15367 // Quit if not CMP and SUB with its value result used.
15368 if (Cmp.getOpcode() != X86ISD::CMP &&
15369 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15372 // Quit if not used as a boolean value.
15373 if (CC != X86::COND_E && CC != X86::COND_NE)
15376 // Check CMP operands. One of them should be 0 or 1 and the other should be
15377 // an SetCC or extended from it.
15378 SDValue Op1 = Cmp.getOperand(0);
15379 SDValue Op2 = Cmp.getOperand(1);
15382 const ConstantSDNode* C = 0;
15383 bool needOppositeCond = (CC == X86::COND_E);
15385 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15387 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15389 else // Quit if all operands are not constants.
15392 if (C->getZExtValue() == 1)
15393 needOppositeCond = !needOppositeCond;
15394 else if (C->getZExtValue() != 0)
15395 // Quit if the constant is neither 0 or 1.
15398 // Skip 'zext' node.
15399 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15400 SetCC = SetCC.getOperand(0);
15402 switch (SetCC.getOpcode()) {
15403 case X86ISD::SETCC:
15404 // Set the condition code or opposite one if necessary.
15405 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15406 if (needOppositeCond)
15407 CC = X86::GetOppositeBranchCondition(CC);
15408 return SetCC.getOperand(1);
15409 case X86ISD::CMOV: {
15410 // Check whether false/true value has canonical one, i.e. 0 or 1.
15411 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15412 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15413 // Quit if true value is not a constant.
15416 // Quit if false value is not a constant.
15418 // A special case for rdrand, where 0 is set if false cond is found.
15419 SDValue Op = SetCC.getOperand(0);
15420 if (Op.getOpcode() != X86ISD::RDRAND)
15423 // Quit if false value is not the constant 0 or 1.
15424 bool FValIsFalse = true;
15425 if (FVal && FVal->getZExtValue() != 0) {
15426 if (FVal->getZExtValue() != 1)
15428 // If FVal is 1, opposite cond is needed.
15429 needOppositeCond = !needOppositeCond;
15430 FValIsFalse = false;
15432 // Quit if TVal is not the constant opposite of FVal.
15433 if (FValIsFalse && TVal->getZExtValue() != 1)
15435 if (!FValIsFalse && TVal->getZExtValue() != 0)
15437 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15438 if (needOppositeCond)
15439 CC = X86::GetOppositeBranchCondition(CC);
15440 return SetCC.getOperand(3);
15447 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15448 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15449 TargetLowering::DAGCombinerInfo &DCI,
15450 const X86Subtarget *Subtarget) {
15451 DebugLoc DL = N->getDebugLoc();
15453 // If the flag operand isn't dead, don't touch this CMOV.
15454 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15457 SDValue FalseOp = N->getOperand(0);
15458 SDValue TrueOp = N->getOperand(1);
15459 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15460 SDValue Cond = N->getOperand(3);
15462 if (CC == X86::COND_E || CC == X86::COND_NE) {
15463 switch (Cond.getOpcode()) {
15467 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15468 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15469 return (CC == X86::COND_E) ? FalseOp : TrueOp;
15475 Flags = checkBoolTestSetCCCombine(Cond, CC);
15476 if (Flags.getNode() &&
15477 // Extra check as FCMOV only supports a subset of X86 cond.
15478 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15479 SDValue Ops[] = { FalseOp, TrueOp,
15480 DAG.getConstant(CC, MVT::i8), Flags };
15481 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15482 Ops, array_lengthof(Ops));
15485 // If this is a select between two integer constants, try to do some
15486 // optimizations. Note that the operands are ordered the opposite of SELECT
15488 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15489 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15490 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15491 // larger than FalseC (the false value).
15492 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15493 CC = X86::GetOppositeBranchCondition(CC);
15494 std::swap(TrueC, FalseC);
15495 std::swap(TrueOp, FalseOp);
15498 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
15499 // This is efficient for any integer data type (including i8/i16) and
15501 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15502 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15503 DAG.getConstant(CC, MVT::i8), Cond);
15505 // Zero extend the condition if needed.
15506 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15508 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15509 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15510 DAG.getConstant(ShAmt, MVT::i8));
15511 if (N->getNumValues() == 2) // Dead flag value?
15512 return DCI.CombineTo(N, Cond, SDValue());
15516 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
15517 // for any integer data type, including i8/i16.
15518 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15519 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15520 DAG.getConstant(CC, MVT::i8), Cond);
15522 // Zero extend the condition if needed.
15523 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15524 FalseC->getValueType(0), Cond);
15525 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15526 SDValue(FalseC, 0));
15528 if (N->getNumValues() == 2) // Dead flag value?
15529 return DCI.CombineTo(N, Cond, SDValue());
15533 // Optimize cases that will turn into an LEA instruction. This requires
15534 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15535 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15536 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15537 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15539 bool isFastMultiplier = false;
15541 switch ((unsigned char)Diff) {
15543 case 1: // result = add base, cond
15544 case 2: // result = lea base( , cond*2)
15545 case 3: // result = lea base(cond, cond*2)
15546 case 4: // result = lea base( , cond*4)
15547 case 5: // result = lea base(cond, cond*4)
15548 case 8: // result = lea base( , cond*8)
15549 case 9: // result = lea base(cond, cond*8)
15550 isFastMultiplier = true;
15555 if (isFastMultiplier) {
15556 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15557 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15558 DAG.getConstant(CC, MVT::i8), Cond);
15559 // Zero extend the condition if needed.
15560 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15562 // Scale the condition by the difference.
15564 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15565 DAG.getConstant(Diff, Cond.getValueType()));
15567 // Add the base if non-zero.
15568 if (FalseC->getAPIntValue() != 0)
15569 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15570 SDValue(FalseC, 0));
15571 if (N->getNumValues() == 2) // Dead flag value?
15572 return DCI.CombineTo(N, Cond, SDValue());
15579 // Handle these cases:
15580 // (select (x != c), e, c) -> select (x != c), e, x),
15581 // (select (x == c), c, e) -> select (x == c), x, e)
15582 // where the c is an integer constant, and the "select" is the combination
15583 // of CMOV and CMP.
15585 // The rationale for this change is that the conditional-move from a constant
15586 // needs two instructions, however, conditional-move from a register needs
15587 // only one instruction.
15589 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15590 // some instruction-combining opportunities. This opt needs to be
15591 // postponed as late as possible.
15593 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15594 // the DCI.xxxx conditions are provided to postpone the optimization as
15595 // late as possible.
15597 ConstantSDNode *CmpAgainst = 0;
15598 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15599 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15600 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15602 if (CC == X86::COND_NE &&
15603 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15604 CC = X86::GetOppositeBranchCondition(CC);
15605 std::swap(TrueOp, FalseOp);
15608 if (CC == X86::COND_E &&
15609 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15610 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15611 DAG.getConstant(CC, MVT::i8), Cond };
15612 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15613 array_lengthof(Ops));
15621 /// PerformMulCombine - Optimize a single multiply with constant into two
15622 /// in order to implement it with two cheaper instructions, e.g.
15623 /// LEA + SHL, LEA + LEA.
15624 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15625 TargetLowering::DAGCombinerInfo &DCI) {
15626 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15629 EVT VT = N->getValueType(0);
15630 if (VT != MVT::i64)
15633 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15636 uint64_t MulAmt = C->getZExtValue();
15637 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15640 uint64_t MulAmt1 = 0;
15641 uint64_t MulAmt2 = 0;
15642 if ((MulAmt % 9) == 0) {
15644 MulAmt2 = MulAmt / 9;
15645 } else if ((MulAmt % 5) == 0) {
15647 MulAmt2 = MulAmt / 5;
15648 } else if ((MulAmt % 3) == 0) {
15650 MulAmt2 = MulAmt / 3;
15653 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15654 DebugLoc DL = N->getDebugLoc();
15656 if (isPowerOf2_64(MulAmt2) &&
15657 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15658 // If second multiplifer is pow2, issue it first. We want the multiply by
15659 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15661 std::swap(MulAmt1, MulAmt2);
15664 if (isPowerOf2_64(MulAmt1))
15665 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15666 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15668 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15669 DAG.getConstant(MulAmt1, VT));
15671 if (isPowerOf2_64(MulAmt2))
15672 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15673 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15675 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15676 DAG.getConstant(MulAmt2, VT));
15678 // Do not add new nodes to DAG combiner worklist.
15679 DCI.CombineTo(N, NewMul, false);
15684 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15685 SDValue N0 = N->getOperand(0);
15686 SDValue N1 = N->getOperand(1);
15687 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15688 EVT VT = N0.getValueType();
15690 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15691 // since the result of setcc_c is all zero's or all ones.
15692 if (VT.isInteger() && !VT.isVector() &&
15693 N1C && N0.getOpcode() == ISD::AND &&
15694 N0.getOperand(1).getOpcode() == ISD::Constant) {
15695 SDValue N00 = N0.getOperand(0);
15696 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15697 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15698 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15699 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15700 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15701 APInt ShAmt = N1C->getAPIntValue();
15702 Mask = Mask.shl(ShAmt);
15704 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15705 N00, DAG.getConstant(Mask, VT));
15709 // Hardware support for vector shifts is sparse which makes us scalarize the
15710 // vector operations in many cases. Also, on sandybridge ADD is faster than
15712 // (shl V, 1) -> add V,V
15713 if (isSplatVector(N1.getNode())) {
15714 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15715 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15716 // We shift all of the values by one. In many cases we do not have
15717 // hardware support for this operation. This is better expressed as an ADD
15719 if (N1C && (1 == N1C->getZExtValue())) {
15720 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15727 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15729 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15730 TargetLowering::DAGCombinerInfo &DCI,
15731 const X86Subtarget *Subtarget) {
15732 EVT VT = N->getValueType(0);
15733 if (N->getOpcode() == ISD::SHL) {
15734 SDValue V = PerformSHLCombine(N, DAG);
15735 if (V.getNode()) return V;
15738 // On X86 with SSE2 support, we can transform this to a vector shift if
15739 // all elements are shifted by the same amount. We can't do this in legalize
15740 // because the a constant vector is typically transformed to a constant pool
15741 // so we have no knowledge of the shift amount.
15742 if (!Subtarget->hasSSE2())
15745 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15746 (!Subtarget->hasInt256() ||
15747 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15750 SDValue ShAmtOp = N->getOperand(1);
15751 EVT EltVT = VT.getVectorElementType();
15752 DebugLoc DL = N->getDebugLoc();
15753 SDValue BaseShAmt = SDValue();
15754 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15755 unsigned NumElts = VT.getVectorNumElements();
15757 for (; i != NumElts; ++i) {
15758 SDValue Arg = ShAmtOp.getOperand(i);
15759 if (Arg.getOpcode() == ISD::UNDEF) continue;
15763 // Handle the case where the build_vector is all undef
15764 // FIXME: Should DAG allow this?
15768 for (; i != NumElts; ++i) {
15769 SDValue Arg = ShAmtOp.getOperand(i);
15770 if (Arg.getOpcode() == ISD::UNDEF) continue;
15771 if (Arg != BaseShAmt) {
15775 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15776 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15777 SDValue InVec = ShAmtOp.getOperand(0);
15778 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15779 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15781 for (; i != NumElts; ++i) {
15782 SDValue Arg = InVec.getOperand(i);
15783 if (Arg.getOpcode() == ISD::UNDEF) continue;
15787 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15788 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15789 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15790 if (C->getZExtValue() == SplatIdx)
15791 BaseShAmt = InVec.getOperand(1);
15794 if (BaseShAmt.getNode() == 0) {
15795 // Don't create instructions with illegal types after legalize
15797 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15798 !DCI.isBeforeLegalize())
15801 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15802 DAG.getIntPtrConstant(0));
15807 // The shift amount is an i32.
15808 if (EltVT.bitsGT(MVT::i32))
15809 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15810 else if (EltVT.bitsLT(MVT::i32))
15811 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15813 // The shift amount is identical so we can do a vector shift.
15814 SDValue ValOp = N->getOperand(0);
15815 switch (N->getOpcode()) {
15817 llvm_unreachable("Unknown shift opcode!");
15819 switch (VT.getSimpleVT().SimpleTy) {
15820 default: return SDValue();
15827 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15830 switch (VT.getSimpleVT().SimpleTy) {
15831 default: return SDValue();
15836 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15839 switch (VT.getSimpleVT().SimpleTy) {
15840 default: return SDValue();
15847 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15852 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15853 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15854 // and friends. Likewise for OR -> CMPNEQSS.
15855 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15856 TargetLowering::DAGCombinerInfo &DCI,
15857 const X86Subtarget *Subtarget) {
15860 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15861 // we're requiring SSE2 for both.
15862 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15863 SDValue N0 = N->getOperand(0);
15864 SDValue N1 = N->getOperand(1);
15865 SDValue CMP0 = N0->getOperand(1);
15866 SDValue CMP1 = N1->getOperand(1);
15867 DebugLoc DL = N->getDebugLoc();
15869 // The SETCCs should both refer to the same CMP.
15870 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15873 SDValue CMP00 = CMP0->getOperand(0);
15874 SDValue CMP01 = CMP0->getOperand(1);
15875 EVT VT = CMP00.getValueType();
15877 if (VT == MVT::f32 || VT == MVT::f64) {
15878 bool ExpectingFlags = false;
15879 // Check for any users that want flags:
15880 for (SDNode::use_iterator UI = N->use_begin(),
15882 !ExpectingFlags && UI != UE; ++UI)
15883 switch (UI->getOpcode()) {
15888 ExpectingFlags = true;
15890 case ISD::CopyToReg:
15891 case ISD::SIGN_EXTEND:
15892 case ISD::ZERO_EXTEND:
15893 case ISD::ANY_EXTEND:
15897 if (!ExpectingFlags) {
15898 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15899 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15901 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15902 X86::CondCode tmp = cc0;
15907 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15908 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15909 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15910 X86ISD::NodeType NTOperator = is64BitFP ?
15911 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15912 // FIXME: need symbolic constants for these magic numbers.
15913 // See X86ATTInstPrinter.cpp:printSSECC().
15914 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15915 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15916 DAG.getConstant(x86cc, MVT::i8));
15917 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15919 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15920 DAG.getConstant(1, MVT::i32));
15921 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15922 return OneBitOfTruth;
15930 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15931 /// so it can be folded inside ANDNP.
15932 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15933 EVT VT = N->getValueType(0);
15935 // Match direct AllOnes for 128 and 256-bit vectors
15936 if (ISD::isBuildVectorAllOnes(N))
15939 // Look through a bit convert.
15940 if (N->getOpcode() == ISD::BITCAST)
15941 N = N->getOperand(0).getNode();
15943 // Sometimes the operand may come from a insert_subvector building a 256-bit
15945 if (VT.is256BitVector() &&
15946 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15947 SDValue V1 = N->getOperand(0);
15948 SDValue V2 = N->getOperand(1);
15950 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15951 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15952 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15953 ISD::isBuildVectorAllOnes(V2.getNode()))
15960 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15961 // register. In most cases we actually compare or select YMM-sized registers
15962 // and mixing the two types creates horrible code. This method optimizes
15963 // some of the transition sequences.
15964 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15965 TargetLowering::DAGCombinerInfo &DCI,
15966 const X86Subtarget *Subtarget) {
15967 EVT VT = N->getValueType(0);
15968 if (!VT.is256BitVector())
15971 assert((N->getOpcode() == ISD::ANY_EXTEND ||
15972 N->getOpcode() == ISD::ZERO_EXTEND ||
15973 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15975 SDValue Narrow = N->getOperand(0);
15976 EVT NarrowVT = Narrow->getValueType(0);
15977 if (!NarrowVT.is128BitVector())
15980 if (Narrow->getOpcode() != ISD::XOR &&
15981 Narrow->getOpcode() != ISD::AND &&
15982 Narrow->getOpcode() != ISD::OR)
15985 SDValue N0 = Narrow->getOperand(0);
15986 SDValue N1 = Narrow->getOperand(1);
15987 DebugLoc DL = Narrow->getDebugLoc();
15989 // The Left side has to be a trunc.
15990 if (N0.getOpcode() != ISD::TRUNCATE)
15993 // The type of the truncated inputs.
15994 EVT WideVT = N0->getOperand(0)->getValueType(0);
15998 // The right side has to be a 'trunc' or a constant vector.
15999 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16000 bool RHSConst = (isSplatVector(N1.getNode()) &&
16001 isa<ConstantSDNode>(N1->getOperand(0)));
16002 if (!RHSTrunc && !RHSConst)
16005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16007 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16010 // Set N0 and N1 to hold the inputs to the new wide operation.
16011 N0 = N0->getOperand(0);
16013 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16014 N1->getOperand(0));
16015 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16016 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16017 } else if (RHSTrunc) {
16018 N1 = N1->getOperand(0);
16021 // Generate the wide operation.
16022 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16023 unsigned Opcode = N->getOpcode();
16025 case ISD::ANY_EXTEND:
16027 case ISD::ZERO_EXTEND: {
16028 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16029 APInt Mask = APInt::getAllOnesValue(InBits);
16030 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16031 return DAG.getNode(ISD::AND, DL, VT,
16032 Op, DAG.getConstant(Mask, VT));
16034 case ISD::SIGN_EXTEND:
16035 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16036 Op, DAG.getValueType(NarrowVT));
16038 llvm_unreachable("Unexpected opcode");
16042 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16043 TargetLowering::DAGCombinerInfo &DCI,
16044 const X86Subtarget *Subtarget) {
16045 EVT VT = N->getValueType(0);
16046 if (DCI.isBeforeLegalizeOps())
16049 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16053 // Create BLSI, and BLSR instructions
16054 // BLSI is X & (-X)
16055 // BLSR is X & (X-1)
16056 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16057 SDValue N0 = N->getOperand(0);
16058 SDValue N1 = N->getOperand(1);
16059 DebugLoc DL = N->getDebugLoc();
16061 // Check LHS for neg
16062 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16063 isZero(N0.getOperand(0)))
16064 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16066 // Check RHS for neg
16067 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16068 isZero(N1.getOperand(0)))
16069 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16071 // Check LHS for X-1
16072 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16073 isAllOnes(N0.getOperand(1)))
16074 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16076 // Check RHS for X-1
16077 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16078 isAllOnes(N1.getOperand(1)))
16079 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16084 // Want to form ANDNP nodes:
16085 // 1) In the hopes of then easily combining them with OR and AND nodes
16086 // to form PBLEND/PSIGN.
16087 // 2) To match ANDN packed intrinsics
16088 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16091 SDValue N0 = N->getOperand(0);
16092 SDValue N1 = N->getOperand(1);
16093 DebugLoc DL = N->getDebugLoc();
16095 // Check LHS for vnot
16096 if (N0.getOpcode() == ISD::XOR &&
16097 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16098 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16099 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16101 // Check RHS for vnot
16102 if (N1.getOpcode() == ISD::XOR &&
16103 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16104 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16105 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16110 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16111 TargetLowering::DAGCombinerInfo &DCI,
16112 const X86Subtarget *Subtarget) {
16113 EVT VT = N->getValueType(0);
16114 if (DCI.isBeforeLegalizeOps())
16117 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16121 SDValue N0 = N->getOperand(0);
16122 SDValue N1 = N->getOperand(1);
16124 // look for psign/blend
16125 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16126 if (!Subtarget->hasSSSE3() ||
16127 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16130 // Canonicalize pandn to RHS
16131 if (N0.getOpcode() == X86ISD::ANDNP)
16133 // or (and (m, y), (pandn m, x))
16134 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16135 SDValue Mask = N1.getOperand(0);
16136 SDValue X = N1.getOperand(1);
16138 if (N0.getOperand(0) == Mask)
16139 Y = N0.getOperand(1);
16140 if (N0.getOperand(1) == Mask)
16141 Y = N0.getOperand(0);
16143 // Check to see if the mask appeared in both the AND and ANDNP and
16147 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16148 // Look through mask bitcast.
16149 if (Mask.getOpcode() == ISD::BITCAST)
16150 Mask = Mask.getOperand(0);
16151 if (X.getOpcode() == ISD::BITCAST)
16152 X = X.getOperand(0);
16153 if (Y.getOpcode() == ISD::BITCAST)
16154 Y = Y.getOperand(0);
16156 EVT MaskVT = Mask.getValueType();
16158 // Validate that the Mask operand is a vector sra node.
16159 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16160 // there is no psrai.b
16161 if (Mask.getOpcode() != X86ISD::VSRAI)
16164 // Check that the SRA is all signbits.
16165 SDValue SraC = Mask.getOperand(1);
16166 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16167 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16168 if ((SraAmt + 1) != EltBits)
16171 DebugLoc DL = N->getDebugLoc();
16173 // We are going to replace the AND, OR, NAND with either BLEND
16174 // or PSIGN, which only look at the MSB. The VSRAI instruction
16175 // does not affect the highest bit, so we can get rid of it.
16176 Mask = Mask.getOperand(0);
16178 // Now we know we at least have a plendvb with the mask val. See if
16179 // we can form a psignb/w/d.
16180 // psign = x.type == y.type == mask.type && y = sub(0, x);
16181 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16182 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16183 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16184 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16185 "Unsupported VT for PSIGN");
16186 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16187 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16189 // PBLENDVB only available on SSE 4.1
16190 if (!Subtarget->hasSSE41())
16193 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16195 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16196 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16197 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16198 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16199 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16203 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16206 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16207 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16209 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16211 if (!N0.hasOneUse() || !N1.hasOneUse())
16214 SDValue ShAmt0 = N0.getOperand(1);
16215 if (ShAmt0.getValueType() != MVT::i8)
16217 SDValue ShAmt1 = N1.getOperand(1);
16218 if (ShAmt1.getValueType() != MVT::i8)
16220 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16221 ShAmt0 = ShAmt0.getOperand(0);
16222 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16223 ShAmt1 = ShAmt1.getOperand(0);
16225 DebugLoc DL = N->getDebugLoc();
16226 unsigned Opc = X86ISD::SHLD;
16227 SDValue Op0 = N0.getOperand(0);
16228 SDValue Op1 = N1.getOperand(0);
16229 if (ShAmt0.getOpcode() == ISD::SUB) {
16230 Opc = X86ISD::SHRD;
16231 std::swap(Op0, Op1);
16232 std::swap(ShAmt0, ShAmt1);
16235 unsigned Bits = VT.getSizeInBits();
16236 if (ShAmt1.getOpcode() == ISD::SUB) {
16237 SDValue Sum = ShAmt1.getOperand(0);
16238 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16239 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16240 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16241 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16242 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16243 return DAG.getNode(Opc, DL, VT,
16245 DAG.getNode(ISD::TRUNCATE, DL,
16248 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16249 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16251 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16252 return DAG.getNode(Opc, DL, VT,
16253 N0.getOperand(0), N1.getOperand(0),
16254 DAG.getNode(ISD::TRUNCATE, DL,
16261 // Generate NEG and CMOV for integer abs.
16262 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16263 EVT VT = N->getValueType(0);
16265 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16266 // 8-bit integer abs to NEG and CMOV.
16267 if (VT.isInteger() && VT.getSizeInBits() == 8)
16270 SDValue N0 = N->getOperand(0);
16271 SDValue N1 = N->getOperand(1);
16272 DebugLoc DL = N->getDebugLoc();
16274 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16275 // and change it to SUB and CMOV.
16276 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16277 N0.getOpcode() == ISD::ADD &&
16278 N0.getOperand(1) == N1 &&
16279 N1.getOpcode() == ISD::SRA &&
16280 N1.getOperand(0) == N0.getOperand(0))
16281 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16282 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16283 // Generate SUB & CMOV.
16284 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16285 DAG.getConstant(0, VT), N0.getOperand(0));
16287 SDValue Ops[] = { N0.getOperand(0), Neg,
16288 DAG.getConstant(X86::COND_GE, MVT::i8),
16289 SDValue(Neg.getNode(), 1) };
16290 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16291 Ops, array_lengthof(Ops));
16296 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16297 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16298 TargetLowering::DAGCombinerInfo &DCI,
16299 const X86Subtarget *Subtarget) {
16300 EVT VT = N->getValueType(0);
16301 if (DCI.isBeforeLegalizeOps())
16304 if (Subtarget->hasCMov()) {
16305 SDValue RV = performIntegerAbsCombine(N, DAG);
16310 // Try forming BMI if it is available.
16311 if (!Subtarget->hasBMI())
16314 if (VT != MVT::i32 && VT != MVT::i64)
16317 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16319 // Create BLSMSK instructions by finding X ^ (X-1)
16320 SDValue N0 = N->getOperand(0);
16321 SDValue N1 = N->getOperand(1);
16322 DebugLoc DL = N->getDebugLoc();
16324 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16325 isAllOnes(N0.getOperand(1)))
16326 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16328 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16329 isAllOnes(N1.getOperand(1)))
16330 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16335 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16336 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16337 TargetLowering::DAGCombinerInfo &DCI,
16338 const X86Subtarget *Subtarget) {
16339 LoadSDNode *Ld = cast<LoadSDNode>(N);
16340 EVT RegVT = Ld->getValueType(0);
16341 EVT MemVT = Ld->getMemoryVT();
16342 DebugLoc dl = Ld->getDebugLoc();
16343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16344 unsigned RegSz = RegVT.getSizeInBits();
16346 ISD::LoadExtType Ext = Ld->getExtensionType();
16347 unsigned Alignment = Ld->getAlignment();
16348 bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16350 // On Sandybridge unaligned 256bit loads are inefficient.
16351 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16352 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16353 unsigned NumElems = RegVT.getVectorNumElements();
16357 SDValue Ptr = Ld->getBasePtr();
16358 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16360 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16362 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16363 Ld->getPointerInfo(), Ld->isVolatile(),
16364 Ld->isNonTemporal(), Ld->isInvariant(),
16366 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16367 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16368 Ld->getPointerInfo(), Ld->isVolatile(),
16369 Ld->isNonTemporal(), Ld->isInvariant(),
16370 std::max(Alignment/2U, 1U));
16371 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16373 Load2.getValue(1));
16375 SDValue NewVec = DAG.getUNDEF(RegVT);
16376 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16377 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16378 return DCI.CombineTo(N, NewVec, TF, true);
16381 // If this is a vector EXT Load then attempt to optimize it using a
16382 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16383 // expansion is still better than scalar code.
16384 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16385 // emit a shuffle and a arithmetic shift.
16386 // TODO: It is possible to support ZExt by zeroing the undef values
16387 // during the shuffle phase or after the shuffle.
16388 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16389 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16390 assert(MemVT != RegVT && "Cannot extend to the same type");
16391 assert(MemVT.isVector() && "Must load a vector from memory");
16393 unsigned NumElems = RegVT.getVectorNumElements();
16394 unsigned MemSz = MemVT.getSizeInBits();
16395 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16397 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16400 // All sizes must be a power of two.
16401 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16404 // Attempt to load the original value using scalar loads.
16405 // Find the largest scalar type that divides the total loaded size.
16406 MVT SclrLoadTy = MVT::i8;
16407 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16408 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16409 MVT Tp = (MVT::SimpleValueType)tp;
16410 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16415 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16416 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16418 SclrLoadTy = MVT::f64;
16420 // Calculate the number of scalar loads that we need to perform
16421 // in order to load our vector from memory.
16422 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16423 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16426 unsigned loadRegZize = RegSz;
16427 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16430 // Represent our vector as a sequence of elements which are the
16431 // largest scalar that we can load.
16432 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16433 loadRegZize/SclrLoadTy.getSizeInBits());
16435 // Represent the data using the same element type that is stored in
16436 // memory. In practice, we ''widen'' MemVT.
16438 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16439 loadRegZize/MemVT.getScalarType().getSizeInBits());
16441 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16442 "Invalid vector type");
16444 // We can't shuffle using an illegal type.
16445 if (!TLI.isTypeLegal(WideVecVT))
16448 SmallVector<SDValue, 8> Chains;
16449 SDValue Ptr = Ld->getBasePtr();
16450 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16451 TLI.getPointerTy());
16452 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16454 for (unsigned i = 0; i < NumLoads; ++i) {
16455 // Perform a single load.
16456 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16457 Ptr, Ld->getPointerInfo(),
16458 Ld->isVolatile(), Ld->isNonTemporal(),
16459 Ld->isInvariant(), Ld->getAlignment());
16460 Chains.push_back(ScalarLoad.getValue(1));
16461 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16462 // another round of DAGCombining.
16464 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16466 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16467 ScalarLoad, DAG.getIntPtrConstant(i));
16469 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16472 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16475 // Bitcast the loaded value to a vector of the original element type, in
16476 // the size of the target vector type.
16477 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16478 unsigned SizeRatio = RegSz/MemSz;
16480 if (Ext == ISD::SEXTLOAD) {
16481 // If we have SSE4.1 we can directly emit a VSEXT node.
16482 if (Subtarget->hasSSE41()) {
16483 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16484 return DCI.CombineTo(N, Sext, TF, true);
16487 // Otherwise we'll shuffle the small elements in the high bits of the
16488 // larger type and perform an arithmetic shift. If the shift is not legal
16489 // it's better to scalarize.
16490 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16493 // Redistribute the loaded elements into the different locations.
16494 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16495 for (unsigned i = 0; i != NumElems; ++i)
16496 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16498 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16499 DAG.getUNDEF(WideVecVT),
16502 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16504 // Build the arithmetic shift.
16505 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16506 MemVT.getVectorElementType().getSizeInBits();
16507 SmallVector<SDValue, 8> C(NumElems,
16508 DAG.getConstant(Amt, RegVT.getScalarType()));
16509 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16510 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16512 return DCI.CombineTo(N, Shuff, TF, true);
16515 // Redistribute the loaded elements into the different locations.
16516 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16517 for (unsigned i = 0; i != NumElems; ++i)
16518 ShuffleVec[i*SizeRatio] = i;
16520 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16521 DAG.getUNDEF(WideVecVT),
16524 // Bitcast to the requested type.
16525 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16526 // Replace the original load with the new sequence
16527 // and return the new chain.
16528 return DCI.CombineTo(N, Shuff, TF, true);
16534 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16535 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16536 const X86Subtarget *Subtarget) {
16537 StoreSDNode *St = cast<StoreSDNode>(N);
16538 EVT VT = St->getValue().getValueType();
16539 EVT StVT = St->getMemoryVT();
16540 DebugLoc dl = St->getDebugLoc();
16541 SDValue StoredVal = St->getOperand(1);
16542 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16543 unsigned Alignment = St->getAlignment();
16544 bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16546 // If we are saving a concatenation of two XMM registers, perform two stores.
16547 // On Sandy Bridge, 256-bit memory operations are executed by two
16548 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16549 // memory operation.
16550 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16551 StVT == VT && !IsAligned) {
16552 unsigned NumElems = VT.getVectorNumElements();
16556 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16557 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16559 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16560 SDValue Ptr0 = St->getBasePtr();
16561 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16563 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16564 St->getPointerInfo(), St->isVolatile(),
16565 St->isNonTemporal(), Alignment);
16566 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16567 St->getPointerInfo(), St->isVolatile(),
16568 St->isNonTemporal(),
16569 std::max(Alignment/2U, 1U));
16570 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16573 // Optimize trunc store (of multiple scalars) to shuffle and store.
16574 // First, pack all of the elements in one place. Next, store to memory
16575 // in fewer chunks.
16576 if (St->isTruncatingStore() && VT.isVector()) {
16577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16578 unsigned NumElems = VT.getVectorNumElements();
16579 assert(StVT != VT && "Cannot truncate to the same type");
16580 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16581 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16583 // From, To sizes and ElemCount must be pow of two
16584 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16585 // We are going to use the original vector elt for storing.
16586 // Accumulated smaller vector elements must be a multiple of the store size.
16587 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16589 unsigned SizeRatio = FromSz / ToSz;
16591 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16593 // Create a type on which we perform the shuffle
16594 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16595 StVT.getScalarType(), NumElems*SizeRatio);
16597 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16599 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16600 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16601 for (unsigned i = 0; i != NumElems; ++i)
16602 ShuffleVec[i] = i * SizeRatio;
16604 // Can't shuffle using an illegal type.
16605 if (!TLI.isTypeLegal(WideVecVT))
16608 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16609 DAG.getUNDEF(WideVecVT),
16611 // At this point all of the data is stored at the bottom of the
16612 // register. We now need to save it to mem.
16614 // Find the largest store unit
16615 MVT StoreType = MVT::i8;
16616 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16617 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16618 MVT Tp = (MVT::SimpleValueType)tp;
16619 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16623 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16624 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16625 (64 <= NumElems * ToSz))
16626 StoreType = MVT::f64;
16628 // Bitcast the original vector into a vector of store-size units
16629 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16630 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16631 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16632 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16633 SmallVector<SDValue, 8> Chains;
16634 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16635 TLI.getPointerTy());
16636 SDValue Ptr = St->getBasePtr();
16638 // Perform one or more big stores into memory.
16639 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16640 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16641 StoreType, ShuffWide,
16642 DAG.getIntPtrConstant(i));
16643 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16644 St->getPointerInfo(), St->isVolatile(),
16645 St->isNonTemporal(), St->getAlignment());
16646 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16647 Chains.push_back(Ch);
16650 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16654 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
16655 // the FP state in cases where an emms may be missing.
16656 // A preferable solution to the general problem is to figure out the right
16657 // places to insert EMMS. This qualifies as a quick hack.
16659 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16660 if (VT.getSizeInBits() != 64)
16663 const Function *F = DAG.getMachineFunction().getFunction();
16664 bool NoImplicitFloatOps = F->getAttributes().
16665 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16666 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16667 && Subtarget->hasSSE2();
16668 if ((VT.isVector() ||
16669 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16670 isa<LoadSDNode>(St->getValue()) &&
16671 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16672 St->getChain().hasOneUse() && !St->isVolatile()) {
16673 SDNode* LdVal = St->getValue().getNode();
16674 LoadSDNode *Ld = 0;
16675 int TokenFactorIndex = -1;
16676 SmallVector<SDValue, 8> Ops;
16677 SDNode* ChainVal = St->getChain().getNode();
16678 // Must be a store of a load. We currently handle two cases: the load
16679 // is a direct child, and it's under an intervening TokenFactor. It is
16680 // possible to dig deeper under nested TokenFactors.
16681 if (ChainVal == LdVal)
16682 Ld = cast<LoadSDNode>(St->getChain());
16683 else if (St->getValue().hasOneUse() &&
16684 ChainVal->getOpcode() == ISD::TokenFactor) {
16685 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16686 if (ChainVal->getOperand(i).getNode() == LdVal) {
16687 TokenFactorIndex = i;
16688 Ld = cast<LoadSDNode>(St->getValue());
16690 Ops.push_back(ChainVal->getOperand(i));
16694 if (!Ld || !ISD::isNormalLoad(Ld))
16697 // If this is not the MMX case, i.e. we are just turning i64 load/store
16698 // into f64 load/store, avoid the transformation if there are multiple
16699 // uses of the loaded value.
16700 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16703 DebugLoc LdDL = Ld->getDebugLoc();
16704 DebugLoc StDL = N->getDebugLoc();
16705 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16706 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16708 if (Subtarget->is64Bit() || F64IsLegal) {
16709 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16710 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16711 Ld->getPointerInfo(), Ld->isVolatile(),
16712 Ld->isNonTemporal(), Ld->isInvariant(),
16713 Ld->getAlignment());
16714 SDValue NewChain = NewLd.getValue(1);
16715 if (TokenFactorIndex != -1) {
16716 Ops.push_back(NewChain);
16717 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16720 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16721 St->getPointerInfo(),
16722 St->isVolatile(), St->isNonTemporal(),
16723 St->getAlignment());
16726 // Otherwise, lower to two pairs of 32-bit loads / stores.
16727 SDValue LoAddr = Ld->getBasePtr();
16728 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16729 DAG.getConstant(4, MVT::i32));
16731 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16732 Ld->getPointerInfo(),
16733 Ld->isVolatile(), Ld->isNonTemporal(),
16734 Ld->isInvariant(), Ld->getAlignment());
16735 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16736 Ld->getPointerInfo().getWithOffset(4),
16737 Ld->isVolatile(), Ld->isNonTemporal(),
16739 MinAlign(Ld->getAlignment(), 4));
16741 SDValue NewChain = LoLd.getValue(1);
16742 if (TokenFactorIndex != -1) {
16743 Ops.push_back(LoLd);
16744 Ops.push_back(HiLd);
16745 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16749 LoAddr = St->getBasePtr();
16750 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16751 DAG.getConstant(4, MVT::i32));
16753 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16754 St->getPointerInfo(),
16755 St->isVolatile(), St->isNonTemporal(),
16756 St->getAlignment());
16757 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16758 St->getPointerInfo().getWithOffset(4),
16760 St->isNonTemporal(),
16761 MinAlign(St->getAlignment(), 4));
16762 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16767 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16768 /// and return the operands for the horizontal operation in LHS and RHS. A
16769 /// horizontal operation performs the binary operation on successive elements
16770 /// of its first operand, then on successive elements of its second operand,
16771 /// returning the resulting values in a vector. For example, if
16772 /// A = < float a0, float a1, float a2, float a3 >
16774 /// B = < float b0, float b1, float b2, float b3 >
16775 /// then the result of doing a horizontal operation on A and B is
16776 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16777 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16778 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16779 /// set to A, RHS to B, and the routine returns 'true'.
16780 /// Note that the binary operation should have the property that if one of the
16781 /// operands is UNDEF then the result is UNDEF.
16782 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16783 // Look for the following pattern: if
16784 // A = < float a0, float a1, float a2, float a3 >
16785 // B = < float b0, float b1, float b2, float b3 >
16787 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16788 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16789 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16790 // which is A horizontal-op B.
16792 // At least one of the operands should be a vector shuffle.
16793 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16794 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16797 EVT VT = LHS.getValueType();
16799 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16800 "Unsupported vector type for horizontal add/sub");
16802 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16803 // operate independently on 128-bit lanes.
16804 unsigned NumElts = VT.getVectorNumElements();
16805 unsigned NumLanes = VT.getSizeInBits()/128;
16806 unsigned NumLaneElts = NumElts / NumLanes;
16807 assert((NumLaneElts % 2 == 0) &&
16808 "Vector type should have an even number of elements in each lane");
16809 unsigned HalfLaneElts = NumLaneElts/2;
16811 // View LHS in the form
16812 // LHS = VECTOR_SHUFFLE A, B, LMask
16813 // If LHS is not a shuffle then pretend it is the shuffle
16814 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16815 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16818 SmallVector<int, 16> LMask(NumElts);
16819 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16820 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16821 A = LHS.getOperand(0);
16822 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16823 B = LHS.getOperand(1);
16824 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16825 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16827 if (LHS.getOpcode() != ISD::UNDEF)
16829 for (unsigned i = 0; i != NumElts; ++i)
16833 // Likewise, view RHS in the form
16834 // RHS = VECTOR_SHUFFLE C, D, RMask
16836 SmallVector<int, 16> RMask(NumElts);
16837 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16838 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16839 C = RHS.getOperand(0);
16840 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16841 D = RHS.getOperand(1);
16842 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16843 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16845 if (RHS.getOpcode() != ISD::UNDEF)
16847 for (unsigned i = 0; i != NumElts; ++i)
16851 // Check that the shuffles are both shuffling the same vectors.
16852 if (!(A == C && B == D) && !(A == D && B == C))
16855 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16856 if (!A.getNode() && !B.getNode())
16859 // If A and B occur in reverse order in RHS, then "swap" them (which means
16860 // rewriting the mask).
16862 CommuteVectorShuffleMask(RMask, NumElts);
16864 // At this point LHS and RHS are equivalent to
16865 // LHS = VECTOR_SHUFFLE A, B, LMask
16866 // RHS = VECTOR_SHUFFLE A, B, RMask
16867 // Check that the masks correspond to performing a horizontal operation.
16868 for (unsigned i = 0; i != NumElts; ++i) {
16869 int LIdx = LMask[i], RIdx = RMask[i];
16871 // Ignore any UNDEF components.
16872 if (LIdx < 0 || RIdx < 0 ||
16873 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16874 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16877 // Check that successive elements are being operated on. If not, this is
16878 // not a horizontal operation.
16879 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16880 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16881 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16882 if (!(LIdx == Index && RIdx == Index + 1) &&
16883 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16887 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16888 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16892 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16893 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16894 const X86Subtarget *Subtarget) {
16895 EVT VT = N->getValueType(0);
16896 SDValue LHS = N->getOperand(0);
16897 SDValue RHS = N->getOperand(1);
16899 // Try to synthesize horizontal adds from adds of shuffles.
16900 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16901 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16902 isHorizontalBinOp(LHS, RHS, true))
16903 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16907 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16908 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16909 const X86Subtarget *Subtarget) {
16910 EVT VT = N->getValueType(0);
16911 SDValue LHS = N->getOperand(0);
16912 SDValue RHS = N->getOperand(1);
16914 // Try to synthesize horizontal subs from subs of shuffles.
16915 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16916 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16917 isHorizontalBinOp(LHS, RHS, false))
16918 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16922 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16923 /// X86ISD::FXOR nodes.
16924 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16925 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16926 // F[X]OR(0.0, x) -> x
16927 // F[X]OR(x, 0.0) -> x
16928 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16929 if (C->getValueAPF().isPosZero())
16930 return N->getOperand(1);
16931 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16932 if (C->getValueAPF().isPosZero())
16933 return N->getOperand(0);
16937 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16938 /// X86ISD::FMAX nodes.
16939 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16940 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16942 // Only perform optimizations if UnsafeMath is used.
16943 if (!DAG.getTarget().Options.UnsafeFPMath)
16946 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16947 // into FMINC and FMAXC, which are Commutative operations.
16948 unsigned NewOp = 0;
16949 switch (N->getOpcode()) {
16950 default: llvm_unreachable("unknown opcode");
16951 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16952 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16955 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16956 N->getOperand(0), N->getOperand(1));
16959 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16960 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16961 // FAND(0.0, x) -> 0.0
16962 // FAND(x, 0.0) -> 0.0
16963 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16964 if (C->getValueAPF().isPosZero())
16965 return N->getOperand(0);
16966 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16967 if (C->getValueAPF().isPosZero())
16968 return N->getOperand(1);
16972 static SDValue PerformBTCombine(SDNode *N,
16974 TargetLowering::DAGCombinerInfo &DCI) {
16975 // BT ignores high bits in the bit index operand.
16976 SDValue Op1 = N->getOperand(1);
16977 if (Op1.hasOneUse()) {
16978 unsigned BitWidth = Op1.getValueSizeInBits();
16979 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16980 APInt KnownZero, KnownOne;
16981 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16982 !DCI.isBeforeLegalizeOps());
16983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16984 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16985 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16986 DCI.CommitTargetLoweringOpt(TLO);
16991 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16992 SDValue Op = N->getOperand(0);
16993 if (Op.getOpcode() == ISD::BITCAST)
16994 Op = Op.getOperand(0);
16995 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16996 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16997 VT.getVectorElementType().getSizeInBits() ==
16998 OpVT.getVectorElementType().getSizeInBits()) {
16999 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17004 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17005 TargetLowering::DAGCombinerInfo &DCI,
17006 const X86Subtarget *Subtarget) {
17007 if (!DCI.isBeforeLegalizeOps())
17010 if (!Subtarget->hasFp256())
17013 EVT VT = N->getValueType(0);
17014 if (VT.isVector() && VT.getSizeInBits() == 256) {
17015 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17023 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17024 const X86Subtarget* Subtarget) {
17025 DebugLoc dl = N->getDebugLoc();
17026 EVT VT = N->getValueType(0);
17028 // Let legalize expand this if it isn't a legal type yet.
17029 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17032 EVT ScalarVT = VT.getScalarType();
17033 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17034 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17037 SDValue A = N->getOperand(0);
17038 SDValue B = N->getOperand(1);
17039 SDValue C = N->getOperand(2);
17041 bool NegA = (A.getOpcode() == ISD::FNEG);
17042 bool NegB = (B.getOpcode() == ISD::FNEG);
17043 bool NegC = (C.getOpcode() == ISD::FNEG);
17045 // Negative multiplication when NegA xor NegB
17046 bool NegMul = (NegA != NegB);
17048 A = A.getOperand(0);
17050 B = B.getOperand(0);
17052 C = C.getOperand(0);
17056 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17058 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17060 return DAG.getNode(Opcode, dl, VT, A, B, C);
17063 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17064 TargetLowering::DAGCombinerInfo &DCI,
17065 const X86Subtarget *Subtarget) {
17066 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17067 // (and (i32 x86isd::setcc_carry), 1)
17068 // This eliminates the zext. This transformation is necessary because
17069 // ISD::SETCC is always legalized to i8.
17070 DebugLoc dl = N->getDebugLoc();
17071 SDValue N0 = N->getOperand(0);
17072 EVT VT = N->getValueType(0);
17074 if (N0.getOpcode() == ISD::AND &&
17076 N0.getOperand(0).hasOneUse()) {
17077 SDValue N00 = N0.getOperand(0);
17078 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17079 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17080 if (!C || C->getZExtValue() != 1)
17082 return DAG.getNode(ISD::AND, dl, VT,
17083 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17084 N00.getOperand(0), N00.getOperand(1)),
17085 DAG.getConstant(1, VT));
17089 if (VT.is256BitVector()) {
17090 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17098 // Optimize x == -y --> x+y == 0
17099 // x != -y --> x+y != 0
17100 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17101 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17102 SDValue LHS = N->getOperand(0);
17103 SDValue RHS = N->getOperand(1);
17105 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17106 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17107 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17108 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17109 LHS.getValueType(), RHS, LHS.getOperand(1));
17110 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17111 addV, DAG.getConstant(0, addV.getValueType()), CC);
17113 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17114 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17115 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17116 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17117 RHS.getValueType(), LHS, RHS.getOperand(1));
17118 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17119 addV, DAG.getConstant(0, addV.getValueType()), CC);
17124 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17125 // as "sbb reg,reg", since it can be extended without zext and produces
17126 // an all-ones bit which is more useful than 0/1 in some cases.
17127 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17128 return DAG.getNode(ISD::AND, DL, MVT::i8,
17129 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17130 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17131 DAG.getConstant(1, MVT::i8));
17134 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17135 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17136 TargetLowering::DAGCombinerInfo &DCI,
17137 const X86Subtarget *Subtarget) {
17138 DebugLoc DL = N->getDebugLoc();
17139 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17140 SDValue EFLAGS = N->getOperand(1);
17142 if (CC == X86::COND_A) {
17143 // Try to convert COND_A into COND_B in an attempt to facilitate
17144 // materializing "setb reg".
17146 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17147 // cannot take an immediate as its first operand.
17149 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17150 EFLAGS.getValueType().isInteger() &&
17151 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17152 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17153 EFLAGS.getNode()->getVTList(),
17154 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17155 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17156 return MaterializeSETB(DL, NewEFLAGS, DAG);
17160 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17161 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17163 if (CC == X86::COND_B)
17164 return MaterializeSETB(DL, EFLAGS, DAG);
17168 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17169 if (Flags.getNode()) {
17170 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17171 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17177 // Optimize branch condition evaluation.
17179 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17180 TargetLowering::DAGCombinerInfo &DCI,
17181 const X86Subtarget *Subtarget) {
17182 DebugLoc DL = N->getDebugLoc();
17183 SDValue Chain = N->getOperand(0);
17184 SDValue Dest = N->getOperand(1);
17185 SDValue EFLAGS = N->getOperand(3);
17186 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17190 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17191 if (Flags.getNode()) {
17192 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17193 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17200 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17201 const X86TargetLowering *XTLI) {
17202 SDValue Op0 = N->getOperand(0);
17203 EVT InVT = Op0->getValueType(0);
17205 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17206 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17207 DebugLoc dl = N->getDebugLoc();
17208 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17209 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17210 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17213 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17214 // a 32-bit target where SSE doesn't support i64->FP operations.
17215 if (Op0.getOpcode() == ISD::LOAD) {
17216 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17217 EVT VT = Ld->getValueType(0);
17218 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17219 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17220 !XTLI->getSubtarget()->is64Bit() &&
17221 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17222 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17223 Ld->getChain(), Op0, DAG);
17224 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17231 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17232 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17233 X86TargetLowering::DAGCombinerInfo &DCI) {
17234 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17235 // the result is either zero or one (depending on the input carry bit).
17236 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17237 if (X86::isZeroNode(N->getOperand(0)) &&
17238 X86::isZeroNode(N->getOperand(1)) &&
17239 // We don't have a good way to replace an EFLAGS use, so only do this when
17241 SDValue(N, 1).use_empty()) {
17242 DebugLoc DL = N->getDebugLoc();
17243 EVT VT = N->getValueType(0);
17244 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17245 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17246 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17247 DAG.getConstant(X86::COND_B,MVT::i8),
17249 DAG.getConstant(1, VT));
17250 return DCI.CombineTo(N, Res1, CarryOut);
17256 // fold (add Y, (sete X, 0)) -> adc 0, Y
17257 // (add Y, (setne X, 0)) -> sbb -1, Y
17258 // (sub (sete X, 0), Y) -> sbb 0, Y
17259 // (sub (setne X, 0), Y) -> adc -1, Y
17260 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17261 DebugLoc DL = N->getDebugLoc();
17263 // Look through ZExts.
17264 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17265 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17268 SDValue SetCC = Ext.getOperand(0);
17269 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17272 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17273 if (CC != X86::COND_E && CC != X86::COND_NE)
17276 SDValue Cmp = SetCC.getOperand(1);
17277 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17278 !X86::isZeroNode(Cmp.getOperand(1)) ||
17279 !Cmp.getOperand(0).getValueType().isInteger())
17282 SDValue CmpOp0 = Cmp.getOperand(0);
17283 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17284 DAG.getConstant(1, CmpOp0.getValueType()));
17286 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17287 if (CC == X86::COND_NE)
17288 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17289 DL, OtherVal.getValueType(), OtherVal,
17290 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17291 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17292 DL, OtherVal.getValueType(), OtherVal,
17293 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17296 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17297 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17298 const X86Subtarget *Subtarget) {
17299 EVT VT = N->getValueType(0);
17300 SDValue Op0 = N->getOperand(0);
17301 SDValue Op1 = N->getOperand(1);
17303 // Try to synthesize horizontal adds from adds of shuffles.
17304 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17305 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17306 isHorizontalBinOp(Op0, Op1, true))
17307 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17309 return OptimizeConditionalInDecrement(N, DAG);
17312 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17313 const X86Subtarget *Subtarget) {
17314 SDValue Op0 = N->getOperand(0);
17315 SDValue Op1 = N->getOperand(1);
17317 // X86 can't encode an immediate LHS of a sub. See if we can push the
17318 // negation into a preceding instruction.
17319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17320 // If the RHS of the sub is a XOR with one use and a constant, invert the
17321 // immediate. Then add one to the LHS of the sub so we can turn
17322 // X-Y -> X+~Y+1, saving one register.
17323 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17324 isa<ConstantSDNode>(Op1.getOperand(1))) {
17325 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17326 EVT VT = Op0.getValueType();
17327 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17329 DAG.getConstant(~XorC, VT));
17330 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17331 DAG.getConstant(C->getAPIntValue()+1, VT));
17335 // Try to synthesize horizontal adds from adds of shuffles.
17336 EVT VT = N->getValueType(0);
17337 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17338 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17339 isHorizontalBinOp(Op0, Op1, true))
17340 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17342 return OptimizeConditionalInDecrement(N, DAG);
17345 /// performVZEXTCombine - Performs build vector combines
17346 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17347 TargetLowering::DAGCombinerInfo &DCI,
17348 const X86Subtarget *Subtarget) {
17349 // (vzext (bitcast (vzext (x)) -> (vzext x)
17350 SDValue In = N->getOperand(0);
17351 while (In.getOpcode() == ISD::BITCAST)
17352 In = In.getOperand(0);
17354 if (In.getOpcode() != X86ISD::VZEXT)
17357 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17360 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17361 DAGCombinerInfo &DCI) const {
17362 SelectionDAG &DAG = DCI.DAG;
17363 switch (N->getOpcode()) {
17365 case ISD::EXTRACT_VECTOR_ELT:
17366 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17368 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17369 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17370 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17371 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17372 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17373 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17376 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17377 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17378 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17379 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17380 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17381 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17382 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17383 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17384 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17386 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17388 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17389 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17390 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17391 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17392 case ISD::ANY_EXTEND:
17393 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17394 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17395 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17396 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17397 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17398 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17399 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17400 case X86ISD::SHUFP: // Handle all target specific shuffles
17401 case X86ISD::PALIGN:
17402 case X86ISD::UNPCKH:
17403 case X86ISD::UNPCKL:
17404 case X86ISD::MOVHLPS:
17405 case X86ISD::MOVLHPS:
17406 case X86ISD::PSHUFD:
17407 case X86ISD::PSHUFHW:
17408 case X86ISD::PSHUFLW:
17409 case X86ISD::MOVSS:
17410 case X86ISD::MOVSD:
17411 case X86ISD::VPERMILP:
17412 case X86ISD::VPERM2X128:
17413 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17414 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17420 /// isTypeDesirableForOp - Return true if the target has native support for
17421 /// the specified value type and it is 'desirable' to use the type for the
17422 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17423 /// instruction encodings are longer and some i16 instructions are slow.
17424 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17425 if (!isTypeLegal(VT))
17427 if (VT != MVT::i16)
17434 case ISD::SIGN_EXTEND:
17435 case ISD::ZERO_EXTEND:
17436 case ISD::ANY_EXTEND:
17449 /// IsDesirableToPromoteOp - This method query the target whether it is
17450 /// beneficial for dag combiner to promote the specified node. If true, it
17451 /// should return the desired promotion type by reference.
17452 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17453 EVT VT = Op.getValueType();
17454 if (VT != MVT::i16)
17457 bool Promote = false;
17458 bool Commute = false;
17459 switch (Op.getOpcode()) {
17462 LoadSDNode *LD = cast<LoadSDNode>(Op);
17463 // If the non-extending load has a single use and it's not live out, then it
17464 // might be folded.
17465 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17466 Op.hasOneUse()*/) {
17467 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17468 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17469 // The only case where we'd want to promote LOAD (rather then it being
17470 // promoted as an operand is when it's only use is liveout.
17471 if (UI->getOpcode() != ISD::CopyToReg)
17478 case ISD::SIGN_EXTEND:
17479 case ISD::ZERO_EXTEND:
17480 case ISD::ANY_EXTEND:
17485 SDValue N0 = Op.getOperand(0);
17486 // Look out for (store (shl (load), x)).
17487 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17500 SDValue N0 = Op.getOperand(0);
17501 SDValue N1 = Op.getOperand(1);
17502 if (!Commute && MayFoldLoad(N1))
17504 // Avoid disabling potential load folding opportunities.
17505 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17507 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17517 //===----------------------------------------------------------------------===//
17518 // X86 Inline Assembly Support
17519 //===----------------------------------------------------------------------===//
17522 // Helper to match a string separated by whitespace.
17523 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17524 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17526 for (unsigned i = 0, e = args.size(); i != e; ++i) {
17527 StringRef piece(*args[i]);
17528 if (!s.startswith(piece)) // Check if the piece matches.
17531 s = s.substr(piece.size());
17532 StringRef::size_type pos = s.find_first_not_of(" \t");
17533 if (pos == 0) // We matched a prefix.
17541 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17544 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17545 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17547 std::string AsmStr = IA->getAsmString();
17549 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17550 if (!Ty || Ty->getBitWidth() % 16 != 0)
17553 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17554 SmallVector<StringRef, 4> AsmPieces;
17555 SplitString(AsmStr, AsmPieces, ";\n");
17557 switch (AsmPieces.size()) {
17558 default: return false;
17560 // FIXME: this should verify that we are targeting a 486 or better. If not,
17561 // we will turn this bswap into something that will be lowered to logical
17562 // ops instead of emitting the bswap asm. For now, we don't support 486 or
17563 // lower so don't worry about this.
17565 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17566 matchAsm(AsmPieces[0], "bswapl", "$0") ||
17567 matchAsm(AsmPieces[0], "bswapq", "$0") ||
17568 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17569 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17570 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17571 // No need to check constraints, nothing other than the equivalent of
17572 // "=r,0" would be valid here.
17573 return IntrinsicLowering::LowerToByteSwap(CI);
17576 // rorw $$8, ${0:w} --> llvm.bswap.i16
17577 if (CI->getType()->isIntegerTy(16) &&
17578 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17579 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17580 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17582 const std::string &ConstraintsStr = IA->getConstraintString();
17583 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17584 std::sort(AsmPieces.begin(), AsmPieces.end());
17585 if (AsmPieces.size() == 4 &&
17586 AsmPieces[0] == "~{cc}" &&
17587 AsmPieces[1] == "~{dirflag}" &&
17588 AsmPieces[2] == "~{flags}" &&
17589 AsmPieces[3] == "~{fpsr}")
17590 return IntrinsicLowering::LowerToByteSwap(CI);
17594 if (CI->getType()->isIntegerTy(32) &&
17595 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17596 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17597 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17598 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17600 const std::string &ConstraintsStr = IA->getConstraintString();
17601 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17602 std::sort(AsmPieces.begin(), AsmPieces.end());
17603 if (AsmPieces.size() == 4 &&
17604 AsmPieces[0] == "~{cc}" &&
17605 AsmPieces[1] == "~{dirflag}" &&
17606 AsmPieces[2] == "~{flags}" &&
17607 AsmPieces[3] == "~{fpsr}")
17608 return IntrinsicLowering::LowerToByteSwap(CI);
17611 if (CI->getType()->isIntegerTy(64)) {
17612 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17613 if (Constraints.size() >= 2 &&
17614 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17615 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17616 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
17617 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17618 matchAsm(AsmPieces[1], "bswap", "%edx") &&
17619 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17620 return IntrinsicLowering::LowerToByteSwap(CI);
17628 /// getConstraintType - Given a constraint letter, return the type of
17629 /// constraint it is for this target.
17630 X86TargetLowering::ConstraintType
17631 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17632 if (Constraint.size() == 1) {
17633 switch (Constraint[0]) {
17644 return C_RegisterClass;
17668 return TargetLowering::getConstraintType(Constraint);
17671 /// Examine constraint type and operand type and determine a weight value.
17672 /// This object must already have been set up with the operand type
17673 /// and the current alternative constraint selected.
17674 TargetLowering::ConstraintWeight
17675 X86TargetLowering::getSingleConstraintMatchWeight(
17676 AsmOperandInfo &info, const char *constraint) const {
17677 ConstraintWeight weight = CW_Invalid;
17678 Value *CallOperandVal = info.CallOperandVal;
17679 // If we don't have a value, we can't do a match,
17680 // but allow it at the lowest weight.
17681 if (CallOperandVal == NULL)
17683 Type *type = CallOperandVal->getType();
17684 // Look at the constraint type.
17685 switch (*constraint) {
17687 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17698 if (CallOperandVal->getType()->isIntegerTy())
17699 weight = CW_SpecificReg;
17704 if (type->isFloatingPointTy())
17705 weight = CW_SpecificReg;
17708 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17709 weight = CW_SpecificReg;
17713 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17714 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17715 weight = CW_Register;
17718 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17719 if (C->getZExtValue() <= 31)
17720 weight = CW_Constant;
17724 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17725 if (C->getZExtValue() <= 63)
17726 weight = CW_Constant;
17730 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17731 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17732 weight = CW_Constant;
17736 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17737 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17738 weight = CW_Constant;
17742 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17743 if (C->getZExtValue() <= 3)
17744 weight = CW_Constant;
17748 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17749 if (C->getZExtValue() <= 0xff)
17750 weight = CW_Constant;
17755 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17756 weight = CW_Constant;
17760 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17761 if ((C->getSExtValue() >= -0x80000000LL) &&
17762 (C->getSExtValue() <= 0x7fffffffLL))
17763 weight = CW_Constant;
17767 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17768 if (C->getZExtValue() <= 0xffffffff)
17769 weight = CW_Constant;
17776 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17777 /// with another that has more specific requirements based on the type of the
17778 /// corresponding operand.
17779 const char *X86TargetLowering::
17780 LowerXConstraint(EVT ConstraintVT) const {
17781 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17782 // 'f' like normal targets.
17783 if (ConstraintVT.isFloatingPoint()) {
17784 if (Subtarget->hasSSE2())
17786 if (Subtarget->hasSSE1())
17790 return TargetLowering::LowerXConstraint(ConstraintVT);
17793 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17794 /// vector. If it is invalid, don't add anything to Ops.
17795 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17796 std::string &Constraint,
17797 std::vector<SDValue>&Ops,
17798 SelectionDAG &DAG) const {
17799 SDValue Result(0, 0);
17801 // Only support length 1 constraints for now.
17802 if (Constraint.length() > 1) return;
17804 char ConstraintLetter = Constraint[0];
17805 switch (ConstraintLetter) {
17808 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17809 if (C->getZExtValue() <= 31) {
17810 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17816 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17817 if (C->getZExtValue() <= 63) {
17818 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17824 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17825 if (isInt<8>(C->getSExtValue())) {
17826 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17832 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17833 if (C->getZExtValue() <= 255) {
17834 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17840 // 32-bit signed value
17841 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17842 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17843 C->getSExtValue())) {
17844 // Widen to 64 bits here to get it sign extended.
17845 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17848 // FIXME gcc accepts some relocatable values here too, but only in certain
17849 // memory models; it's complicated.
17854 // 32-bit unsigned value
17855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17856 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17857 C->getZExtValue())) {
17858 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17862 // FIXME gcc accepts some relocatable values here too, but only in certain
17863 // memory models; it's complicated.
17867 // Literal immediates are always ok.
17868 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17869 // Widen to 64 bits here to get it sign extended.
17870 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17874 // In any sort of PIC mode addresses need to be computed at runtime by
17875 // adding in a register or some sort of table lookup. These can't
17876 // be used as immediates.
17877 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17880 // If we are in non-pic codegen mode, we allow the address of a global (with
17881 // an optional displacement) to be used with 'i'.
17882 GlobalAddressSDNode *GA = 0;
17883 int64_t Offset = 0;
17885 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17887 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17888 Offset += GA->getOffset();
17890 } else if (Op.getOpcode() == ISD::ADD) {
17891 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17892 Offset += C->getZExtValue();
17893 Op = Op.getOperand(0);
17896 } else if (Op.getOpcode() == ISD::SUB) {
17897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17898 Offset += -C->getZExtValue();
17899 Op = Op.getOperand(0);
17904 // Otherwise, this isn't something we can handle, reject it.
17908 const GlobalValue *GV = GA->getGlobal();
17909 // If we require an extra load to get this address, as in PIC mode, we
17910 // can't accept it.
17911 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17912 getTargetMachine())))
17915 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17916 GA->getValueType(0), Offset);
17921 if (Result.getNode()) {
17922 Ops.push_back(Result);
17925 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17928 std::pair<unsigned, const TargetRegisterClass*>
17929 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17931 // First, see if this is a constraint that directly corresponds to an LLVM
17933 if (Constraint.size() == 1) {
17934 // GCC Constraint Letters
17935 switch (Constraint[0]) {
17937 // TODO: Slight differences here in allocation order and leaving
17938 // RIP in the class. Do they matter any more here than they do
17939 // in the normal allocation?
17940 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17941 if (Subtarget->is64Bit()) {
17942 if (VT == MVT::i32 || VT == MVT::f32)
17943 return std::make_pair(0U, &X86::GR32RegClass);
17944 if (VT == MVT::i16)
17945 return std::make_pair(0U, &X86::GR16RegClass);
17946 if (VT == MVT::i8 || VT == MVT::i1)
17947 return std::make_pair(0U, &X86::GR8RegClass);
17948 if (VT == MVT::i64 || VT == MVT::f64)
17949 return std::make_pair(0U, &X86::GR64RegClass);
17952 // 32-bit fallthrough
17953 case 'Q': // Q_REGS
17954 if (VT == MVT::i32 || VT == MVT::f32)
17955 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17956 if (VT == MVT::i16)
17957 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17958 if (VT == MVT::i8 || VT == MVT::i1)
17959 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17960 if (VT == MVT::i64)
17961 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17963 case 'r': // GENERAL_REGS
17964 case 'l': // INDEX_REGS
17965 if (VT == MVT::i8 || VT == MVT::i1)
17966 return std::make_pair(0U, &X86::GR8RegClass);
17967 if (VT == MVT::i16)
17968 return std::make_pair(0U, &X86::GR16RegClass);
17969 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17970 return std::make_pair(0U, &X86::GR32RegClass);
17971 return std::make_pair(0U, &X86::GR64RegClass);
17972 case 'R': // LEGACY_REGS
17973 if (VT == MVT::i8 || VT == MVT::i1)
17974 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17975 if (VT == MVT::i16)
17976 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17977 if (VT == MVT::i32 || !Subtarget->is64Bit())
17978 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17979 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17980 case 'f': // FP Stack registers.
17981 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17982 // value to the correct fpstack register class.
17983 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17984 return std::make_pair(0U, &X86::RFP32RegClass);
17985 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17986 return std::make_pair(0U, &X86::RFP64RegClass);
17987 return std::make_pair(0U, &X86::RFP80RegClass);
17988 case 'y': // MMX_REGS if MMX allowed.
17989 if (!Subtarget->hasMMX()) break;
17990 return std::make_pair(0U, &X86::VR64RegClass);
17991 case 'Y': // SSE_REGS if SSE2 allowed
17992 if (!Subtarget->hasSSE2()) break;
17994 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17995 if (!Subtarget->hasSSE1()) break;
17997 switch (VT.getSimpleVT().SimpleTy) {
17999 // Scalar SSE types.
18002 return std::make_pair(0U, &X86::FR32RegClass);
18005 return std::make_pair(0U, &X86::FR64RegClass);
18013 return std::make_pair(0U, &X86::VR128RegClass);
18021 return std::make_pair(0U, &X86::VR256RegClass);
18027 // Use the default implementation in TargetLowering to convert the register
18028 // constraint into a member of a register class.
18029 std::pair<unsigned, const TargetRegisterClass*> Res;
18030 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18032 // Not found as a standard register?
18033 if (Res.second == 0) {
18034 // Map st(0) -> st(7) -> ST0
18035 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18036 tolower(Constraint[1]) == 's' &&
18037 tolower(Constraint[2]) == 't' &&
18038 Constraint[3] == '(' &&
18039 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18040 Constraint[5] == ')' &&
18041 Constraint[6] == '}') {
18043 Res.first = X86::ST0+Constraint[4]-'0';
18044 Res.second = &X86::RFP80RegClass;
18048 // GCC allows "st(0)" to be called just plain "st".
18049 if (StringRef("{st}").equals_lower(Constraint)) {
18050 Res.first = X86::ST0;
18051 Res.second = &X86::RFP80RegClass;
18056 if (StringRef("{flags}").equals_lower(Constraint)) {
18057 Res.first = X86::EFLAGS;
18058 Res.second = &X86::CCRRegClass;
18062 // 'A' means EAX + EDX.
18063 if (Constraint == "A") {
18064 Res.first = X86::EAX;
18065 Res.second = &X86::GR32_ADRegClass;
18071 // Otherwise, check to see if this is a register class of the wrong value
18072 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18073 // turn into {ax},{dx}.
18074 if (Res.second->hasType(VT))
18075 return Res; // Correct type already, nothing to do.
18077 // All of the single-register GCC register classes map their values onto
18078 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18079 // really want an 8-bit or 32-bit register, map to the appropriate register
18080 // class and return the appropriate register.
18081 if (Res.second == &X86::GR16RegClass) {
18082 if (VT == MVT::i8) {
18083 unsigned DestReg = 0;
18084 switch (Res.first) {
18086 case X86::AX: DestReg = X86::AL; break;
18087 case X86::DX: DestReg = X86::DL; break;
18088 case X86::CX: DestReg = X86::CL; break;
18089 case X86::BX: DestReg = X86::BL; break;
18092 Res.first = DestReg;
18093 Res.second = &X86::GR8RegClass;
18095 } else if (VT == MVT::i32) {
18096 unsigned DestReg = 0;
18097 switch (Res.first) {
18099 case X86::AX: DestReg = X86::EAX; break;
18100 case X86::DX: DestReg = X86::EDX; break;
18101 case X86::CX: DestReg = X86::ECX; break;
18102 case X86::BX: DestReg = X86::EBX; break;
18103 case X86::SI: DestReg = X86::ESI; break;
18104 case X86::DI: DestReg = X86::EDI; break;
18105 case X86::BP: DestReg = X86::EBP; break;
18106 case X86::SP: DestReg = X86::ESP; break;
18109 Res.first = DestReg;
18110 Res.second = &X86::GR32RegClass;
18112 } else if (VT == MVT::i64) {
18113 unsigned DestReg = 0;
18114 switch (Res.first) {
18116 case X86::AX: DestReg = X86::RAX; break;
18117 case X86::DX: DestReg = X86::RDX; break;
18118 case X86::CX: DestReg = X86::RCX; break;
18119 case X86::BX: DestReg = X86::RBX; break;
18120 case X86::SI: DestReg = X86::RSI; break;
18121 case X86::DI: DestReg = X86::RDI; break;
18122 case X86::BP: DestReg = X86::RBP; break;
18123 case X86::SP: DestReg = X86::RSP; break;
18126 Res.first = DestReg;
18127 Res.second = &X86::GR64RegClass;
18130 } else if (Res.second == &X86::FR32RegClass ||
18131 Res.second == &X86::FR64RegClass ||
18132 Res.second == &X86::VR128RegClass) {
18133 // Handle references to XMM physical registers that got mapped into the
18134 // wrong class. This can happen with constraints like {xmm0} where the
18135 // target independent register mapper will just pick the first match it can
18136 // find, ignoring the required type.
18138 if (VT == MVT::f32 || VT == MVT::i32)
18139 Res.second = &X86::FR32RegClass;
18140 else if (VT == MVT::f64 || VT == MVT::i64)
18141 Res.second = &X86::FR64RegClass;
18142 else if (X86::VR128RegClass.hasType(VT))
18143 Res.second = &X86::VR128RegClass;
18144 else if (X86::VR256RegClass.hasType(VT))
18145 Res.second = &X86::VR256RegClass;