Remove intrinsics for X86 BLSI, BLSMSK, and BLSR intrinsics and replace with custom...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static SDValue Insert128BitVector(SDValue Result,
65                                   SDValue Vec,
66                                   SDValue Idx,
67                                   SelectionDAG &DAG,
68                                   DebugLoc dl);
69
70 static SDValue Extract128BitVector(SDValue Vec,
71                                    SDValue Idx,
72                                    SelectionDAG &DAG,
73                                    DebugLoc dl);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.  Idx is an index in the 128 bits we
78 /// want.  It need not be aligned to a 128-bit bounday.  That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
81                                    SDValue Idx,
82                                    SelectionDAG &DAG,
83                                    DebugLoc dl) {
84   EVT VT = Vec.getValueType();
85   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86   EVT ElVT = VT.getVectorElementType();
87   int Factor = VT.getSizeInBits()/128;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95   if (isa<ConstantSDNode>(Idx)) {
96     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99     // we can match to VEXTRACTF128.
100     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102     // This is the index of the first element of the 128-bit chunk
103     // we want.
104     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                  * ElemsPerChunk);
106
107     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                  VecIdx);
110
111     return Result;
112   }
113
114   return SDValue();
115 }
116
117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference.  Idx is an index in the 128 bits
120 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
123                                   SDValue Vec,
124                                   SDValue Idx,
125                                   SelectionDAG &DAG,
126                                   DebugLoc dl) {
127   if (isa<ConstantSDNode>(Idx)) {
128     EVT VT = Vec.getValueType();
129     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131     EVT ElVT = VT.getVectorElementType();
132     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133     EVT ResultVT = Result.getValueType();
134
135     // Insert the relevant 128 bits.
136     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138     // This is the index of the first element of the 128-bit chunk
139     // we want.
140     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                  * ElemsPerChunk);
142
143     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                          VecIdx);
146     return Result;
147   }
148
149   return SDValue();
150 }
151
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154   bool is64Bit = Subtarget->is64Bit();
155
156   if (Subtarget->isTargetEnvMacho()) {
157     if (is64Bit)
158       return new X8664_MachoTargetObjectFile();
159     return new TargetLoweringObjectFileMachO();
160   }
161
162   if (Subtarget->isTargetELF())
163     return new TargetLoweringObjectFileELF();
164   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165     return new TargetLoweringObjectFileCOFF();
166   llvm_unreachable("unknown subtarget type");
167 }
168
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170   : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<X86Subtarget>();
172   X86ScalarSSEf64 = Subtarget->hasXMMInt();
173   X86ScalarSSEf32 = Subtarget->hasXMM();
174   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176   RegInfo = TM.getRegisterInfo();
177   TD = getTargetData();
178
179   // Set up the TargetLowering object.
180   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182   // X86 is weird, it always uses i8 for shift amounts and setcc results.
183   setBooleanContents(ZeroOrOneBooleanContent);
184   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187   // For 64-bit since we have so many registers use the ILP scheduler, for
188   // 32-bit code use the register pressure specific scheduling.
189   if (Subtarget->is64Bit())
190     setSchedulingPreference(Sched::ILP);
191   else
192     setSchedulingPreference(Sched::RegPressure);
193   setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196     // Setup Windows compiler runtime calls.
197     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199     setLibcallName(RTLIB::SREM_I64, "_allrem");
200     setLibcallName(RTLIB::UREM_I64, "_aullrem");
201     setLibcallName(RTLIB::MUL_I64, "_allmul");
202     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211   }
212
213   if (Subtarget->isTargetDarwin()) {
214     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215     setUseUnderscoreSetJmp(false);
216     setUseUnderscoreLongJmp(false);
217   } else if (Subtarget->isTargetMingw()) {
218     // MS runtime is weird: it exports _setjmp, but longjmp!
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(false);
221   } else {
222     setUseUnderscoreSetJmp(true);
223     setUseUnderscoreLongJmp(true);
224   }
225
226   // Set up the register classes.
227   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230   if (Subtarget->is64Bit())
231     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235   // We don't accept any truncstore of integer registers.
236   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243   // SETOEQ and SETUNE require checking two conditions.
244   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252   // operation.
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257   if (Subtarget->is64Bit()) {
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260   } else if (!UseSoftFloat) {
261     // We have an algorithm for SSE2->double, and we turn this into a
262     // 64-bit FILD followed by conditional FADD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264     // We have an algorithm for SSE2, and we turn this into a 64-bit
265     // FILD for other targets.
266     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267   }
268
269   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270   // this operation.
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274   if (!UseSoftFloat) {
275     // SSE has no i16 to fp conversion, only i32
276     if (X86ScalarSSEf32) {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278       // f32 and f64 cases are Legal, f80 case is not
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     } else {
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283     }
284   } else {
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287   }
288
289   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290   // are Legal, f80 is custom lowered.
291   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295   // this operation.
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299   if (X86ScalarSSEf32) {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301     // f32 and f64 cases are Legal, f80 case is not
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   } else {
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306   }
307
308   // Handle FP_TO_UINT by promoting the destination to a larger signed
309   // conversion.
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314   if (Subtarget->is64Bit()) {
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317   } else if (!UseSoftFloat) {
318     // Since AVX is a superset of SSE3, only check for SSE here.
319     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320       // Expand FP_TO_UINT into a select.
321       // FIXME: We would like to use a Custom expander here eventually to do
322       // the optimal thing for SSE vs. the default expansion in the legalizer.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
324     else
325       // With SSE3 we can use fisttpll to convert to a signed i64; without
326       // SSE, we're stuck with a fistpll.
327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
328   }
329
330   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331   if (!X86ScalarSSEf64) {
332     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
333     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
334     if (Subtarget->is64Bit()) {
335       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
336       // Without SSE, i64->f64 goes through memory.
337       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
338     }
339   }
340
341   // Scalar integer divide and remainder are lowered to use operations that
342   // produce two results, to match the available instructions. This exposes
343   // the two-result form to trivial CSE, which is able to combine x/y and x%y
344   // into a single instruction.
345   //
346   // Scalar integer multiply-high is also lowered to use two-result
347   // operations, to match the available instructions. However, plain multiply
348   // (low) operations are left as Legal, as there are single-result
349   // instructions for this in x86. Using the two-result multiply instructions
350   // when both high and low results are needed must be arranged by dagcombine.
351   for (unsigned i = 0, e = 4; i != e; ++i) {
352     MVT VT = IntVTs[i];
353     setOperationAction(ISD::MULHS, VT, Expand);
354     setOperationAction(ISD::MULHU, VT, Expand);
355     setOperationAction(ISD::SDIV, VT, Expand);
356     setOperationAction(ISD::UDIV, VT, Expand);
357     setOperationAction(ISD::SREM, VT, Expand);
358     setOperationAction(ISD::UREM, VT, Expand);
359
360     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361     setOperationAction(ISD::ADDC, VT, Custom);
362     setOperationAction(ISD::ADDE, VT, Custom);
363     setOperationAction(ISD::SUBC, VT, Custom);
364     setOperationAction(ISD::SUBE, VT, Custom);
365   }
366
367   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
368   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
369   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
370   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
371   if (Subtarget->is64Bit())
372     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
376   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
380   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
381
382   if (Subtarget->hasBMI()) {
383     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
384   } else {
385     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
386     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
387     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
388     if (Subtarget->is64Bit())
389       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
390   }
391
392   if (Subtarget->hasLZCNT()) {
393     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
394   } else {
395     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
396     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasPOPCNT()) {
403     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
404   } else {
405     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
406     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
407     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
410   }
411
412   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
413   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
414
415   // These should be promoted to a larger select which is supported.
416   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
417   // X86 wants to expand cmov itself.
418   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
419   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
423   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
430   if (Subtarget->is64Bit()) {
431     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
432     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
433   }
434   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
435
436   // Darwin ABI issue.
437   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
438   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
439   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
440   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
441   if (Subtarget->is64Bit())
442     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
443   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
444   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
447     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
448     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
449     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
450     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
451   }
452   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
453   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
454   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
455   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
456   if (Subtarget->is64Bit()) {
457     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
458     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
459     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
460   }
461
462   if (Subtarget->hasXMM())
463     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
464
465   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
466   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
467
468   // On X86 and X86-64, atomic operations are lowered to locked instructions.
469   // Locked instructions, in turn, have implicit fence semantics (all memory
470   // operations are flushed before issuing the locked instruction, and they
471   // are not buffered), so we can fold away the common pattern of
472   // fence-atomic-fence.
473   setShouldFoldAtomicFences(true);
474
475   // Expand certain atomics
476   for (unsigned i = 0, e = 4; i != e; ++i) {
477     MVT VT = IntVTs[i];
478     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
479     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
480     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
481   }
482
483   if (!Subtarget->is64Bit()) {
484     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
491     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
492   }
493
494   if (Subtarget->hasCmpxchg16b()) {
495     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
496   }
497
498   // FIXME - use subtarget debug flags
499   if (!Subtarget->isTargetDarwin() &&
500       !Subtarget->isTargetELF() &&
501       !Subtarget->isTargetCygMing()) {
502     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
506   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
507   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
508   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
509   if (Subtarget->is64Bit()) {
510     setExceptionPointerRegister(X86::RAX);
511     setExceptionSelectorRegister(X86::RDX);
512   } else {
513     setExceptionPointerRegister(X86::EAX);
514     setExceptionSelectorRegister(X86::EDX);
515   }
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
517   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518
519   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
520   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521
522   setOperationAction(ISD::TRAP, MVT::Other, Legal);
523
524   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
525   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
526   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
529     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
530   } else {
531     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
532     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
533   }
534
535   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
536   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
537
538   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
539     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
540                        MVT::i64 : MVT::i32, Custom);
541   else if (EnableSegmentedStacks)
542     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
543                        MVT::i64 : MVT::i32, Custom);
544   else
545     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
546                        MVT::i64 : MVT::i32, Expand);
547
548   if (!UseSoftFloat && X86ScalarSSEf64) {
549     // f32 and f64 use SSE.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
552     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553
554     // Use ANDPD to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f64, Custom);
556     setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558     // Use XORP to simulate FNEG.
559     setOperationAction(ISD::FNEG , MVT::f64, Custom);
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     // Use ANDPD and ORPD to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // Lower this to FGETSIGNx86 plus an AND.
567     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
568     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569
570     // We don't support sin/cos/fmod
571     setOperationAction(ISD::FSIN , MVT::f64, Expand);
572     setOperationAction(ISD::FCOS , MVT::f64, Expand);
573     setOperationAction(ISD::FSIN , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS , MVT::f32, Expand);
575
576     // Expand FP immediates into loads from the stack, except for the special
577     // cases we handle.
578     addLegalFPImmediate(APFloat(+0.0)); // xorpd
579     addLegalFPImmediate(APFloat(+0.0f)); // xorps
580   } else if (!UseSoftFloat && X86ScalarSSEf32) {
581     // Use SSE for f32, x87 for f64.
582     // Set up the FP register classes.
583     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
584     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585
586     // Use ANDPS to simulate FABS.
587     setOperationAction(ISD::FABS , MVT::f32, Custom);
588
589     // Use XORP to simulate FNEG.
590     setOperationAction(ISD::FNEG , MVT::f32, Custom);
591
592     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
593
594     // Use ANDPS and ORPS to simulate FCOPYSIGN.
595     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597
598     // We don't support sin/cos/fmod
599     setOperationAction(ISD::FSIN , MVT::f32, Expand);
600     setOperationAction(ISD::FCOS , MVT::f32, Expand);
601
602     // Special cases we handle for FP constants.
603     addLegalFPImmediate(APFloat(+0.0f)); // xorps
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608
609     if (!UnsafeFPMath) {
610       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
611       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
612     }
613   } else if (!UseSoftFloat) {
614     // f32 and f64 in x87.
615     // Set up the FP register classes.
616     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
617     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618
619     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
620     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
623
624     if (!UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628     addLegalFPImmediate(APFloat(+0.0)); // FLD0
629     addLegalFPImmediate(APFloat(+1.0)); // FLD1
630     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
631     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
632     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
633     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
634     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
635     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
636   }
637
638   // We don't support FMA.
639   setOperationAction(ISD::FMA, MVT::f64, Expand);
640   setOperationAction(ISD::FMA, MVT::f32, Expand);
641
642   // Long double always uses X87.
643   if (!UseSoftFloat) {
644     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
645     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
646     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647     {
648       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
649       addLegalFPImmediate(TmpFlt);  // FLD0
650       TmpFlt.changeSign();
651       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
652
653       bool ignored;
654       APFloat TmpFlt2(+1.0);
655       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656                       &ignored);
657       addLegalFPImmediate(TmpFlt2);  // FLD1
658       TmpFlt2.changeSign();
659       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
660     }
661
662     if (!UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
665     }
666
667     setOperationAction(ISD::FMA, MVT::f80, Expand);
668   }
669
670   // Always use a library call for pow.
671   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675   setOperationAction(ISD::FLOG, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680
681   // First set operation action for all vector types to either promote
682   // (for widening) or expand (for scalarization). Then we will selectively
683   // turn on ones that can be effectively codegen'd.
684   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
685        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
686     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
701     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
736     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
932     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
933     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
934     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
935     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
936
937     // i8 and i16 vectors are custom , because the source register and source
938     // source memory operand types are not the same width.  f32 vectors are
939     // custom since the immediate controlling the insert encodes additional
940     // information.
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
944     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
945
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
949     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
950
951     if (Subtarget->is64Bit()) {
952       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
953       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
954     }
955   }
956
957   if (Subtarget->hasXMMInt()) {
958     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
959     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
960     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
961     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
962
963     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
964     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
966
967     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
968     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
969   }
970
971   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
972     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
973
974   if (!UseSoftFloat && Subtarget->hasAVX()) {
975     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
976     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
977     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
978     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
979     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
980     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
981
982     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
983     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
984     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
985
986     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
988     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
989     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
990     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
991     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
992
993     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
995     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
996     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
997     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
998     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
999
1000     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1001     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1002     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1003
1004     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1005     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1006     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1007     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1008     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1009     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1010
1011     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1012     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1013     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1014     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1015
1016     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1017     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1019     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1020
1021     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1022     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1023
1024     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1025     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1026     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1027     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1028
1029     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1030     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1031     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1032
1033     setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1034     setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1035     setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1036     setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1037
1038     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1039     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1040     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1041     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1042
1043     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1044     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1045     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1046     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1047
1048     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1049     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1050     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1051     // Don't lower v32i8 because there is no 128-bit byte mul
1052
1053     // Custom lower several nodes for 256-bit types.
1054     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1055                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1056       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1057       EVT VT = SVT;
1058
1059       // Extract subvector is special because the value type
1060       // (result) is 128-bit but the source is 256-bit wide.
1061       if (VT.is128BitVector())
1062         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1063
1064       // Do not attempt to custom lower other non-256-bit vectors
1065       if (!VT.is256BitVector())
1066         continue;
1067
1068       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1069       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1070       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1071       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1072       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1073       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1074     }
1075
1076     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1077     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1078       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1079       EVT VT = SVT;
1080
1081       // Do not attempt to promote non-256-bit vectors
1082       if (!VT.is256BitVector())
1083         continue;
1084
1085       setOperationAction(ISD::AND,    SVT, Promote);
1086       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1087       setOperationAction(ISD::OR,     SVT, Promote);
1088       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1089       setOperationAction(ISD::XOR,    SVT, Promote);
1090       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1091       setOperationAction(ISD::LOAD,   SVT, Promote);
1092       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1093       setOperationAction(ISD::SELECT, SVT, Promote);
1094       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1095     }
1096   }
1097
1098   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1099   // of this type with custom code.
1100   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1101          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1102     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1103   }
1104
1105   // We want to custom lower some of our intrinsics.
1106   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1107
1108
1109   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1110   // handle type legalization for these operations here.
1111   //
1112   // FIXME: We really should do custom legalization for addition and
1113   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1114   // than generic legalization for 64-bit multiplication-with-overflow, though.
1115   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1116     // Add/Sub/Mul with overflow operations are custom lowered.
1117     MVT VT = IntVTs[i];
1118     setOperationAction(ISD::SADDO, VT, Custom);
1119     setOperationAction(ISD::UADDO, VT, Custom);
1120     setOperationAction(ISD::SSUBO, VT, Custom);
1121     setOperationAction(ISD::USUBO, VT, Custom);
1122     setOperationAction(ISD::SMULO, VT, Custom);
1123     setOperationAction(ISD::UMULO, VT, Custom);
1124   }
1125
1126   // There are no 8-bit 3-address imul/mul instructions
1127   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1128   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1129
1130   if (!Subtarget->is64Bit()) {
1131     // These libcalls are not available in 32-bit.
1132     setLibcallName(RTLIB::SHL_I128, 0);
1133     setLibcallName(RTLIB::SRL_I128, 0);
1134     setLibcallName(RTLIB::SRA_I128, 0);
1135   }
1136
1137   // We have target-specific dag combine patterns for the following nodes:
1138   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1139   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1140   setTargetDAGCombine(ISD::BUILD_VECTOR);
1141   setTargetDAGCombine(ISD::VSELECT);
1142   setTargetDAGCombine(ISD::SELECT);
1143   setTargetDAGCombine(ISD::SHL);
1144   setTargetDAGCombine(ISD::SRA);
1145   setTargetDAGCombine(ISD::SRL);
1146   setTargetDAGCombine(ISD::OR);
1147   setTargetDAGCombine(ISD::AND);
1148   setTargetDAGCombine(ISD::ADD);
1149   setTargetDAGCombine(ISD::FADD);
1150   setTargetDAGCombine(ISD::FSUB);
1151   setTargetDAGCombine(ISD::SUB);
1152   setTargetDAGCombine(ISD::LOAD);
1153   setTargetDAGCombine(ISD::STORE);
1154   setTargetDAGCombine(ISD::ZERO_EXTEND);
1155   setTargetDAGCombine(ISD::SINT_TO_FP);
1156   if (Subtarget->is64Bit())
1157     setTargetDAGCombine(ISD::MUL);
1158   if (Subtarget->hasBMI())
1159     setTargetDAGCombine(ISD::XOR);
1160
1161   computeRegisterProperties();
1162
1163   // On Darwin, -Os means optimize for size without hurting performance,
1164   // do not reduce the limit.
1165   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1166   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1167   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1168   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1169   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1170   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1171   setPrefLoopAlignment(16);
1172   benefitFromCodePlacementOpt = true;
1173
1174   setPrefFunctionAlignment(4);
1175 }
1176
1177
1178 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1179   if (!VT.isVector()) return MVT::i8;
1180   return VT.changeVectorElementTypeToInteger();
1181 }
1182
1183
1184 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1185 /// the desired ByVal argument alignment.
1186 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1187   if (MaxAlign == 16)
1188     return;
1189   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1190     if (VTy->getBitWidth() == 128)
1191       MaxAlign = 16;
1192   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1193     unsigned EltAlign = 0;
1194     getMaxByValAlign(ATy->getElementType(), EltAlign);
1195     if (EltAlign > MaxAlign)
1196       MaxAlign = EltAlign;
1197   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1198     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1199       unsigned EltAlign = 0;
1200       getMaxByValAlign(STy->getElementType(i), EltAlign);
1201       if (EltAlign > MaxAlign)
1202         MaxAlign = EltAlign;
1203       if (MaxAlign == 16)
1204         break;
1205     }
1206   }
1207   return;
1208 }
1209
1210 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1211 /// function arguments in the caller parameter area. For X86, aggregates
1212 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1213 /// are at 4-byte boundaries.
1214 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1215   if (Subtarget->is64Bit()) {
1216     // Max of 8 and alignment of type.
1217     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1218     if (TyAlign > 8)
1219       return TyAlign;
1220     return 8;
1221   }
1222
1223   unsigned Align = 4;
1224   if (Subtarget->hasXMM())
1225     getMaxByValAlign(Ty, Align);
1226   return Align;
1227 }
1228
1229 /// getOptimalMemOpType - Returns the target specific optimal type for load
1230 /// and store operations as a result of memset, memcpy, and memmove
1231 /// lowering. If DstAlign is zero that means it's safe to destination
1232 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1233 /// means there isn't a need to check it against alignment requirement,
1234 /// probably because the source does not need to be loaded. If
1235 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1236 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1237 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1238 /// constant so it does not need to be loaded.
1239 /// It returns EVT::Other if the type should be determined using generic
1240 /// target-independent logic.
1241 EVT
1242 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1243                                        unsigned DstAlign, unsigned SrcAlign,
1244                                        bool NonScalarIntSafe,
1245                                        bool MemcpyStrSrc,
1246                                        MachineFunction &MF) const {
1247   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1248   // linux.  This is because the stack realignment code can't handle certain
1249   // cases like PR2962.  This should be removed when PR2962 is fixed.
1250   const Function *F = MF.getFunction();
1251   if (NonScalarIntSafe &&
1252       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1253     if (Size >= 16 &&
1254         (Subtarget->isUnalignedMemAccessFast() ||
1255          ((DstAlign == 0 || DstAlign >= 16) &&
1256           (SrcAlign == 0 || SrcAlign >= 16))) &&
1257         Subtarget->getStackAlignment() >= 16) {
1258       if (Subtarget->hasAVX() &&
1259           Subtarget->getStackAlignment() >= 32)
1260         return MVT::v8f32;
1261       if (Subtarget->hasXMMInt())
1262         return MVT::v4i32;
1263       if (Subtarget->hasXMM())
1264         return MVT::v4f32;
1265     } else if (!MemcpyStrSrc && Size >= 8 &&
1266                !Subtarget->is64Bit() &&
1267                Subtarget->getStackAlignment() >= 8 &&
1268                Subtarget->hasXMMInt()) {
1269       // Do not use f64 to lower memcpy if source is string constant. It's
1270       // better to use i32 to avoid the loads.
1271       return MVT::f64;
1272     }
1273   }
1274   if (Subtarget->is64Bit() && Size >= 8)
1275     return MVT::i64;
1276   return MVT::i32;
1277 }
1278
1279 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1280 /// current function.  The returned value is a member of the
1281 /// MachineJumpTableInfo::JTEntryKind enum.
1282 unsigned X86TargetLowering::getJumpTableEncoding() const {
1283   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1284   // symbol.
1285   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1286       Subtarget->isPICStyleGOT())
1287     return MachineJumpTableInfo::EK_Custom32;
1288
1289   // Otherwise, use the normal jump table encoding heuristics.
1290   return TargetLowering::getJumpTableEncoding();
1291 }
1292
1293 const MCExpr *
1294 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1295                                              const MachineBasicBlock *MBB,
1296                                              unsigned uid,MCContext &Ctx) const{
1297   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1298          Subtarget->isPICStyleGOT());
1299   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1300   // entries.
1301   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1302                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1303 }
1304
1305 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1306 /// jumptable.
1307 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1308                                                     SelectionDAG &DAG) const {
1309   if (!Subtarget->is64Bit())
1310     // This doesn't have DebugLoc associated with it, but is not really the
1311     // same as a Register.
1312     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1313   return Table;
1314 }
1315
1316 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1317 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1318 /// MCExpr.
1319 const MCExpr *X86TargetLowering::
1320 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1321                              MCContext &Ctx) const {
1322   // X86-64 uses RIP relative addressing based on the jump table label.
1323   if (Subtarget->isPICStyleRIPRel())
1324     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1325
1326   // Otherwise, the reference is relative to the PIC base.
1327   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1328 }
1329
1330 // FIXME: Why this routine is here? Move to RegInfo!
1331 std::pair<const TargetRegisterClass*, uint8_t>
1332 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1333   const TargetRegisterClass *RRC = 0;
1334   uint8_t Cost = 1;
1335   switch (VT.getSimpleVT().SimpleTy) {
1336   default:
1337     return TargetLowering::findRepresentativeClass(VT);
1338   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1339     RRC = (Subtarget->is64Bit()
1340            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1341     break;
1342   case MVT::x86mmx:
1343     RRC = X86::VR64RegisterClass;
1344     break;
1345   case MVT::f32: case MVT::f64:
1346   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1347   case MVT::v4f32: case MVT::v2f64:
1348   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1349   case MVT::v4f64:
1350     RRC = X86::VR128RegisterClass;
1351     break;
1352   }
1353   return std::make_pair(RRC, Cost);
1354 }
1355
1356 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1357                                                unsigned &Offset) const {
1358   if (!Subtarget->isTargetLinux())
1359     return false;
1360
1361   if (Subtarget->is64Bit()) {
1362     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1363     Offset = 0x28;
1364     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1365       AddressSpace = 256;
1366     else
1367       AddressSpace = 257;
1368   } else {
1369     // %gs:0x14 on i386
1370     Offset = 0x14;
1371     AddressSpace = 256;
1372   }
1373   return true;
1374 }
1375
1376
1377 //===----------------------------------------------------------------------===//
1378 //               Return Value Calling Convention Implementation
1379 //===----------------------------------------------------------------------===//
1380
1381 #include "X86GenCallingConv.inc"
1382
1383 bool
1384 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1385                                   MachineFunction &MF, bool isVarArg,
1386                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1387                         LLVMContext &Context) const {
1388   SmallVector<CCValAssign, 16> RVLocs;
1389   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1390                  RVLocs, Context);
1391   return CCInfo.CheckReturn(Outs, RetCC_X86);
1392 }
1393
1394 SDValue
1395 X86TargetLowering::LowerReturn(SDValue Chain,
1396                                CallingConv::ID CallConv, bool isVarArg,
1397                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1398                                const SmallVectorImpl<SDValue> &OutVals,
1399                                DebugLoc dl, SelectionDAG &DAG) const {
1400   MachineFunction &MF = DAG.getMachineFunction();
1401   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1402
1403   SmallVector<CCValAssign, 16> RVLocs;
1404   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1405                  RVLocs, *DAG.getContext());
1406   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1407
1408   // Add the regs to the liveout set for the function.
1409   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1410   for (unsigned i = 0; i != RVLocs.size(); ++i)
1411     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1412       MRI.addLiveOut(RVLocs[i].getLocReg());
1413
1414   SDValue Flag;
1415
1416   SmallVector<SDValue, 6> RetOps;
1417   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1418   // Operand #1 = Bytes To Pop
1419   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1420                    MVT::i16));
1421
1422   // Copy the result values into the output registers.
1423   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1424     CCValAssign &VA = RVLocs[i];
1425     assert(VA.isRegLoc() && "Can only return in registers!");
1426     SDValue ValToCopy = OutVals[i];
1427     EVT ValVT = ValToCopy.getValueType();
1428
1429     // If this is x86-64, and we disabled SSE, we can't return FP values,
1430     // or SSE or MMX vectors.
1431     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1432          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1433           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1434       report_fatal_error("SSE register return with SSE disabled");
1435     }
1436     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1437     // llvm-gcc has never done it right and no one has noticed, so this
1438     // should be OK for now.
1439     if (ValVT == MVT::f64 &&
1440         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1441       report_fatal_error("SSE2 register return with SSE2 disabled");
1442
1443     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1444     // the RET instruction and handled by the FP Stackifier.
1445     if (VA.getLocReg() == X86::ST0 ||
1446         VA.getLocReg() == X86::ST1) {
1447       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1448       // change the value to the FP stack register class.
1449       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1450         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1451       RetOps.push_back(ValToCopy);
1452       // Don't emit a copytoreg.
1453       continue;
1454     }
1455
1456     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1457     // which is returned in RAX / RDX.
1458     if (Subtarget->is64Bit()) {
1459       if (ValVT == MVT::x86mmx) {
1460         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1461           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1462           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1463                                   ValToCopy);
1464           // If we don't have SSE2 available, convert to v4f32 so the generated
1465           // register is legal.
1466           if (!Subtarget->hasXMMInt())
1467             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1468         }
1469       }
1470     }
1471
1472     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1473     Flag = Chain.getValue(1);
1474   }
1475
1476   // The x86-64 ABI for returning structs by value requires that we copy
1477   // the sret argument into %rax for the return. We saved the argument into
1478   // a virtual register in the entry block, so now we copy the value out
1479   // and into %rax.
1480   if (Subtarget->is64Bit() &&
1481       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1482     MachineFunction &MF = DAG.getMachineFunction();
1483     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1484     unsigned Reg = FuncInfo->getSRetReturnReg();
1485     assert(Reg &&
1486            "SRetReturnReg should have been set in LowerFormalArguments().");
1487     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1488
1489     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1490     Flag = Chain.getValue(1);
1491
1492     // RAX now acts like a return value.
1493     MRI.addLiveOut(X86::RAX);
1494   }
1495
1496   RetOps[0] = Chain;  // Update chain.
1497
1498   // Add the flag if we have it.
1499   if (Flag.getNode())
1500     RetOps.push_back(Flag);
1501
1502   return DAG.getNode(X86ISD::RET_FLAG, dl,
1503                      MVT::Other, &RetOps[0], RetOps.size());
1504 }
1505
1506 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1507   if (N->getNumValues() != 1)
1508     return false;
1509   if (!N->hasNUsesOfValue(1, 0))
1510     return false;
1511
1512   SDNode *Copy = *N->use_begin();
1513   if (Copy->getOpcode() != ISD::CopyToReg &&
1514       Copy->getOpcode() != ISD::FP_EXTEND)
1515     return false;
1516
1517   bool HasRet = false;
1518   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1519        UI != UE; ++UI) {
1520     if (UI->getOpcode() != X86ISD::RET_FLAG)
1521       return false;
1522     HasRet = true;
1523   }
1524
1525   return HasRet;
1526 }
1527
1528 EVT
1529 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1530                                             ISD::NodeType ExtendKind) const {
1531   MVT ReturnMVT;
1532   // TODO: Is this also valid on 32-bit?
1533   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1534     ReturnMVT = MVT::i8;
1535   else
1536     ReturnMVT = MVT::i32;
1537
1538   EVT MinVT = getRegisterType(Context, ReturnMVT);
1539   return VT.bitsLT(MinVT) ? MinVT : VT;
1540 }
1541
1542 /// LowerCallResult - Lower the result values of a call into the
1543 /// appropriate copies out of appropriate physical registers.
1544 ///
1545 SDValue
1546 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1547                                    CallingConv::ID CallConv, bool isVarArg,
1548                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1549                                    DebugLoc dl, SelectionDAG &DAG,
1550                                    SmallVectorImpl<SDValue> &InVals) const {
1551
1552   // Assign locations to each value returned by this call.
1553   SmallVector<CCValAssign, 16> RVLocs;
1554   bool Is64Bit = Subtarget->is64Bit();
1555   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1556                  getTargetMachine(), RVLocs, *DAG.getContext());
1557   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1558
1559   // Copy all of the result registers out of their specified physreg.
1560   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1561     CCValAssign &VA = RVLocs[i];
1562     EVT CopyVT = VA.getValVT();
1563
1564     // If this is x86-64, and we disabled SSE, we can't return FP values
1565     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1566         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1567       report_fatal_error("SSE register return with SSE disabled");
1568     }
1569
1570     SDValue Val;
1571
1572     // If this is a call to a function that returns an fp value on the floating
1573     // point stack, we must guarantee the the value is popped from the stack, so
1574     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1575     // if the return value is not used. We use the FpPOP_RETVAL instruction
1576     // instead.
1577     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1578       // If we prefer to use the value in xmm registers, copy it out as f80 and
1579       // use a truncate to move it from fp stack reg to xmm reg.
1580       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1581       SDValue Ops[] = { Chain, InFlag };
1582       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1583                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1584       Val = Chain.getValue(0);
1585
1586       // Round the f80 to the right size, which also moves it to the appropriate
1587       // xmm register.
1588       if (CopyVT != VA.getValVT())
1589         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1590                           // This truncation won't change the value.
1591                           DAG.getIntPtrConstant(1));
1592     } else {
1593       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1594                                  CopyVT, InFlag).getValue(1);
1595       Val = Chain.getValue(0);
1596     }
1597     InFlag = Chain.getValue(2);
1598     InVals.push_back(Val);
1599   }
1600
1601   return Chain;
1602 }
1603
1604
1605 //===----------------------------------------------------------------------===//
1606 //                C & StdCall & Fast Calling Convention implementation
1607 //===----------------------------------------------------------------------===//
1608 //  StdCall calling convention seems to be standard for many Windows' API
1609 //  routines and around. It differs from C calling convention just a little:
1610 //  callee should clean up the stack, not caller. Symbols should be also
1611 //  decorated in some fancy way :) It doesn't support any vector arguments.
1612 //  For info on fast calling convention see Fast Calling Convention (tail call)
1613 //  implementation LowerX86_32FastCCCallTo.
1614
1615 /// CallIsStructReturn - Determines whether a call uses struct return
1616 /// semantics.
1617 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1618   if (Outs.empty())
1619     return false;
1620
1621   return Outs[0].Flags.isSRet();
1622 }
1623
1624 /// ArgsAreStructReturn - Determines whether a function uses struct
1625 /// return semantics.
1626 static bool
1627 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1628   if (Ins.empty())
1629     return false;
1630
1631   return Ins[0].Flags.isSRet();
1632 }
1633
1634 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1635 /// by "Src" to address "Dst" with size and alignment information specified by
1636 /// the specific parameter attribute. The copy will be passed as a byval
1637 /// function parameter.
1638 static SDValue
1639 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1640                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1641                           DebugLoc dl) {
1642   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1643
1644   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1645                        /*isVolatile*/false, /*AlwaysInline=*/true,
1646                        MachinePointerInfo(), MachinePointerInfo());
1647 }
1648
1649 /// IsTailCallConvention - Return true if the calling convention is one that
1650 /// supports tail call optimization.
1651 static bool IsTailCallConvention(CallingConv::ID CC) {
1652   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1653 }
1654
1655 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1656   if (!CI->isTailCall())
1657     return false;
1658
1659   CallSite CS(CI);
1660   CallingConv::ID CalleeCC = CS.getCallingConv();
1661   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1662     return false;
1663
1664   return true;
1665 }
1666
1667 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1668 /// a tailcall target by changing its ABI.
1669 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1670   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1671 }
1672
1673 SDValue
1674 X86TargetLowering::LowerMemArgument(SDValue Chain,
1675                                     CallingConv::ID CallConv,
1676                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1677                                     DebugLoc dl, SelectionDAG &DAG,
1678                                     const CCValAssign &VA,
1679                                     MachineFrameInfo *MFI,
1680                                     unsigned i) const {
1681   // Create the nodes corresponding to a load from this parameter slot.
1682   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1683   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1684   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1685   EVT ValVT;
1686
1687   // If value is passed by pointer we have address passed instead of the value
1688   // itself.
1689   if (VA.getLocInfo() == CCValAssign::Indirect)
1690     ValVT = VA.getLocVT();
1691   else
1692     ValVT = VA.getValVT();
1693
1694   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1695   // changed with more analysis.
1696   // In case of tail call optimization mark all arguments mutable. Since they
1697   // could be overwritten by lowering of arguments in case of a tail call.
1698   if (Flags.isByVal()) {
1699     unsigned Bytes = Flags.getByValSize();
1700     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1701     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1702     return DAG.getFrameIndex(FI, getPointerTy());
1703   } else {
1704     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1705                                     VA.getLocMemOffset(), isImmutable);
1706     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1707     return DAG.getLoad(ValVT, dl, Chain, FIN,
1708                        MachinePointerInfo::getFixedStack(FI),
1709                        false, false, 0);
1710   }
1711 }
1712
1713 SDValue
1714 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1715                                         CallingConv::ID CallConv,
1716                                         bool isVarArg,
1717                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1718                                         DebugLoc dl,
1719                                         SelectionDAG &DAG,
1720                                         SmallVectorImpl<SDValue> &InVals)
1721                                           const {
1722   MachineFunction &MF = DAG.getMachineFunction();
1723   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1724
1725   const Function* Fn = MF.getFunction();
1726   if (Fn->hasExternalLinkage() &&
1727       Subtarget->isTargetCygMing() &&
1728       Fn->getName() == "main")
1729     FuncInfo->setForceFramePointer(true);
1730
1731   MachineFrameInfo *MFI = MF.getFrameInfo();
1732   bool Is64Bit = Subtarget->is64Bit();
1733   bool IsWin64 = Subtarget->isTargetWin64();
1734
1735   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1736          "Var args not supported with calling convention fastcc or ghc");
1737
1738   // Assign locations to all of the incoming arguments.
1739   SmallVector<CCValAssign, 16> ArgLocs;
1740   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1741                  ArgLocs, *DAG.getContext());
1742
1743   // Allocate shadow area for Win64
1744   if (IsWin64) {
1745     CCInfo.AllocateStack(32, 8);
1746   }
1747
1748   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1749
1750   unsigned LastVal = ~0U;
1751   SDValue ArgValue;
1752   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1753     CCValAssign &VA = ArgLocs[i];
1754     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1755     // places.
1756     assert(VA.getValNo() != LastVal &&
1757            "Don't support value assigned to multiple locs yet");
1758     (void)LastVal;
1759     LastVal = VA.getValNo();
1760
1761     if (VA.isRegLoc()) {
1762       EVT RegVT = VA.getLocVT();
1763       TargetRegisterClass *RC = NULL;
1764       if (RegVT == MVT::i32)
1765         RC = X86::GR32RegisterClass;
1766       else if (Is64Bit && RegVT == MVT::i64)
1767         RC = X86::GR64RegisterClass;
1768       else if (RegVT == MVT::f32)
1769         RC = X86::FR32RegisterClass;
1770       else if (RegVT == MVT::f64)
1771         RC = X86::FR64RegisterClass;
1772       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1773         RC = X86::VR256RegisterClass;
1774       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1775         RC = X86::VR128RegisterClass;
1776       else if (RegVT == MVT::x86mmx)
1777         RC = X86::VR64RegisterClass;
1778       else
1779         llvm_unreachable("Unknown argument type!");
1780
1781       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1782       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1783
1784       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1785       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1786       // right size.
1787       if (VA.getLocInfo() == CCValAssign::SExt)
1788         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1789                                DAG.getValueType(VA.getValVT()));
1790       else if (VA.getLocInfo() == CCValAssign::ZExt)
1791         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1792                                DAG.getValueType(VA.getValVT()));
1793       else if (VA.getLocInfo() == CCValAssign::BCvt)
1794         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1795
1796       if (VA.isExtInLoc()) {
1797         // Handle MMX values passed in XMM regs.
1798         if (RegVT.isVector()) {
1799           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1800                                  ArgValue);
1801         } else
1802           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1803       }
1804     } else {
1805       assert(VA.isMemLoc());
1806       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1807     }
1808
1809     // If value is passed via pointer - do a load.
1810     if (VA.getLocInfo() == CCValAssign::Indirect)
1811       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1812                              MachinePointerInfo(), false, false, 0);
1813
1814     InVals.push_back(ArgValue);
1815   }
1816
1817   // The x86-64 ABI for returning structs by value requires that we copy
1818   // the sret argument into %rax for the return. Save the argument into
1819   // a virtual register so that we can access it from the return points.
1820   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1821     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1822     unsigned Reg = FuncInfo->getSRetReturnReg();
1823     if (!Reg) {
1824       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1825       FuncInfo->setSRetReturnReg(Reg);
1826     }
1827     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1828     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1829   }
1830
1831   unsigned StackSize = CCInfo.getNextStackOffset();
1832   // Align stack specially for tail calls.
1833   if (FuncIsMadeTailCallSafe(CallConv))
1834     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1835
1836   // If the function takes variable number of arguments, make a frame index for
1837   // the start of the first vararg value... for expansion of llvm.va_start.
1838   if (isVarArg) {
1839     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1840                     CallConv != CallingConv::X86_ThisCall)) {
1841       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1842     }
1843     if (Is64Bit) {
1844       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1845
1846       // FIXME: We should really autogenerate these arrays
1847       static const unsigned GPR64ArgRegsWin64[] = {
1848         X86::RCX, X86::RDX, X86::R8,  X86::R9
1849       };
1850       static const unsigned GPR64ArgRegs64Bit[] = {
1851         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1852       };
1853       static const unsigned XMMArgRegs64Bit[] = {
1854         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1855         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1856       };
1857       const unsigned *GPR64ArgRegs;
1858       unsigned NumXMMRegs = 0;
1859
1860       if (IsWin64) {
1861         // The XMM registers which might contain var arg parameters are shadowed
1862         // in their paired GPR.  So we only need to save the GPR to their home
1863         // slots.
1864         TotalNumIntRegs = 4;
1865         GPR64ArgRegs = GPR64ArgRegsWin64;
1866       } else {
1867         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1868         GPR64ArgRegs = GPR64ArgRegs64Bit;
1869
1870         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1871       }
1872       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1873                                                        TotalNumIntRegs);
1874
1875       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1876       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1877              "SSE register cannot be used when SSE is disabled!");
1878       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1879              "SSE register cannot be used when SSE is disabled!");
1880       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1881         // Kernel mode asks for SSE to be disabled, so don't push them
1882         // on the stack.
1883         TotalNumXMMRegs = 0;
1884
1885       if (IsWin64) {
1886         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1887         // Get to the caller-allocated home save location.  Add 8 to account
1888         // for the return address.
1889         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1890         FuncInfo->setRegSaveFrameIndex(
1891           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1892         // Fixup to set vararg frame on shadow area (4 x i64).
1893         if (NumIntRegs < 4)
1894           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1895       } else {
1896         // For X86-64, if there are vararg parameters that are passed via
1897         // registers, then we must store them to their spots on the stack so they
1898         // may be loaded by deferencing the result of va_next.
1899         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1900         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1901         FuncInfo->setRegSaveFrameIndex(
1902           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1903                                false));
1904       }
1905
1906       // Store the integer parameter registers.
1907       SmallVector<SDValue, 8> MemOps;
1908       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1909                                         getPointerTy());
1910       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1911       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1912         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1913                                   DAG.getIntPtrConstant(Offset));
1914         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1915                                      X86::GR64RegisterClass);
1916         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1917         SDValue Store =
1918           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1919                        MachinePointerInfo::getFixedStack(
1920                          FuncInfo->getRegSaveFrameIndex(), Offset),
1921                        false, false, 0);
1922         MemOps.push_back(Store);
1923         Offset += 8;
1924       }
1925
1926       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1927         // Now store the XMM (fp + vector) parameter registers.
1928         SmallVector<SDValue, 11> SaveXMMOps;
1929         SaveXMMOps.push_back(Chain);
1930
1931         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1932         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1933         SaveXMMOps.push_back(ALVal);
1934
1935         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1936                                FuncInfo->getRegSaveFrameIndex()));
1937         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1938                                FuncInfo->getVarArgsFPOffset()));
1939
1940         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1941           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1942                                        X86::VR128RegisterClass);
1943           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1944           SaveXMMOps.push_back(Val);
1945         }
1946         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1947                                      MVT::Other,
1948                                      &SaveXMMOps[0], SaveXMMOps.size()));
1949       }
1950
1951       if (!MemOps.empty())
1952         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1953                             &MemOps[0], MemOps.size());
1954     }
1955   }
1956
1957   // Some CCs need callee pop.
1958   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1959     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1960   } else {
1961     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1962     // If this is an sret function, the return should pop the hidden pointer.
1963     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1964       FuncInfo->setBytesToPopOnReturn(4);
1965   }
1966
1967   if (!Is64Bit) {
1968     // RegSaveFrameIndex is X86-64 only.
1969     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1970     if (CallConv == CallingConv::X86_FastCall ||
1971         CallConv == CallingConv::X86_ThisCall)
1972       // fastcc functions can't have varargs.
1973       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1974   }
1975
1976   FuncInfo->setArgumentStackSize(StackSize);
1977
1978   return Chain;
1979 }
1980
1981 SDValue
1982 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1983                                     SDValue StackPtr, SDValue Arg,
1984                                     DebugLoc dl, SelectionDAG &DAG,
1985                                     const CCValAssign &VA,
1986                                     ISD::ArgFlagsTy Flags) const {
1987   unsigned LocMemOffset = VA.getLocMemOffset();
1988   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1989   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1990   if (Flags.isByVal())
1991     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1992
1993   return DAG.getStore(Chain, dl, Arg, PtrOff,
1994                       MachinePointerInfo::getStack(LocMemOffset),
1995                       false, false, 0);
1996 }
1997
1998 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1999 /// optimization is performed and it is required.
2000 SDValue
2001 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2002                                            SDValue &OutRetAddr, SDValue Chain,
2003                                            bool IsTailCall, bool Is64Bit,
2004                                            int FPDiff, DebugLoc dl) const {
2005   // Adjust the Return address stack slot.
2006   EVT VT = getPointerTy();
2007   OutRetAddr = getReturnAddressFrameIndex(DAG);
2008
2009   // Load the "old" Return address.
2010   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2011                            false, false, 0);
2012   return SDValue(OutRetAddr.getNode(), 1);
2013 }
2014
2015 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2016 /// optimization is performed and it is required (FPDiff!=0).
2017 static SDValue
2018 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2019                          SDValue Chain, SDValue RetAddrFrIdx,
2020                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2021   // Store the return address to the appropriate stack slot.
2022   if (!FPDiff) return Chain;
2023   // Calculate the new stack slot for the return address.
2024   int SlotSize = Is64Bit ? 8 : 4;
2025   int NewReturnAddrFI =
2026     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2027   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2028   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2029   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2030                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2031                        false, false, 0);
2032   return Chain;
2033 }
2034
2035 SDValue
2036 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2037                              CallingConv::ID CallConv, bool isVarArg,
2038                              bool &isTailCall,
2039                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2040                              const SmallVectorImpl<SDValue> &OutVals,
2041                              const SmallVectorImpl<ISD::InputArg> &Ins,
2042                              DebugLoc dl, SelectionDAG &DAG,
2043                              SmallVectorImpl<SDValue> &InVals) const {
2044   MachineFunction &MF = DAG.getMachineFunction();
2045   bool Is64Bit        = Subtarget->is64Bit();
2046   bool IsWin64        = Subtarget->isTargetWin64();
2047   bool IsStructRet    = CallIsStructReturn(Outs);
2048   bool IsSibcall      = false;
2049
2050   if (isTailCall) {
2051     // Check if it's really possible to do a tail call.
2052     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2053                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2054                                                    Outs, OutVals, Ins, DAG);
2055
2056     // Sibcalls are automatically detected tailcalls which do not require
2057     // ABI changes.
2058     if (!GuaranteedTailCallOpt && isTailCall)
2059       IsSibcall = true;
2060
2061     if (isTailCall)
2062       ++NumTailCalls;
2063   }
2064
2065   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2066          "Var args not supported with calling convention fastcc or ghc");
2067
2068   // Analyze operands of the call, assigning locations to each operand.
2069   SmallVector<CCValAssign, 16> ArgLocs;
2070   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2071                  ArgLocs, *DAG.getContext());
2072
2073   // Allocate shadow area for Win64
2074   if (IsWin64) {
2075     CCInfo.AllocateStack(32, 8);
2076   }
2077
2078   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2079
2080   // Get a count of how many bytes are to be pushed on the stack.
2081   unsigned NumBytes = CCInfo.getNextStackOffset();
2082   if (IsSibcall)
2083     // This is a sibcall. The memory operands are available in caller's
2084     // own caller's stack.
2085     NumBytes = 0;
2086   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2087     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2088
2089   int FPDiff = 0;
2090   if (isTailCall && !IsSibcall) {
2091     // Lower arguments at fp - stackoffset + fpdiff.
2092     unsigned NumBytesCallerPushed =
2093       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2094     FPDiff = NumBytesCallerPushed - NumBytes;
2095
2096     // Set the delta of movement of the returnaddr stackslot.
2097     // But only set if delta is greater than previous delta.
2098     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2099       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2100   }
2101
2102   if (!IsSibcall)
2103     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2104
2105   SDValue RetAddrFrIdx;
2106   // Load return address for tail calls.
2107   if (isTailCall && FPDiff)
2108     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2109                                     Is64Bit, FPDiff, dl);
2110
2111   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2112   SmallVector<SDValue, 8> MemOpChains;
2113   SDValue StackPtr;
2114
2115   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2116   // of tail call optimization arguments are handle later.
2117   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2118     CCValAssign &VA = ArgLocs[i];
2119     EVT RegVT = VA.getLocVT();
2120     SDValue Arg = OutVals[i];
2121     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2122     bool isByVal = Flags.isByVal();
2123
2124     // Promote the value if needed.
2125     switch (VA.getLocInfo()) {
2126     default: llvm_unreachable("Unknown loc info!");
2127     case CCValAssign::Full: break;
2128     case CCValAssign::SExt:
2129       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2130       break;
2131     case CCValAssign::ZExt:
2132       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2133       break;
2134     case CCValAssign::AExt:
2135       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2136         // Special case: passing MMX values in XMM registers.
2137         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2138         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2139         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2140       } else
2141         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2142       break;
2143     case CCValAssign::BCvt:
2144       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2145       break;
2146     case CCValAssign::Indirect: {
2147       // Store the argument.
2148       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2149       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2150       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2151                            MachinePointerInfo::getFixedStack(FI),
2152                            false, false, 0);
2153       Arg = SpillSlot;
2154       break;
2155     }
2156     }
2157
2158     if (VA.isRegLoc()) {
2159       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2160       if (isVarArg && IsWin64) {
2161         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2162         // shadow reg if callee is a varargs function.
2163         unsigned ShadowReg = 0;
2164         switch (VA.getLocReg()) {
2165         case X86::XMM0: ShadowReg = X86::RCX; break;
2166         case X86::XMM1: ShadowReg = X86::RDX; break;
2167         case X86::XMM2: ShadowReg = X86::R8; break;
2168         case X86::XMM3: ShadowReg = X86::R9; break;
2169         }
2170         if (ShadowReg)
2171           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2172       }
2173     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2174       assert(VA.isMemLoc());
2175       if (StackPtr.getNode() == 0)
2176         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2177       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2178                                              dl, DAG, VA, Flags));
2179     }
2180   }
2181
2182   if (!MemOpChains.empty())
2183     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2184                         &MemOpChains[0], MemOpChains.size());
2185
2186   // Build a sequence of copy-to-reg nodes chained together with token chain
2187   // and flag operands which copy the outgoing args into registers.
2188   SDValue InFlag;
2189   // Tail call byval lowering might overwrite argument registers so in case of
2190   // tail call optimization the copies to registers are lowered later.
2191   if (!isTailCall)
2192     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2193       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2194                                RegsToPass[i].second, InFlag);
2195       InFlag = Chain.getValue(1);
2196     }
2197
2198   if (Subtarget->isPICStyleGOT()) {
2199     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2200     // GOT pointer.
2201     if (!isTailCall) {
2202       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2203                                DAG.getNode(X86ISD::GlobalBaseReg,
2204                                            DebugLoc(), getPointerTy()),
2205                                InFlag);
2206       InFlag = Chain.getValue(1);
2207     } else {
2208       // If we are tail calling and generating PIC/GOT style code load the
2209       // address of the callee into ECX. The value in ecx is used as target of
2210       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2211       // for tail calls on PIC/GOT architectures. Normally we would just put the
2212       // address of GOT into ebx and then call target@PLT. But for tail calls
2213       // ebx would be restored (since ebx is callee saved) before jumping to the
2214       // target@PLT.
2215
2216       // Note: The actual moving to ECX is done further down.
2217       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2218       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2219           !G->getGlobal()->hasProtectedVisibility())
2220         Callee = LowerGlobalAddress(Callee, DAG);
2221       else if (isa<ExternalSymbolSDNode>(Callee))
2222         Callee = LowerExternalSymbol(Callee, DAG);
2223     }
2224   }
2225
2226   if (Is64Bit && isVarArg && !IsWin64) {
2227     // From AMD64 ABI document:
2228     // For calls that may call functions that use varargs or stdargs
2229     // (prototype-less calls or calls to functions containing ellipsis (...) in
2230     // the declaration) %al is used as hidden argument to specify the number
2231     // of SSE registers used. The contents of %al do not need to match exactly
2232     // the number of registers, but must be an ubound on the number of SSE
2233     // registers used and is in the range 0 - 8 inclusive.
2234
2235     // Count the number of XMM registers allocated.
2236     static const unsigned XMMArgRegs[] = {
2237       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2238       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2239     };
2240     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2241     assert((Subtarget->hasXMM() || !NumXMMRegs)
2242            && "SSE registers cannot be used when SSE is disabled");
2243
2244     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2245                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2246     InFlag = Chain.getValue(1);
2247   }
2248
2249
2250   // For tail calls lower the arguments to the 'real' stack slot.
2251   if (isTailCall) {
2252     // Force all the incoming stack arguments to be loaded from the stack
2253     // before any new outgoing arguments are stored to the stack, because the
2254     // outgoing stack slots may alias the incoming argument stack slots, and
2255     // the alias isn't otherwise explicit. This is slightly more conservative
2256     // than necessary, because it means that each store effectively depends
2257     // on every argument instead of just those arguments it would clobber.
2258     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2259
2260     SmallVector<SDValue, 8> MemOpChains2;
2261     SDValue FIN;
2262     int FI = 0;
2263     // Do not flag preceding copytoreg stuff together with the following stuff.
2264     InFlag = SDValue();
2265     if (GuaranteedTailCallOpt) {
2266       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2267         CCValAssign &VA = ArgLocs[i];
2268         if (VA.isRegLoc())
2269           continue;
2270         assert(VA.isMemLoc());
2271         SDValue Arg = OutVals[i];
2272         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2273         // Create frame index.
2274         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2275         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2276         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2277         FIN = DAG.getFrameIndex(FI, getPointerTy());
2278
2279         if (Flags.isByVal()) {
2280           // Copy relative to framepointer.
2281           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2282           if (StackPtr.getNode() == 0)
2283             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2284                                           getPointerTy());
2285           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2286
2287           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2288                                                            ArgChain,
2289                                                            Flags, DAG, dl));
2290         } else {
2291           // Store relative to framepointer.
2292           MemOpChains2.push_back(
2293             DAG.getStore(ArgChain, dl, Arg, FIN,
2294                          MachinePointerInfo::getFixedStack(FI),
2295                          false, false, 0));
2296         }
2297       }
2298     }
2299
2300     if (!MemOpChains2.empty())
2301       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2302                           &MemOpChains2[0], MemOpChains2.size());
2303
2304     // Copy arguments to their registers.
2305     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2306       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2307                                RegsToPass[i].second, InFlag);
2308       InFlag = Chain.getValue(1);
2309     }
2310     InFlag =SDValue();
2311
2312     // Store the return address to the appropriate stack slot.
2313     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2314                                      FPDiff, dl);
2315   }
2316
2317   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2318     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2319     // In the 64-bit large code model, we have to make all calls
2320     // through a register, since the call instruction's 32-bit
2321     // pc-relative offset may not be large enough to hold the whole
2322     // address.
2323   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2324     // If the callee is a GlobalAddress node (quite common, every direct call
2325     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2326     // it.
2327
2328     // We should use extra load for direct calls to dllimported functions in
2329     // non-JIT mode.
2330     const GlobalValue *GV = G->getGlobal();
2331     if (!GV->hasDLLImportLinkage()) {
2332       unsigned char OpFlags = 0;
2333       bool ExtraLoad = false;
2334       unsigned WrapperKind = ISD::DELETED_NODE;
2335
2336       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2337       // external symbols most go through the PLT in PIC mode.  If the symbol
2338       // has hidden or protected visibility, or if it is static or local, then
2339       // we don't need to use the PLT - we can directly call it.
2340       if (Subtarget->isTargetELF() &&
2341           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2342           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2343         OpFlags = X86II::MO_PLT;
2344       } else if (Subtarget->isPICStyleStubAny() &&
2345                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2346                  (!Subtarget->getTargetTriple().isMacOSX() ||
2347                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2348         // PC-relative references to external symbols should go through $stub,
2349         // unless we're building with the leopard linker or later, which
2350         // automatically synthesizes these stubs.
2351         OpFlags = X86II::MO_DARWIN_STUB;
2352       } else if (Subtarget->isPICStyleRIPRel() &&
2353                  isa<Function>(GV) &&
2354                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2355         // If the function is marked as non-lazy, generate an indirect call
2356         // which loads from the GOT directly. This avoids runtime overhead
2357         // at the cost of eager binding (and one extra byte of encoding).
2358         OpFlags = X86II::MO_GOTPCREL;
2359         WrapperKind = X86ISD::WrapperRIP;
2360         ExtraLoad = true;
2361       }
2362
2363       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2364                                           G->getOffset(), OpFlags);
2365
2366       // Add a wrapper if needed.
2367       if (WrapperKind != ISD::DELETED_NODE)
2368         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2369       // Add extra indirection if needed.
2370       if (ExtraLoad)
2371         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2372                              MachinePointerInfo::getGOT(),
2373                              false, false, 0);
2374     }
2375   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2376     unsigned char OpFlags = 0;
2377
2378     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2379     // external symbols should go through the PLT.
2380     if (Subtarget->isTargetELF() &&
2381         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2382       OpFlags = X86II::MO_PLT;
2383     } else if (Subtarget->isPICStyleStubAny() &&
2384                (!Subtarget->getTargetTriple().isMacOSX() ||
2385                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2386       // PC-relative references to external symbols should go through $stub,
2387       // unless we're building with the leopard linker or later, which
2388       // automatically synthesizes these stubs.
2389       OpFlags = X86II::MO_DARWIN_STUB;
2390     }
2391
2392     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2393                                          OpFlags);
2394   }
2395
2396   // Returns a chain & a flag for retval copy to use.
2397   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2398   SmallVector<SDValue, 8> Ops;
2399
2400   if (!IsSibcall && isTailCall) {
2401     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2402                            DAG.getIntPtrConstant(0, true), InFlag);
2403     InFlag = Chain.getValue(1);
2404   }
2405
2406   Ops.push_back(Chain);
2407   Ops.push_back(Callee);
2408
2409   if (isTailCall)
2410     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2411
2412   // Add argument registers to the end of the list so that they are known live
2413   // into the call.
2414   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2415     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2416                                   RegsToPass[i].second.getValueType()));
2417
2418   // Add an implicit use GOT pointer in EBX.
2419   if (!isTailCall && Subtarget->isPICStyleGOT())
2420     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2421
2422   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2423   if (Is64Bit && isVarArg && !IsWin64)
2424     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2425
2426   if (InFlag.getNode())
2427     Ops.push_back(InFlag);
2428
2429   if (isTailCall) {
2430     // We used to do:
2431     //// If this is the first return lowered for this function, add the regs
2432     //// to the liveout set for the function.
2433     // This isn't right, although it's probably harmless on x86; liveouts
2434     // should be computed from returns not tail calls.  Consider a void
2435     // function making a tail call to a function returning int.
2436     return DAG.getNode(X86ISD::TC_RETURN, dl,
2437                        NodeTys, &Ops[0], Ops.size());
2438   }
2439
2440   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2441   InFlag = Chain.getValue(1);
2442
2443   // Create the CALLSEQ_END node.
2444   unsigned NumBytesForCalleeToPush;
2445   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2446     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2447   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2448     // If this is a call to a struct-return function, the callee
2449     // pops the hidden struct pointer, so we have to push it back.
2450     // This is common for Darwin/X86, Linux & Mingw32 targets.
2451     NumBytesForCalleeToPush = 4;
2452   else
2453     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2454
2455   // Returns a flag for retval copy to use.
2456   if (!IsSibcall) {
2457     Chain = DAG.getCALLSEQ_END(Chain,
2458                                DAG.getIntPtrConstant(NumBytes, true),
2459                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2460                                                      true),
2461                                InFlag);
2462     InFlag = Chain.getValue(1);
2463   }
2464
2465   // Handle result values, copying them out of physregs into vregs that we
2466   // return.
2467   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2468                          Ins, dl, DAG, InVals);
2469 }
2470
2471
2472 //===----------------------------------------------------------------------===//
2473 //                Fast Calling Convention (tail call) implementation
2474 //===----------------------------------------------------------------------===//
2475
2476 //  Like std call, callee cleans arguments, convention except that ECX is
2477 //  reserved for storing the tail called function address. Only 2 registers are
2478 //  free for argument passing (inreg). Tail call optimization is performed
2479 //  provided:
2480 //                * tailcallopt is enabled
2481 //                * caller/callee are fastcc
2482 //  On X86_64 architecture with GOT-style position independent code only local
2483 //  (within module) calls are supported at the moment.
2484 //  To keep the stack aligned according to platform abi the function
2485 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2486 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2487 //  If a tail called function callee has more arguments than the caller the
2488 //  caller needs to make sure that there is room to move the RETADDR to. This is
2489 //  achieved by reserving an area the size of the argument delta right after the
2490 //  original REtADDR, but before the saved framepointer or the spilled registers
2491 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2492 //  stack layout:
2493 //    arg1
2494 //    arg2
2495 //    RETADDR
2496 //    [ new RETADDR
2497 //      move area ]
2498 //    (possible EBP)
2499 //    ESI
2500 //    EDI
2501 //    local1 ..
2502
2503 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2504 /// for a 16 byte align requirement.
2505 unsigned
2506 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2507                                                SelectionDAG& DAG) const {
2508   MachineFunction &MF = DAG.getMachineFunction();
2509   const TargetMachine &TM = MF.getTarget();
2510   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2511   unsigned StackAlignment = TFI.getStackAlignment();
2512   uint64_t AlignMask = StackAlignment - 1;
2513   int64_t Offset = StackSize;
2514   uint64_t SlotSize = TD->getPointerSize();
2515   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2516     // Number smaller than 12 so just add the difference.
2517     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2518   } else {
2519     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2520     Offset = ((~AlignMask) & Offset) + StackAlignment +
2521       (StackAlignment-SlotSize);
2522   }
2523   return Offset;
2524 }
2525
2526 /// MatchingStackOffset - Return true if the given stack call argument is
2527 /// already available in the same position (relatively) of the caller's
2528 /// incoming argument stack.
2529 static
2530 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2531                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2532                          const X86InstrInfo *TII) {
2533   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2534   int FI = INT_MAX;
2535   if (Arg.getOpcode() == ISD::CopyFromReg) {
2536     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2537     if (!TargetRegisterInfo::isVirtualRegister(VR))
2538       return false;
2539     MachineInstr *Def = MRI->getVRegDef(VR);
2540     if (!Def)
2541       return false;
2542     if (!Flags.isByVal()) {
2543       if (!TII->isLoadFromStackSlot(Def, FI))
2544         return false;
2545     } else {
2546       unsigned Opcode = Def->getOpcode();
2547       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2548           Def->getOperand(1).isFI()) {
2549         FI = Def->getOperand(1).getIndex();
2550         Bytes = Flags.getByValSize();
2551       } else
2552         return false;
2553     }
2554   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2555     if (Flags.isByVal())
2556       // ByVal argument is passed in as a pointer but it's now being
2557       // dereferenced. e.g.
2558       // define @foo(%struct.X* %A) {
2559       //   tail call @bar(%struct.X* byval %A)
2560       // }
2561       return false;
2562     SDValue Ptr = Ld->getBasePtr();
2563     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2564     if (!FINode)
2565       return false;
2566     FI = FINode->getIndex();
2567   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2568     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2569     FI = FINode->getIndex();
2570     Bytes = Flags.getByValSize();
2571   } else
2572     return false;
2573
2574   assert(FI != INT_MAX);
2575   if (!MFI->isFixedObjectIndex(FI))
2576     return false;
2577   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2578 }
2579
2580 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2581 /// for tail call optimization. Targets which want to do tail call
2582 /// optimization should implement this function.
2583 bool
2584 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2585                                                      CallingConv::ID CalleeCC,
2586                                                      bool isVarArg,
2587                                                      bool isCalleeStructRet,
2588                                                      bool isCallerStructRet,
2589                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2590                                     const SmallVectorImpl<SDValue> &OutVals,
2591                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2592                                                      SelectionDAG& DAG) const {
2593   if (!IsTailCallConvention(CalleeCC) &&
2594       CalleeCC != CallingConv::C)
2595     return false;
2596
2597   // If -tailcallopt is specified, make fastcc functions tail-callable.
2598   const MachineFunction &MF = DAG.getMachineFunction();
2599   const Function *CallerF = DAG.getMachineFunction().getFunction();
2600   CallingConv::ID CallerCC = CallerF->getCallingConv();
2601   bool CCMatch = CallerCC == CalleeCC;
2602
2603   if (GuaranteedTailCallOpt) {
2604     if (IsTailCallConvention(CalleeCC) && CCMatch)
2605       return true;
2606     return false;
2607   }
2608
2609   // Look for obvious safe cases to perform tail call optimization that do not
2610   // require ABI changes. This is what gcc calls sibcall.
2611
2612   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2613   // emit a special epilogue.
2614   if (RegInfo->needsStackRealignment(MF))
2615     return false;
2616
2617   // Also avoid sibcall optimization if either caller or callee uses struct
2618   // return semantics.
2619   if (isCalleeStructRet || isCallerStructRet)
2620     return false;
2621
2622   // An stdcall caller is expected to clean up its arguments; the callee
2623   // isn't going to do that.
2624   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2625     return false;
2626
2627   // Do not sibcall optimize vararg calls unless all arguments are passed via
2628   // registers.
2629   if (isVarArg && !Outs.empty()) {
2630
2631     // Optimizing for varargs on Win64 is unlikely to be safe without
2632     // additional testing.
2633     if (Subtarget->isTargetWin64())
2634       return false;
2635
2636     SmallVector<CCValAssign, 16> ArgLocs;
2637     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2638                    getTargetMachine(), ArgLocs, *DAG.getContext());
2639
2640     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2641     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2642       if (!ArgLocs[i].isRegLoc())
2643         return false;
2644   }
2645
2646   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2647   // Therefore if it's not used by the call it is not safe to optimize this into
2648   // a sibcall.
2649   bool Unused = false;
2650   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2651     if (!Ins[i].Used) {
2652       Unused = true;
2653       break;
2654     }
2655   }
2656   if (Unused) {
2657     SmallVector<CCValAssign, 16> RVLocs;
2658     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2659                    getTargetMachine(), RVLocs, *DAG.getContext());
2660     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2661     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2662       CCValAssign &VA = RVLocs[i];
2663       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2664         return false;
2665     }
2666   }
2667
2668   // If the calling conventions do not match, then we'd better make sure the
2669   // results are returned in the same way as what the caller expects.
2670   if (!CCMatch) {
2671     SmallVector<CCValAssign, 16> RVLocs1;
2672     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2673                     getTargetMachine(), RVLocs1, *DAG.getContext());
2674     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2675
2676     SmallVector<CCValAssign, 16> RVLocs2;
2677     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2678                     getTargetMachine(), RVLocs2, *DAG.getContext());
2679     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2680
2681     if (RVLocs1.size() != RVLocs2.size())
2682       return false;
2683     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2684       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2685         return false;
2686       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2687         return false;
2688       if (RVLocs1[i].isRegLoc()) {
2689         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2690           return false;
2691       } else {
2692         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2693           return false;
2694       }
2695     }
2696   }
2697
2698   // If the callee takes no arguments then go on to check the results of the
2699   // call.
2700   if (!Outs.empty()) {
2701     // Check if stack adjustment is needed. For now, do not do this if any
2702     // argument is passed on the stack.
2703     SmallVector<CCValAssign, 16> ArgLocs;
2704     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2705                    getTargetMachine(), ArgLocs, *DAG.getContext());
2706
2707     // Allocate shadow area for Win64
2708     if (Subtarget->isTargetWin64()) {
2709       CCInfo.AllocateStack(32, 8);
2710     }
2711
2712     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2713     if (CCInfo.getNextStackOffset()) {
2714       MachineFunction &MF = DAG.getMachineFunction();
2715       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2716         return false;
2717
2718       // Check if the arguments are already laid out in the right way as
2719       // the caller's fixed stack objects.
2720       MachineFrameInfo *MFI = MF.getFrameInfo();
2721       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2722       const X86InstrInfo *TII =
2723         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2724       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2725         CCValAssign &VA = ArgLocs[i];
2726         SDValue Arg = OutVals[i];
2727         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2728         if (VA.getLocInfo() == CCValAssign::Indirect)
2729           return false;
2730         if (!VA.isRegLoc()) {
2731           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2732                                    MFI, MRI, TII))
2733             return false;
2734         }
2735       }
2736     }
2737
2738     // If the tailcall address may be in a register, then make sure it's
2739     // possible to register allocate for it. In 32-bit, the call address can
2740     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2741     // callee-saved registers are restored. These happen to be the same
2742     // registers used to pass 'inreg' arguments so watch out for those.
2743     if (!Subtarget->is64Bit() &&
2744         !isa<GlobalAddressSDNode>(Callee) &&
2745         !isa<ExternalSymbolSDNode>(Callee)) {
2746       unsigned NumInRegs = 0;
2747       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2748         CCValAssign &VA = ArgLocs[i];
2749         if (!VA.isRegLoc())
2750           continue;
2751         unsigned Reg = VA.getLocReg();
2752         switch (Reg) {
2753         default: break;
2754         case X86::EAX: case X86::EDX: case X86::ECX:
2755           if (++NumInRegs == 3)
2756             return false;
2757           break;
2758         }
2759       }
2760     }
2761   }
2762
2763   return true;
2764 }
2765
2766 FastISel *
2767 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2768   return X86::createFastISel(funcInfo);
2769 }
2770
2771
2772 //===----------------------------------------------------------------------===//
2773 //                           Other Lowering Hooks
2774 //===----------------------------------------------------------------------===//
2775
2776 static bool MayFoldLoad(SDValue Op) {
2777   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2778 }
2779
2780 static bool MayFoldIntoStore(SDValue Op) {
2781   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2782 }
2783
2784 static bool isTargetShuffle(unsigned Opcode) {
2785   switch(Opcode) {
2786   default: return false;
2787   case X86ISD::PSHUFD:
2788   case X86ISD::PSHUFHW:
2789   case X86ISD::PSHUFLW:
2790   case X86ISD::SHUFPD:
2791   case X86ISD::PALIGN:
2792   case X86ISD::SHUFPS:
2793   case X86ISD::MOVLHPS:
2794   case X86ISD::MOVLHPD:
2795   case X86ISD::MOVHLPS:
2796   case X86ISD::MOVLPS:
2797   case X86ISD::MOVLPD:
2798   case X86ISD::MOVSHDUP:
2799   case X86ISD::MOVSLDUP:
2800   case X86ISD::MOVDDUP:
2801   case X86ISD::MOVSS:
2802   case X86ISD::MOVSD:
2803   case X86ISD::UNPCKLPS:
2804   case X86ISD::UNPCKLPD:
2805   case X86ISD::VUNPCKLPSY:
2806   case X86ISD::VUNPCKLPDY:
2807   case X86ISD::PUNPCKLWD:
2808   case X86ISD::PUNPCKLBW:
2809   case X86ISD::PUNPCKLDQ:
2810   case X86ISD::PUNPCKLQDQ:
2811   case X86ISD::UNPCKHPS:
2812   case X86ISD::UNPCKHPD:
2813   case X86ISD::VUNPCKHPSY:
2814   case X86ISD::VUNPCKHPDY:
2815   case X86ISD::PUNPCKHWD:
2816   case X86ISD::PUNPCKHBW:
2817   case X86ISD::PUNPCKHDQ:
2818   case X86ISD::PUNPCKHQDQ:
2819   case X86ISD::VPERMILPS:
2820   case X86ISD::VPERMILPSY:
2821   case X86ISD::VPERMILPD:
2822   case X86ISD::VPERMILPDY:
2823   case X86ISD::VPERM2F128:
2824     return true;
2825   }
2826   return false;
2827 }
2828
2829 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2830                                                SDValue V1, SelectionDAG &DAG) {
2831   switch(Opc) {
2832   default: llvm_unreachable("Unknown x86 shuffle node");
2833   case X86ISD::MOVSHDUP:
2834   case X86ISD::MOVSLDUP:
2835   case X86ISD::MOVDDUP:
2836     return DAG.getNode(Opc, dl, VT, V1);
2837   }
2838
2839   return SDValue();
2840 }
2841
2842 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2843                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2844   switch(Opc) {
2845   default: llvm_unreachable("Unknown x86 shuffle node");
2846   case X86ISD::PSHUFD:
2847   case X86ISD::PSHUFHW:
2848   case X86ISD::PSHUFLW:
2849   case X86ISD::VPERMILPS:
2850   case X86ISD::VPERMILPSY:
2851   case X86ISD::VPERMILPD:
2852   case X86ISD::VPERMILPDY:
2853     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2854   }
2855
2856   return SDValue();
2857 }
2858
2859 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2860                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2861   switch(Opc) {
2862   default: llvm_unreachable("Unknown x86 shuffle node");
2863   case X86ISD::PALIGN:
2864   case X86ISD::SHUFPD:
2865   case X86ISD::SHUFPS:
2866   case X86ISD::VPERM2F128:
2867     return DAG.getNode(Opc, dl, VT, V1, V2,
2868                        DAG.getConstant(TargetMask, MVT::i8));
2869   }
2870   return SDValue();
2871 }
2872
2873 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2874                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2875   switch(Opc) {
2876   default: llvm_unreachable("Unknown x86 shuffle node");
2877   case X86ISD::MOVLHPS:
2878   case X86ISD::MOVLHPD:
2879   case X86ISD::MOVHLPS:
2880   case X86ISD::MOVLPS:
2881   case X86ISD::MOVLPD:
2882   case X86ISD::MOVSS:
2883   case X86ISD::MOVSD:
2884   case X86ISD::UNPCKLPS:
2885   case X86ISD::UNPCKLPD:
2886   case X86ISD::VUNPCKLPSY:
2887   case X86ISD::VUNPCKLPDY:
2888   case X86ISD::PUNPCKLWD:
2889   case X86ISD::PUNPCKLBW:
2890   case X86ISD::PUNPCKLDQ:
2891   case X86ISD::PUNPCKLQDQ:
2892   case X86ISD::UNPCKHPS:
2893   case X86ISD::UNPCKHPD:
2894   case X86ISD::VUNPCKHPSY:
2895   case X86ISD::VUNPCKHPDY:
2896   case X86ISD::PUNPCKHWD:
2897   case X86ISD::PUNPCKHBW:
2898   case X86ISD::PUNPCKHDQ:
2899   case X86ISD::PUNPCKHQDQ:
2900     return DAG.getNode(Opc, dl, VT, V1, V2);
2901   }
2902   return SDValue();
2903 }
2904
2905 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2906   MachineFunction &MF = DAG.getMachineFunction();
2907   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2908   int ReturnAddrIndex = FuncInfo->getRAIndex();
2909
2910   if (ReturnAddrIndex == 0) {
2911     // Set up a frame object for the return address.
2912     uint64_t SlotSize = TD->getPointerSize();
2913     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2914                                                            false);
2915     FuncInfo->setRAIndex(ReturnAddrIndex);
2916   }
2917
2918   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2919 }
2920
2921
2922 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2923                                        bool hasSymbolicDisplacement) {
2924   // Offset should fit into 32 bit immediate field.
2925   if (!isInt<32>(Offset))
2926     return false;
2927
2928   // If we don't have a symbolic displacement - we don't have any extra
2929   // restrictions.
2930   if (!hasSymbolicDisplacement)
2931     return true;
2932
2933   // FIXME: Some tweaks might be needed for medium code model.
2934   if (M != CodeModel::Small && M != CodeModel::Kernel)
2935     return false;
2936
2937   // For small code model we assume that latest object is 16MB before end of 31
2938   // bits boundary. We may also accept pretty large negative constants knowing
2939   // that all objects are in the positive half of address space.
2940   if (M == CodeModel::Small && Offset < 16*1024*1024)
2941     return true;
2942
2943   // For kernel code model we know that all object resist in the negative half
2944   // of 32bits address space. We may not accept negative offsets, since they may
2945   // be just off and we may accept pretty large positive ones.
2946   if (M == CodeModel::Kernel && Offset > 0)
2947     return true;
2948
2949   return false;
2950 }
2951
2952 /// isCalleePop - Determines whether the callee is required to pop its
2953 /// own arguments. Callee pop is necessary to support tail calls.
2954 bool X86::isCalleePop(CallingConv::ID CallingConv,
2955                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2956   if (IsVarArg)
2957     return false;
2958
2959   switch (CallingConv) {
2960   default:
2961     return false;
2962   case CallingConv::X86_StdCall:
2963     return !is64Bit;
2964   case CallingConv::X86_FastCall:
2965     return !is64Bit;
2966   case CallingConv::X86_ThisCall:
2967     return !is64Bit;
2968   case CallingConv::Fast:
2969     return TailCallOpt;
2970   case CallingConv::GHC:
2971     return TailCallOpt;
2972   }
2973 }
2974
2975 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2976 /// specific condition code, returning the condition code and the LHS/RHS of the
2977 /// comparison to make.
2978 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2979                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2980   if (!isFP) {
2981     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2982       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2983         // X > -1   -> X == 0, jump !sign.
2984         RHS = DAG.getConstant(0, RHS.getValueType());
2985         return X86::COND_NS;
2986       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2987         // X < 0   -> X == 0, jump on sign.
2988         return X86::COND_S;
2989       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2990         // X < 1   -> X <= 0
2991         RHS = DAG.getConstant(0, RHS.getValueType());
2992         return X86::COND_LE;
2993       }
2994     }
2995
2996     switch (SetCCOpcode) {
2997     default: llvm_unreachable("Invalid integer condition!");
2998     case ISD::SETEQ:  return X86::COND_E;
2999     case ISD::SETGT:  return X86::COND_G;
3000     case ISD::SETGE:  return X86::COND_GE;
3001     case ISD::SETLT:  return X86::COND_L;
3002     case ISD::SETLE:  return X86::COND_LE;
3003     case ISD::SETNE:  return X86::COND_NE;
3004     case ISD::SETULT: return X86::COND_B;
3005     case ISD::SETUGT: return X86::COND_A;
3006     case ISD::SETULE: return X86::COND_BE;
3007     case ISD::SETUGE: return X86::COND_AE;
3008     }
3009   }
3010
3011   // First determine if it is required or is profitable to flip the operands.
3012
3013   // If LHS is a foldable load, but RHS is not, flip the condition.
3014   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3015       !ISD::isNON_EXTLoad(RHS.getNode())) {
3016     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3017     std::swap(LHS, RHS);
3018   }
3019
3020   switch (SetCCOpcode) {
3021   default: break;
3022   case ISD::SETOLT:
3023   case ISD::SETOLE:
3024   case ISD::SETUGT:
3025   case ISD::SETUGE:
3026     std::swap(LHS, RHS);
3027     break;
3028   }
3029
3030   // On a floating point condition, the flags are set as follows:
3031   // ZF  PF  CF   op
3032   //  0 | 0 | 0 | X > Y
3033   //  0 | 0 | 1 | X < Y
3034   //  1 | 0 | 0 | X == Y
3035   //  1 | 1 | 1 | unordered
3036   switch (SetCCOpcode) {
3037   default: llvm_unreachable("Condcode should be pre-legalized away");
3038   case ISD::SETUEQ:
3039   case ISD::SETEQ:   return X86::COND_E;
3040   case ISD::SETOLT:              // flipped
3041   case ISD::SETOGT:
3042   case ISD::SETGT:   return X86::COND_A;
3043   case ISD::SETOLE:              // flipped
3044   case ISD::SETOGE:
3045   case ISD::SETGE:   return X86::COND_AE;
3046   case ISD::SETUGT:              // flipped
3047   case ISD::SETULT:
3048   case ISD::SETLT:   return X86::COND_B;
3049   case ISD::SETUGE:              // flipped
3050   case ISD::SETULE:
3051   case ISD::SETLE:   return X86::COND_BE;
3052   case ISD::SETONE:
3053   case ISD::SETNE:   return X86::COND_NE;
3054   case ISD::SETUO:   return X86::COND_P;
3055   case ISD::SETO:    return X86::COND_NP;
3056   case ISD::SETOEQ:
3057   case ISD::SETUNE:  return X86::COND_INVALID;
3058   }
3059 }
3060
3061 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3062 /// code. Current x86 isa includes the following FP cmov instructions:
3063 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3064 static bool hasFPCMov(unsigned X86CC) {
3065   switch (X86CC) {
3066   default:
3067     return false;
3068   case X86::COND_B:
3069   case X86::COND_BE:
3070   case X86::COND_E:
3071   case X86::COND_P:
3072   case X86::COND_A:
3073   case X86::COND_AE:
3074   case X86::COND_NE:
3075   case X86::COND_NP:
3076     return true;
3077   }
3078 }
3079
3080 /// isFPImmLegal - Returns true if the target can instruction select the
3081 /// specified FP immediate natively. If false, the legalizer will
3082 /// materialize the FP immediate as a load from a constant pool.
3083 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3084   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3085     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3086       return true;
3087   }
3088   return false;
3089 }
3090
3091 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3092 /// the specified range (L, H].
3093 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3094   return (Val < 0) || (Val >= Low && Val < Hi);
3095 }
3096
3097 /// isUndefOrInRange - Return true if every element in Mask, begining
3098 /// from position Pos and ending in Pos+Size, falls within the specified
3099 /// range (L, L+Pos]. or is undef.
3100 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3101                              int Pos, int Size, int Low, int Hi) {
3102   for (int i = Pos, e = Pos+Size; i != e; ++i)
3103     if (!isUndefOrInRange(Mask[i], Low, Hi))
3104       return false;
3105   return true;
3106 }
3107
3108 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3109 /// specified value.
3110 static bool isUndefOrEqual(int Val, int CmpVal) {
3111   if (Val < 0 || Val == CmpVal)
3112     return true;
3113   return false;
3114 }
3115
3116 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3117 /// from position Pos and ending in Pos+Size, falls within the specified
3118 /// sequential range (L, L+Pos]. or is undef.
3119 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3120                                        int Pos, int Size, int Low) {
3121   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3122     if (!isUndefOrEqual(Mask[i], Low))
3123       return false;
3124   return true;
3125 }
3126
3127 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3128 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3129 /// the second operand.
3130 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3131   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3132     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3133   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3134     return (Mask[0] < 2 && Mask[1] < 2);
3135   return false;
3136 }
3137
3138 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3139   SmallVector<int, 8> M;
3140   N->getMask(M);
3141   return ::isPSHUFDMask(M, N->getValueType(0));
3142 }
3143
3144 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3145 /// is suitable for input to PSHUFHW.
3146 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3147   if (VT != MVT::v8i16)
3148     return false;
3149
3150   // Lower quadword copied in order or undef.
3151   for (int i = 0; i != 4; ++i)
3152     if (Mask[i] >= 0 && Mask[i] != i)
3153       return false;
3154
3155   // Upper quadword shuffled.
3156   for (int i = 4; i != 8; ++i)
3157     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3158       return false;
3159
3160   return true;
3161 }
3162
3163 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3164   SmallVector<int, 8> M;
3165   N->getMask(M);
3166   return ::isPSHUFHWMask(M, N->getValueType(0));
3167 }
3168
3169 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3170 /// is suitable for input to PSHUFLW.
3171 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3172   if (VT != MVT::v8i16)
3173     return false;
3174
3175   // Upper quadword copied in order.
3176   for (int i = 4; i != 8; ++i)
3177     if (Mask[i] >= 0 && Mask[i] != i)
3178       return false;
3179
3180   // Lower quadword shuffled.
3181   for (int i = 0; i != 4; ++i)
3182     if (Mask[i] >= 4)
3183       return false;
3184
3185   return true;
3186 }
3187
3188 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3189   SmallVector<int, 8> M;
3190   N->getMask(M);
3191   return ::isPSHUFLWMask(M, N->getValueType(0));
3192 }
3193
3194 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3195 /// is suitable for input to PALIGNR.
3196 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3197                           bool hasSSSE3OrAVX) {
3198   int i, e = VT.getVectorNumElements();
3199   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3200     return false;
3201
3202   // Do not handle v2i64 / v2f64 shuffles with palignr.
3203   if (e < 4 || !hasSSSE3OrAVX)
3204     return false;
3205
3206   for (i = 0; i != e; ++i)
3207     if (Mask[i] >= 0)
3208       break;
3209
3210   // All undef, not a palignr.
3211   if (i == e)
3212     return false;
3213
3214   // Make sure we're shifting in the right direction.
3215   if (Mask[i] <= i)
3216     return false;
3217
3218   int s = Mask[i] - i;
3219
3220   // Check the rest of the elements to see if they are consecutive.
3221   for (++i; i != e; ++i) {
3222     int m = Mask[i];
3223     if (m >= 0 && m != s+i)
3224       return false;
3225   }
3226   return true;
3227 }
3228
3229 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3230 /// specifies a shuffle of elements that is suitable for input to 256-bit
3231 /// VSHUFPSY.
3232 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3233                           const X86Subtarget *Subtarget) {
3234   int NumElems = VT.getVectorNumElements();
3235
3236   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3237     return false;
3238
3239   if (NumElems != 8)
3240     return false;
3241
3242   // VSHUFPSY divides the resulting vector into 4 chunks.
3243   // The sources are also splitted into 4 chunks, and each destination
3244   // chunk must come from a different source chunk.
3245   //
3246   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3247   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3248   //
3249   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3250   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3251   //
3252   int QuarterSize = NumElems/4;
3253   int HalfSize = QuarterSize*2;
3254   for (int i = 0; i < QuarterSize; ++i)
3255     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3256       return false;
3257   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3258     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3259       return false;
3260
3261   // The mask of the second half must be the same as the first but with
3262   // the appropriate offsets. This works in the same way as VPERMILPS
3263   // works with masks.
3264   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3265     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3266       return false;
3267     int FstHalfIdx = i-HalfSize;
3268     if (Mask[FstHalfIdx] < 0)
3269       continue;
3270     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3271       return false;
3272   }
3273   for (int i = QuarterSize*3; i < NumElems; ++i) {
3274     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3275       return false;
3276     int FstHalfIdx = i-HalfSize;
3277     if (Mask[FstHalfIdx] < 0)
3278       continue;
3279     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3280       return false;
3281
3282   }
3283
3284   return true;
3285 }
3286
3287 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3288 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3289 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3290   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3291   EVT VT = SVOp->getValueType(0);
3292   int NumElems = VT.getVectorNumElements();
3293
3294   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3295          "Only supports v8i32 and v8f32 types");
3296
3297   int HalfSize = NumElems/2;
3298   unsigned Mask = 0;
3299   for (int i = 0; i != NumElems ; ++i) {
3300     if (SVOp->getMaskElt(i) < 0)
3301       continue;
3302     // The mask of the first half must be equal to the second one.
3303     unsigned Shamt = (i%HalfSize)*2;
3304     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3305     Mask |= Elt << Shamt;
3306   }
3307
3308   return Mask;
3309 }
3310
3311 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3312 /// specifies a shuffle of elements that is suitable for input to 256-bit
3313 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3314 /// version and the mask of the second half isn't binded with the first
3315 /// one.
3316 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3317                            const X86Subtarget *Subtarget) {
3318   int NumElems = VT.getVectorNumElements();
3319
3320   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3321     return false;
3322
3323   if (NumElems != 4)
3324     return false;
3325
3326   // VSHUFPSY divides the resulting vector into 4 chunks.
3327   // The sources are also splitted into 4 chunks, and each destination
3328   // chunk must come from a different source chunk.
3329   //
3330   //  SRC1 =>      X3       X2       X1       X0
3331   //  SRC2 =>      Y3       Y2       Y1       Y0
3332   //
3333   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3334   //
3335   int QuarterSize = NumElems/4;
3336   int HalfSize = QuarterSize*2;
3337   for (int i = 0; i < QuarterSize; ++i)
3338     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3339       return false;
3340   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3341     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3342       return false;
3343   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3344     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3345       return false;
3346   for (int i = QuarterSize*3; i < NumElems; ++i)
3347     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3348       return false;
3349
3350   return true;
3351 }
3352
3353 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3354 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3355 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3356   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3357   EVT VT = SVOp->getValueType(0);
3358   int NumElems = VT.getVectorNumElements();
3359
3360   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3361          "Only supports v4i64 and v4f64 types");
3362
3363   int HalfSize = NumElems/2;
3364   unsigned Mask = 0;
3365   for (int i = 0; i != NumElems ; ++i) {
3366     if (SVOp->getMaskElt(i) < 0)
3367       continue;
3368     int Elt = SVOp->getMaskElt(i) % HalfSize;
3369     Mask |= Elt << i;
3370   }
3371
3372   return Mask;
3373 }
3374
3375 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3376 /// specifies a shuffle of elements that is suitable for input to 128-bit
3377 /// SHUFPS and SHUFPD.
3378 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3379   int NumElems = VT.getVectorNumElements();
3380
3381   if (VT.getSizeInBits() != 128)
3382     return false;
3383
3384   if (NumElems != 2 && NumElems != 4)
3385     return false;
3386
3387   int Half = NumElems / 2;
3388   for (int i = 0; i < Half; ++i)
3389     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3390       return false;
3391   for (int i = Half; i < NumElems; ++i)
3392     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3393       return false;
3394
3395   return true;
3396 }
3397
3398 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3399   SmallVector<int, 8> M;
3400   N->getMask(M);
3401   return ::isSHUFPMask(M, N->getValueType(0));
3402 }
3403
3404 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3405 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3406 /// half elements to come from vector 1 (which would equal the dest.) and
3407 /// the upper half to come from vector 2.
3408 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3409   int NumElems = VT.getVectorNumElements();
3410
3411   if (NumElems != 2 && NumElems != 4)
3412     return false;
3413
3414   int Half = NumElems / 2;
3415   for (int i = 0; i < Half; ++i)
3416     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3417       return false;
3418   for (int i = Half; i < NumElems; ++i)
3419     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3420       return false;
3421   return true;
3422 }
3423
3424 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3425   SmallVector<int, 8> M;
3426   N->getMask(M);
3427   return isCommutedSHUFPMask(M, N->getValueType(0));
3428 }
3429
3430 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3431 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3432 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3433   EVT VT = N->getValueType(0);
3434   unsigned NumElems = VT.getVectorNumElements();
3435
3436   if (VT.getSizeInBits() != 128)
3437     return false;
3438
3439   if (NumElems != 4)
3440     return false;
3441
3442   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3443   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3444          isUndefOrEqual(N->getMaskElt(1), 7) &&
3445          isUndefOrEqual(N->getMaskElt(2), 2) &&
3446          isUndefOrEqual(N->getMaskElt(3), 3);
3447 }
3448
3449 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3450 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3451 /// <2, 3, 2, 3>
3452 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3453   EVT VT = N->getValueType(0);
3454   unsigned NumElems = VT.getVectorNumElements();
3455
3456   if (VT.getSizeInBits() != 128)
3457     return false;
3458
3459   if (NumElems != 4)
3460     return false;
3461
3462   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3463          isUndefOrEqual(N->getMaskElt(1), 3) &&
3464          isUndefOrEqual(N->getMaskElt(2), 2) &&
3465          isUndefOrEqual(N->getMaskElt(3), 3);
3466 }
3467
3468 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3469 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3470 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3471   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3472
3473   if (NumElems != 2 && NumElems != 4)
3474     return false;
3475
3476   for (unsigned i = 0; i < NumElems/2; ++i)
3477     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3478       return false;
3479
3480   for (unsigned i = NumElems/2; i < NumElems; ++i)
3481     if (!isUndefOrEqual(N->getMaskElt(i), i))
3482       return false;
3483
3484   return true;
3485 }
3486
3487 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3488 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3489 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3490   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3491
3492   if ((NumElems != 2 && NumElems != 4)
3493       || N->getValueType(0).getSizeInBits() > 128)
3494     return false;
3495
3496   for (unsigned i = 0; i < NumElems/2; ++i)
3497     if (!isUndefOrEqual(N->getMaskElt(i), i))
3498       return false;
3499
3500   for (unsigned i = 0; i < NumElems/2; ++i)
3501     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3502       return false;
3503
3504   return true;
3505 }
3506
3507 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3508 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3509 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3510                          bool V2IsSplat = false) {
3511   int NumElts = VT.getVectorNumElements();
3512
3513   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3514          "Unsupported vector type for unpckh");
3515
3516   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3517     return false;
3518
3519   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3520   // independently on 128-bit lanes.
3521   unsigned NumLanes = VT.getSizeInBits()/128;
3522   unsigned NumLaneElts = NumElts/NumLanes;
3523
3524   unsigned Start = 0;
3525   unsigned End = NumLaneElts;
3526   for (unsigned s = 0; s < NumLanes; ++s) {
3527     for (unsigned i = Start, j = s * NumLaneElts;
3528          i != End;
3529          i += 2, ++j) {
3530       int BitI  = Mask[i];
3531       int BitI1 = Mask[i+1];
3532       if (!isUndefOrEqual(BitI, j))
3533         return false;
3534       if (V2IsSplat) {
3535         if (!isUndefOrEqual(BitI1, NumElts))
3536           return false;
3537       } else {
3538         if (!isUndefOrEqual(BitI1, j + NumElts))
3539           return false;
3540       }
3541     }
3542     // Process the next 128 bits.
3543     Start += NumLaneElts;
3544     End += NumLaneElts;
3545   }
3546
3547   return true;
3548 }
3549
3550 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3551   SmallVector<int, 8> M;
3552   N->getMask(M);
3553   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3554 }
3555
3556 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3557 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3558 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3559                          bool V2IsSplat = false) {
3560   int NumElts = VT.getVectorNumElements();
3561
3562   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3563          "Unsupported vector type for unpckh");
3564
3565   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3566     return false;
3567
3568   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3569   // independently on 128-bit lanes.
3570   unsigned NumLanes = VT.getSizeInBits()/128;
3571   unsigned NumLaneElts = NumElts/NumLanes;
3572
3573   unsigned Start = 0;
3574   unsigned End = NumLaneElts;
3575   for (unsigned l = 0; l != NumLanes; ++l) {
3576     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3577                              i != End; i += 2, ++j) {
3578       int BitI  = Mask[i];
3579       int BitI1 = Mask[i+1];
3580       if (!isUndefOrEqual(BitI, j))
3581         return false;
3582       if (V2IsSplat) {
3583         if (isUndefOrEqual(BitI1, NumElts))
3584           return false;
3585       } else {
3586         if (!isUndefOrEqual(BitI1, j+NumElts))
3587           return false;
3588       }
3589     }
3590     // Process the next 128 bits.
3591     Start += NumLaneElts;
3592     End += NumLaneElts;
3593   }
3594   return true;
3595 }
3596
3597 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3598   SmallVector<int, 8> M;
3599   N->getMask(M);
3600   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3601 }
3602
3603 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3604 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3605 /// <0, 0, 1, 1>
3606 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3607   int NumElems = VT.getVectorNumElements();
3608   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3609     return false;
3610
3611   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3612   // FIXME: Need a better way to get rid of this, there's no latency difference
3613   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3614   // the former later. We should also remove the "_undef" special mask.
3615   if (NumElems == 4 && VT.getSizeInBits() == 256)
3616     return false;
3617
3618   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3619   // independently on 128-bit lanes.
3620   unsigned NumLanes = VT.getSizeInBits() / 128;
3621   unsigned NumLaneElts = NumElems / NumLanes;
3622
3623   for (unsigned s = 0; s < NumLanes; ++s) {
3624     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3625          i != NumLaneElts * (s + 1);
3626          i += 2, ++j) {
3627       int BitI  = Mask[i];
3628       int BitI1 = Mask[i+1];
3629
3630       if (!isUndefOrEqual(BitI, j))
3631         return false;
3632       if (!isUndefOrEqual(BitI1, j))
3633         return false;
3634     }
3635   }
3636
3637   return true;
3638 }
3639
3640 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3641   SmallVector<int, 8> M;
3642   N->getMask(M);
3643   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3644 }
3645
3646 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3647 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3648 /// <2, 2, 3, 3>
3649 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3650   int NumElems = VT.getVectorNumElements();
3651   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3652     return false;
3653
3654   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3655     int BitI  = Mask[i];
3656     int BitI1 = Mask[i+1];
3657     if (!isUndefOrEqual(BitI, j))
3658       return false;
3659     if (!isUndefOrEqual(BitI1, j))
3660       return false;
3661   }
3662   return true;
3663 }
3664
3665 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3666   SmallVector<int, 8> M;
3667   N->getMask(M);
3668   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3669 }
3670
3671 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3672 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3673 /// MOVSD, and MOVD, i.e. setting the lowest element.
3674 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3675   if (VT.getVectorElementType().getSizeInBits() < 32)
3676     return false;
3677
3678   int NumElts = VT.getVectorNumElements();
3679
3680   if (!isUndefOrEqual(Mask[0], NumElts))
3681     return false;
3682
3683   for (int i = 1; i < NumElts; ++i)
3684     if (!isUndefOrEqual(Mask[i], i))
3685       return false;
3686
3687   return true;
3688 }
3689
3690 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3691   SmallVector<int, 8> M;
3692   N->getMask(M);
3693   return ::isMOVLMask(M, N->getValueType(0));
3694 }
3695
3696 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3697 /// as permutations between 128-bit chunks or halves. As an example: this
3698 /// shuffle bellow:
3699 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3700 /// The first half comes from the second half of V1 and the second half from the
3701 /// the second half of V2.
3702 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3703                              const X86Subtarget *Subtarget) {
3704   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3705     return false;
3706
3707   // The shuffle result is divided into half A and half B. In total the two
3708   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3709   // B must come from C, D, E or F.
3710   int HalfSize = VT.getVectorNumElements()/2;
3711   bool MatchA = false, MatchB = false;
3712
3713   // Check if A comes from one of C, D, E, F.
3714   for (int Half = 0; Half < 4; ++Half) {
3715     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3716       MatchA = true;
3717       break;
3718     }
3719   }
3720
3721   // Check if B comes from one of C, D, E, F.
3722   for (int Half = 0; Half < 4; ++Half) {
3723     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3724       MatchB = true;
3725       break;
3726     }
3727   }
3728
3729   return MatchA && MatchB;
3730 }
3731
3732 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3733 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3734 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3735   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3736   EVT VT = SVOp->getValueType(0);
3737
3738   int HalfSize = VT.getVectorNumElements()/2;
3739
3740   int FstHalf = 0, SndHalf = 0;
3741   for (int i = 0; i < HalfSize; ++i) {
3742     if (SVOp->getMaskElt(i) > 0) {
3743       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3744       break;
3745     }
3746   }
3747   for (int i = HalfSize; i < HalfSize*2; ++i) {
3748     if (SVOp->getMaskElt(i) > 0) {
3749       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3750       break;
3751     }
3752   }
3753
3754   return (FstHalf | (SndHalf << 4));
3755 }
3756
3757 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3758 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3759 /// Note that VPERMIL mask matching is different depending whether theunderlying
3760 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3761 /// to the same elements of the low, but to the higher half of the source.
3762 /// In VPERMILPD the two lanes could be shuffled independently of each other
3763 /// with the same restriction that lanes can't be crossed.
3764 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3765                             const X86Subtarget *Subtarget) {
3766   int NumElts = VT.getVectorNumElements();
3767   int NumLanes = VT.getSizeInBits()/128;
3768
3769   if (!Subtarget->hasAVX())
3770     return false;
3771
3772   // Only match 256-bit with 64-bit types
3773   if (VT.getSizeInBits() != 256 || NumElts != 4)
3774     return false;
3775
3776   // The mask on the high lane is independent of the low. Both can match
3777   // any element in inside its own lane, but can't cross.
3778   int LaneSize = NumElts/NumLanes;
3779   for (int l = 0; l < NumLanes; ++l)
3780     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3781       int LaneStart = l*LaneSize;
3782       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3783         return false;
3784     }
3785
3786   return true;
3787 }
3788
3789 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3790 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3791 /// Note that VPERMIL mask matching is different depending whether theunderlying
3792 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3793 /// to the same elements of the low, but to the higher half of the source.
3794 /// In VPERMILPD the two lanes could be shuffled independently of each other
3795 /// with the same restriction that lanes can't be crossed.
3796 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3797                             const X86Subtarget *Subtarget) {
3798   unsigned NumElts = VT.getVectorNumElements();
3799   unsigned NumLanes = VT.getSizeInBits()/128;
3800
3801   if (!Subtarget->hasAVX())
3802     return false;
3803
3804   // Only match 256-bit with 32-bit types
3805   if (VT.getSizeInBits() != 256 || NumElts != 8)
3806     return false;
3807
3808   // The mask on the high lane should be the same as the low. Actually,
3809   // they can differ if any of the corresponding index in a lane is undef
3810   // and the other stays in range.
3811   int LaneSize = NumElts/NumLanes;
3812   for (int i = 0; i < LaneSize; ++i) {
3813     int HighElt = i+LaneSize;
3814     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3815     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3816
3817     if (!HighValid || !LowValid)
3818       return false;
3819     if (Mask[i] < 0 || Mask[HighElt] < 0)
3820       continue;
3821     if (Mask[HighElt]-Mask[i] != LaneSize)
3822       return false;
3823   }
3824
3825   return true;
3826 }
3827
3828 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3829 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3830 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3831   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3832   EVT VT = SVOp->getValueType(0);
3833
3834   int NumElts = VT.getVectorNumElements();
3835   int NumLanes = VT.getSizeInBits()/128;
3836   int LaneSize = NumElts/NumLanes;
3837
3838   // Although the mask is equal for both lanes do it twice to get the cases
3839   // where a mask will match because the same mask element is undef on the
3840   // first half but valid on the second. This would get pathological cases
3841   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3842   unsigned Mask = 0;
3843   for (int l = 0; l < NumLanes; ++l) {
3844     for (int i = 0; i < LaneSize; ++i) {
3845       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3846       if (MaskElt < 0)
3847         continue;
3848       if (MaskElt >= LaneSize)
3849         MaskElt -= LaneSize;
3850       Mask |= MaskElt << (i*2);
3851     }
3852   }
3853
3854   return Mask;
3855 }
3856
3857 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3858 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3859 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3860   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3861   EVT VT = SVOp->getValueType(0);
3862
3863   int NumElts = VT.getVectorNumElements();
3864   int NumLanes = VT.getSizeInBits()/128;
3865
3866   unsigned Mask = 0;
3867   int LaneSize = NumElts/NumLanes;
3868   for (int l = 0; l < NumLanes; ++l)
3869     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3870       int MaskElt = SVOp->getMaskElt(i);
3871       if (MaskElt < 0)
3872         continue;
3873       Mask |= (MaskElt-l*LaneSize) << i;
3874     }
3875
3876   return Mask;
3877 }
3878
3879 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3880 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3881 /// element of vector 2 and the other elements to come from vector 1 in order.
3882 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3883                                bool V2IsSplat = false, bool V2IsUndef = false) {
3884   int NumOps = VT.getVectorNumElements();
3885   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3886     return false;
3887
3888   if (!isUndefOrEqual(Mask[0], 0))
3889     return false;
3890
3891   for (int i = 1; i < NumOps; ++i)
3892     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3893           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3894           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3895       return false;
3896
3897   return true;
3898 }
3899
3900 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3901                            bool V2IsUndef = false) {
3902   SmallVector<int, 8> M;
3903   N->getMask(M);
3904   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3905 }
3906
3907 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3909 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3910 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3911                          const X86Subtarget *Subtarget) {
3912   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3913     return false;
3914
3915   // The second vector must be undef
3916   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3917     return false;
3918
3919   EVT VT = N->getValueType(0);
3920   unsigned NumElems = VT.getVectorNumElements();
3921
3922   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3923       (VT.getSizeInBits() == 256 && NumElems != 8))
3924     return false;
3925
3926   // "i+1" is the value the indexed mask element must have
3927   for (unsigned i = 0; i < NumElems; i += 2)
3928     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3929         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3930       return false;
3931
3932   return true;
3933 }
3934
3935 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3937 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3938 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3939                          const X86Subtarget *Subtarget) {
3940   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3941     return false;
3942
3943   // The second vector must be undef
3944   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3945     return false;
3946
3947   EVT VT = N->getValueType(0);
3948   unsigned NumElems = VT.getVectorNumElements();
3949
3950   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3951       (VT.getSizeInBits() == 256 && NumElems != 8))
3952     return false;
3953
3954   // "i" is the value the indexed mask element must have
3955   for (unsigned i = 0; i < NumElems; i += 2)
3956     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3957         !isUndefOrEqual(N->getMaskElt(i+1), i))
3958       return false;
3959
3960   return true;
3961 }
3962
3963 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3964 /// specifies a shuffle of elements that is suitable for input to 256-bit
3965 /// version of MOVDDUP.
3966 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3967                            const X86Subtarget *Subtarget) {
3968   EVT VT = N->getValueType(0);
3969   int NumElts = VT.getVectorNumElements();
3970   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3971
3972   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3973       !V2IsUndef || NumElts != 4)
3974     return false;
3975
3976   for (int i = 0; i != NumElts/2; ++i)
3977     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3978       return false;
3979   for (int i = NumElts/2; i != NumElts; ++i)
3980     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3981       return false;
3982   return true;
3983 }
3984
3985 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3986 /// specifies a shuffle of elements that is suitable for input to 128-bit
3987 /// version of MOVDDUP.
3988 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3989   EVT VT = N->getValueType(0);
3990
3991   if (VT.getSizeInBits() != 128)
3992     return false;
3993
3994   int e = VT.getVectorNumElements() / 2;
3995   for (int i = 0; i < e; ++i)
3996     if (!isUndefOrEqual(N->getMaskElt(i), i))
3997       return false;
3998   for (int i = 0; i < e; ++i)
3999     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4000       return false;
4001   return true;
4002 }
4003
4004 /// isVEXTRACTF128Index - Return true if the specified
4005 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4006 /// suitable for input to VEXTRACTF128.
4007 bool X86::isVEXTRACTF128Index(SDNode *N) {
4008   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4009     return false;
4010
4011   // The index should be aligned on a 128-bit boundary.
4012   uint64_t Index =
4013     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4014
4015   unsigned VL = N->getValueType(0).getVectorNumElements();
4016   unsigned VBits = N->getValueType(0).getSizeInBits();
4017   unsigned ElSize = VBits / VL;
4018   bool Result = (Index * ElSize) % 128 == 0;
4019
4020   return Result;
4021 }
4022
4023 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4024 /// operand specifies a subvector insert that is suitable for input to
4025 /// VINSERTF128.
4026 bool X86::isVINSERTF128Index(SDNode *N) {
4027   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4028     return false;
4029
4030   // The index should be aligned on a 128-bit boundary.
4031   uint64_t Index =
4032     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4033
4034   unsigned VL = N->getValueType(0).getVectorNumElements();
4035   unsigned VBits = N->getValueType(0).getSizeInBits();
4036   unsigned ElSize = VBits / VL;
4037   bool Result = (Index * ElSize) % 128 == 0;
4038
4039   return Result;
4040 }
4041
4042 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4043 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4044 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4046   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4047
4048   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4049   unsigned Mask = 0;
4050   for (int i = 0; i < NumOperands; ++i) {
4051     int Val = SVOp->getMaskElt(NumOperands-i-1);
4052     if (Val < 0) Val = 0;
4053     if (Val >= NumOperands) Val -= NumOperands;
4054     Mask |= Val;
4055     if (i != NumOperands - 1)
4056       Mask <<= Shift;
4057   }
4058   return Mask;
4059 }
4060
4061 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4062 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4063 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4064   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4065   unsigned Mask = 0;
4066   // 8 nodes, but we only care about the last 4.
4067   for (unsigned i = 7; i >= 4; --i) {
4068     int Val = SVOp->getMaskElt(i);
4069     if (Val >= 0)
4070       Mask |= (Val - 4);
4071     if (i != 4)
4072       Mask <<= 2;
4073   }
4074   return Mask;
4075 }
4076
4077 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4078 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4079 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4080   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4081   unsigned Mask = 0;
4082   // 8 nodes, but we only care about the first 4.
4083   for (int i = 3; i >= 0; --i) {
4084     int Val = SVOp->getMaskElt(i);
4085     if (Val >= 0)
4086       Mask |= Val;
4087     if (i != 0)
4088       Mask <<= 2;
4089   }
4090   return Mask;
4091 }
4092
4093 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4094 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4095 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4097   EVT VVT = N->getValueType(0);
4098   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4099   int Val = 0;
4100
4101   unsigned i, e;
4102   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4103     Val = SVOp->getMaskElt(i);
4104     if (Val >= 0)
4105       break;
4106   }
4107   assert(Val - i > 0 && "PALIGNR imm should be positive");
4108   return (Val - i) * EltSize;
4109 }
4110
4111 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4112 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4113 /// instructions.
4114 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4115   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4116     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4117
4118   uint64_t Index =
4119     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4120
4121   EVT VecVT = N->getOperand(0).getValueType();
4122   EVT ElVT = VecVT.getVectorElementType();
4123
4124   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4125   return Index / NumElemsPerChunk;
4126 }
4127
4128 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4129 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4130 /// instructions.
4131 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4132   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4133     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4134
4135   uint64_t Index =
4136     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4137
4138   EVT VecVT = N->getValueType(0);
4139   EVT ElVT = VecVT.getVectorElementType();
4140
4141   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4142   return Index / NumElemsPerChunk;
4143 }
4144
4145 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4146 /// constant +0.0.
4147 bool X86::isZeroNode(SDValue Elt) {
4148   return ((isa<ConstantSDNode>(Elt) &&
4149            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4150           (isa<ConstantFPSDNode>(Elt) &&
4151            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4152 }
4153
4154 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4155 /// their permute mask.
4156 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4157                                     SelectionDAG &DAG) {
4158   EVT VT = SVOp->getValueType(0);
4159   unsigned NumElems = VT.getVectorNumElements();
4160   SmallVector<int, 8> MaskVec;
4161
4162   for (unsigned i = 0; i != NumElems; ++i) {
4163     int idx = SVOp->getMaskElt(i);
4164     if (idx < 0)
4165       MaskVec.push_back(idx);
4166     else if (idx < (int)NumElems)
4167       MaskVec.push_back(idx + NumElems);
4168     else
4169       MaskVec.push_back(idx - NumElems);
4170   }
4171   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4172                               SVOp->getOperand(0), &MaskVec[0]);
4173 }
4174
4175 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4176 /// the two vector operands have swapped position.
4177 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4178   unsigned NumElems = VT.getVectorNumElements();
4179   for (unsigned i = 0; i != NumElems; ++i) {
4180     int idx = Mask[i];
4181     if (idx < 0)
4182       continue;
4183     else if (idx < (int)NumElems)
4184       Mask[i] = idx + NumElems;
4185     else
4186       Mask[i] = idx - NumElems;
4187   }
4188 }
4189
4190 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4191 /// match movhlps. The lower half elements should come from upper half of
4192 /// V1 (and in order), and the upper half elements should come from the upper
4193 /// half of V2 (and in order).
4194 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4195   EVT VT = Op->getValueType(0);
4196   if (VT.getSizeInBits() != 128)
4197     return false;
4198   if (VT.getVectorNumElements() != 4)
4199     return false;
4200   for (unsigned i = 0, e = 2; i != e; ++i)
4201     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4202       return false;
4203   for (unsigned i = 2; i != 4; ++i)
4204     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4205       return false;
4206   return true;
4207 }
4208
4209 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4210 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4211 /// required.
4212 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4213   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4214     return false;
4215   N = N->getOperand(0).getNode();
4216   if (!ISD::isNON_EXTLoad(N))
4217     return false;
4218   if (LD)
4219     *LD = cast<LoadSDNode>(N);
4220   return true;
4221 }
4222
4223 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4224 /// match movlp{s|d}. The lower half elements should come from lower half of
4225 /// V1 (and in order), and the upper half elements should come from the upper
4226 /// half of V2 (and in order). And since V1 will become the source of the
4227 /// MOVLP, it must be either a vector load or a scalar load to vector.
4228 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4229                                ShuffleVectorSDNode *Op) {
4230   EVT VT = Op->getValueType(0);
4231   if (VT.getSizeInBits() != 128)
4232     return false;
4233
4234   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4235     return false;
4236   // Is V2 is a vector load, don't do this transformation. We will try to use
4237   // load folding shufps op.
4238   if (ISD::isNON_EXTLoad(V2))
4239     return false;
4240
4241   unsigned NumElems = VT.getVectorNumElements();
4242
4243   if (NumElems != 2 && NumElems != 4)
4244     return false;
4245   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4246     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4247       return false;
4248   for (unsigned i = NumElems/2; i != NumElems; ++i)
4249     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4250       return false;
4251   return true;
4252 }
4253
4254 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4255 /// all the same.
4256 static bool isSplatVector(SDNode *N) {
4257   if (N->getOpcode() != ISD::BUILD_VECTOR)
4258     return false;
4259
4260   SDValue SplatValue = N->getOperand(0);
4261   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4262     if (N->getOperand(i) != SplatValue)
4263       return false;
4264   return true;
4265 }
4266
4267 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4268 /// to an zero vector.
4269 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4270 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4271   SDValue V1 = N->getOperand(0);
4272   SDValue V2 = N->getOperand(1);
4273   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4274   for (unsigned i = 0; i != NumElems; ++i) {
4275     int Idx = N->getMaskElt(i);
4276     if (Idx >= (int)NumElems) {
4277       unsigned Opc = V2.getOpcode();
4278       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4279         continue;
4280       if (Opc != ISD::BUILD_VECTOR ||
4281           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4282         return false;
4283     } else if (Idx >= 0) {
4284       unsigned Opc = V1.getOpcode();
4285       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4286         continue;
4287       if (Opc != ISD::BUILD_VECTOR ||
4288           !X86::isZeroNode(V1.getOperand(Idx)))
4289         return false;
4290     }
4291   }
4292   return true;
4293 }
4294
4295 /// getZeroVector - Returns a vector of specified type with all zero elements.
4296 ///
4297 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4298                              DebugLoc dl) {
4299   assert(VT.isVector() && "Expected a vector type");
4300
4301   // Always build SSE zero vectors as <4 x i32> bitcasted
4302   // to their dest type. This ensures they get CSE'd.
4303   SDValue Vec;
4304   if (VT.getSizeInBits() == 128) {  // SSE
4305     if (HasXMMInt) {  // SSE2
4306       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4307       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4308     } else { // SSE1
4309       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4310       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4311     }
4312   } else if (VT.getSizeInBits() == 256) { // AVX
4313     // 256-bit logic and arithmetic instructions in AVX are
4314     // all floating-point, no support for integer ops. Default
4315     // to emitting fp zeroed vectors then.
4316     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4317     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4318     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4319   }
4320   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4321 }
4322
4323 /// getOnesVector - Returns a vector of specified type with all bits set.
4324 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4325 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4326 /// original type, ensuring they get CSE'd.
4327 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4328   assert(VT.isVector() && "Expected a vector type");
4329   assert((VT.is128BitVector() || VT.is256BitVector())
4330          && "Expected a 128-bit or 256-bit vector type");
4331
4332   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4333   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4334                             Cst, Cst, Cst, Cst);
4335
4336   if (VT.is256BitVector()) {
4337     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4338                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4339     Vec = Insert128BitVector(InsV, Vec,
4340                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4341   }
4342
4343   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4344 }
4345
4346 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4347 /// that point to V2 points to its first element.
4348 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4349   EVT VT = SVOp->getValueType(0);
4350   unsigned NumElems = VT.getVectorNumElements();
4351
4352   bool Changed = false;
4353   SmallVector<int, 8> MaskVec;
4354   SVOp->getMask(MaskVec);
4355
4356   for (unsigned i = 0; i != NumElems; ++i) {
4357     if (MaskVec[i] > (int)NumElems) {
4358       MaskVec[i] = NumElems;
4359       Changed = true;
4360     }
4361   }
4362   if (Changed)
4363     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4364                                 SVOp->getOperand(1), &MaskVec[0]);
4365   return SDValue(SVOp, 0);
4366 }
4367
4368 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4369 /// operation of specified width.
4370 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4371                        SDValue V2) {
4372   unsigned NumElems = VT.getVectorNumElements();
4373   SmallVector<int, 8> Mask;
4374   Mask.push_back(NumElems);
4375   for (unsigned i = 1; i != NumElems; ++i)
4376     Mask.push_back(i);
4377   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4378 }
4379
4380 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4381 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4382                           SDValue V2) {
4383   unsigned NumElems = VT.getVectorNumElements();
4384   SmallVector<int, 8> Mask;
4385   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4386     Mask.push_back(i);
4387     Mask.push_back(i + NumElems);
4388   }
4389   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4390 }
4391
4392 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4393 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4394                           SDValue V2) {
4395   unsigned NumElems = VT.getVectorNumElements();
4396   unsigned Half = NumElems/2;
4397   SmallVector<int, 8> Mask;
4398   for (unsigned i = 0; i != Half; ++i) {
4399     Mask.push_back(i + Half);
4400     Mask.push_back(i + NumElems + Half);
4401   }
4402   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4403 }
4404
4405 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4406 // a generic shuffle instruction because the target has no such instructions.
4407 // Generate shuffles which repeat i16 and i8 several times until they can be
4408 // represented by v4f32 and then be manipulated by target suported shuffles.
4409 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4410   EVT VT = V.getValueType();
4411   int NumElems = VT.getVectorNumElements();
4412   DebugLoc dl = V.getDebugLoc();
4413
4414   while (NumElems > 4) {
4415     if (EltNo < NumElems/2) {
4416       V = getUnpackl(DAG, dl, VT, V, V);
4417     } else {
4418       V = getUnpackh(DAG, dl, VT, V, V);
4419       EltNo -= NumElems/2;
4420     }
4421     NumElems >>= 1;
4422   }
4423   return V;
4424 }
4425
4426 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4427 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4428   EVT VT = V.getValueType();
4429   DebugLoc dl = V.getDebugLoc();
4430   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4431          && "Vector size not supported");
4432
4433   if (VT.getSizeInBits() == 128) {
4434     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4435     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4436     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4437                              &SplatMask[0]);
4438   } else {
4439     // To use VPERMILPS to splat scalars, the second half of indicies must
4440     // refer to the higher part, which is a duplication of the lower one,
4441     // because VPERMILPS can only handle in-lane permutations.
4442     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4443                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4444
4445     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4446     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4447                              &SplatMask[0]);
4448   }
4449
4450   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4451 }
4452
4453 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4454 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4455   EVT SrcVT = SV->getValueType(0);
4456   SDValue V1 = SV->getOperand(0);
4457   DebugLoc dl = SV->getDebugLoc();
4458
4459   int EltNo = SV->getSplatIndex();
4460   int NumElems = SrcVT.getVectorNumElements();
4461   unsigned Size = SrcVT.getSizeInBits();
4462
4463   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4464           "Unknown how to promote splat for type");
4465
4466   // Extract the 128-bit part containing the splat element and update
4467   // the splat element index when it refers to the higher register.
4468   if (Size == 256) {
4469     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4470     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4471     if (Idx > 0)
4472       EltNo -= NumElems/2;
4473   }
4474
4475   // All i16 and i8 vector types can't be used directly by a generic shuffle
4476   // instruction because the target has no such instruction. Generate shuffles
4477   // which repeat i16 and i8 several times until they fit in i32, and then can
4478   // be manipulated by target suported shuffles.
4479   EVT EltVT = SrcVT.getVectorElementType();
4480   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4481     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4482
4483   // Recreate the 256-bit vector and place the same 128-bit vector
4484   // into the low and high part. This is necessary because we want
4485   // to use VPERM* to shuffle the vectors
4486   if (Size == 256) {
4487     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4488                          DAG.getConstant(0, MVT::i32), DAG, dl);
4489     V1 = Insert128BitVector(InsV, V1,
4490                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4491   }
4492
4493   return getLegalSplat(DAG, V1, EltNo);
4494 }
4495
4496 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4497 /// vector of zero or undef vector.  This produces a shuffle where the low
4498 /// element of V2 is swizzled into the zero/undef vector, landing at element
4499 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4500 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4501                                            bool isZero, bool HasXMMInt,
4502                                            SelectionDAG &DAG) {
4503   EVT VT = V2.getValueType();
4504   SDValue V1 = isZero
4505     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4506   unsigned NumElems = VT.getVectorNumElements();
4507   SmallVector<int, 16> MaskVec;
4508   for (unsigned i = 0; i != NumElems; ++i)
4509     // If this is the insertion idx, put the low elt of V2 here.
4510     MaskVec.push_back(i == Idx ? NumElems : i);
4511   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4512 }
4513
4514 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4515 /// element of the result of the vector shuffle.
4516 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4517                                    unsigned Depth) {
4518   if (Depth == 6)
4519     return SDValue();  // Limit search depth.
4520
4521   SDValue V = SDValue(N, 0);
4522   EVT VT = V.getValueType();
4523   unsigned Opcode = V.getOpcode();
4524
4525   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4526   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4527     Index = SV->getMaskElt(Index);
4528
4529     if (Index < 0)
4530       return DAG.getUNDEF(VT.getVectorElementType());
4531
4532     int NumElems = VT.getVectorNumElements();
4533     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4534     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4535   }
4536
4537   // Recurse into target specific vector shuffles to find scalars.
4538   if (isTargetShuffle(Opcode)) {
4539     int NumElems = VT.getVectorNumElements();
4540     SmallVector<unsigned, 16> ShuffleMask;
4541     SDValue ImmN;
4542
4543     switch(Opcode) {
4544     case X86ISD::SHUFPS:
4545     case X86ISD::SHUFPD:
4546       ImmN = N->getOperand(N->getNumOperands()-1);
4547       DecodeSHUFPSMask(NumElems,
4548                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4549                        ShuffleMask);
4550       break;
4551     case X86ISD::PUNPCKHBW:
4552     case X86ISD::PUNPCKHWD:
4553     case X86ISD::PUNPCKHDQ:
4554     case X86ISD::PUNPCKHQDQ:
4555       DecodePUNPCKHMask(NumElems, ShuffleMask);
4556       break;
4557     case X86ISD::UNPCKHPS:
4558     case X86ISD::UNPCKHPD:
4559     case X86ISD::VUNPCKHPSY:
4560     case X86ISD::VUNPCKHPDY:
4561       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4562       break;
4563     case X86ISD::PUNPCKLBW:
4564     case X86ISD::PUNPCKLWD:
4565     case X86ISD::PUNPCKLDQ:
4566     case X86ISD::PUNPCKLQDQ:
4567       DecodePUNPCKLMask(VT, ShuffleMask);
4568       break;
4569     case X86ISD::UNPCKLPS:
4570     case X86ISD::UNPCKLPD:
4571     case X86ISD::VUNPCKLPSY:
4572     case X86ISD::VUNPCKLPDY:
4573       DecodeUNPCKLPMask(VT, ShuffleMask);
4574       break;
4575     case X86ISD::MOVHLPS:
4576       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4577       break;
4578     case X86ISD::MOVLHPS:
4579       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4580       break;
4581     case X86ISD::PSHUFD:
4582       ImmN = N->getOperand(N->getNumOperands()-1);
4583       DecodePSHUFMask(NumElems,
4584                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4585                       ShuffleMask);
4586       break;
4587     case X86ISD::PSHUFHW:
4588       ImmN = N->getOperand(N->getNumOperands()-1);
4589       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4590                         ShuffleMask);
4591       break;
4592     case X86ISD::PSHUFLW:
4593       ImmN = N->getOperand(N->getNumOperands()-1);
4594       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4595                         ShuffleMask);
4596       break;
4597     case X86ISD::MOVSS:
4598     case X86ISD::MOVSD: {
4599       // The index 0 always comes from the first element of the second source,
4600       // this is why MOVSS and MOVSD are used in the first place. The other
4601       // elements come from the other positions of the first source vector.
4602       unsigned OpNum = (Index == 0) ? 1 : 0;
4603       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4604                                  Depth+1);
4605     }
4606     case X86ISD::VPERMILPS:
4607       ImmN = N->getOperand(N->getNumOperands()-1);
4608       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4609                         ShuffleMask);
4610       break;
4611     case X86ISD::VPERMILPSY:
4612       ImmN = N->getOperand(N->getNumOperands()-1);
4613       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4614                         ShuffleMask);
4615       break;
4616     case X86ISD::VPERMILPD:
4617       ImmN = N->getOperand(N->getNumOperands()-1);
4618       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4619                         ShuffleMask);
4620       break;
4621     case X86ISD::VPERMILPDY:
4622       ImmN = N->getOperand(N->getNumOperands()-1);
4623       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4624                         ShuffleMask);
4625       break;
4626     case X86ISD::VPERM2F128:
4627       ImmN = N->getOperand(N->getNumOperands()-1);
4628       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4629                            ShuffleMask);
4630       break;
4631     case X86ISD::MOVDDUP:
4632     case X86ISD::MOVLHPD:
4633     case X86ISD::MOVLPD:
4634     case X86ISD::MOVLPS:
4635     case X86ISD::MOVSHDUP:
4636     case X86ISD::MOVSLDUP:
4637     case X86ISD::PALIGN:
4638       return SDValue(); // Not yet implemented.
4639     default:
4640       assert(0 && "unknown target shuffle node");
4641       return SDValue();
4642     }
4643
4644     Index = ShuffleMask[Index];
4645     if (Index < 0)
4646       return DAG.getUNDEF(VT.getVectorElementType());
4647
4648     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4649     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4650                                Depth+1);
4651   }
4652
4653   // Actual nodes that may contain scalar elements
4654   if (Opcode == ISD::BITCAST) {
4655     V = V.getOperand(0);
4656     EVT SrcVT = V.getValueType();
4657     unsigned NumElems = VT.getVectorNumElements();
4658
4659     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4660       return SDValue();
4661   }
4662
4663   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4664     return (Index == 0) ? V.getOperand(0)
4665                           : DAG.getUNDEF(VT.getVectorElementType());
4666
4667   if (V.getOpcode() == ISD::BUILD_VECTOR)
4668     return V.getOperand(Index);
4669
4670   return SDValue();
4671 }
4672
4673 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4674 /// shuffle operation which come from a consecutively from a zero. The
4675 /// search can start in two different directions, from left or right.
4676 static
4677 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4678                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4679   int i = 0;
4680
4681   while (i < NumElems) {
4682     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4683     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4684     if (!(Elt.getNode() &&
4685          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4686       break;
4687     ++i;
4688   }
4689
4690   return i;
4691 }
4692
4693 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4694 /// MaskE correspond consecutively to elements from one of the vector operands,
4695 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4696 static
4697 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4698                               int OpIdx, int NumElems, unsigned &OpNum) {
4699   bool SeenV1 = false;
4700   bool SeenV2 = false;
4701
4702   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4703     int Idx = SVOp->getMaskElt(i);
4704     // Ignore undef indicies
4705     if (Idx < 0)
4706       continue;
4707
4708     if (Idx < NumElems)
4709       SeenV1 = true;
4710     else
4711       SeenV2 = true;
4712
4713     // Only accept consecutive elements from the same vector
4714     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4715       return false;
4716   }
4717
4718   OpNum = SeenV1 ? 0 : 1;
4719   return true;
4720 }
4721
4722 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4723 /// logical left shift of a vector.
4724 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4725                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4726   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4727   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4728               false /* check zeros from right */, DAG);
4729   unsigned OpSrc;
4730
4731   if (!NumZeros)
4732     return false;
4733
4734   // Considering the elements in the mask that are not consecutive zeros,
4735   // check if they consecutively come from only one of the source vectors.
4736   //
4737   //               V1 = {X, A, B, C}     0
4738   //                         \  \  \    /
4739   //   vector_shuffle V1, V2 <1, 2, 3, X>
4740   //
4741   if (!isShuffleMaskConsecutive(SVOp,
4742             0,                   // Mask Start Index
4743             NumElems-NumZeros-1, // Mask End Index
4744             NumZeros,            // Where to start looking in the src vector
4745             NumElems,            // Number of elements in vector
4746             OpSrc))              // Which source operand ?
4747     return false;
4748
4749   isLeft = false;
4750   ShAmt = NumZeros;
4751   ShVal = SVOp->getOperand(OpSrc);
4752   return true;
4753 }
4754
4755 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4756 /// logical left shift of a vector.
4757 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4758                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4759   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4760   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4761               true /* check zeros from left */, DAG);
4762   unsigned OpSrc;
4763
4764   if (!NumZeros)
4765     return false;
4766
4767   // Considering the elements in the mask that are not consecutive zeros,
4768   // check if they consecutively come from only one of the source vectors.
4769   //
4770   //                           0    { A, B, X, X } = V2
4771   //                          / \    /  /
4772   //   vector_shuffle V1, V2 <X, X, 4, 5>
4773   //
4774   if (!isShuffleMaskConsecutive(SVOp,
4775             NumZeros,     // Mask Start Index
4776             NumElems-1,   // Mask End Index
4777             0,            // Where to start looking in the src vector
4778             NumElems,     // Number of elements in vector
4779             OpSrc))       // Which source operand ?
4780     return false;
4781
4782   isLeft = true;
4783   ShAmt = NumZeros;
4784   ShVal = SVOp->getOperand(OpSrc);
4785   return true;
4786 }
4787
4788 /// isVectorShift - Returns true if the shuffle can be implemented as a
4789 /// logical left or right shift of a vector.
4790 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4791                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4792   // Although the logic below support any bitwidth size, there are no
4793   // shift instructions which handle more than 128-bit vectors.
4794   if (SVOp->getValueType(0).getSizeInBits() > 128)
4795     return false;
4796
4797   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4798       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4799     return true;
4800
4801   return false;
4802 }
4803
4804 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4805 ///
4806 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4807                                        unsigned NumNonZero, unsigned NumZero,
4808                                        SelectionDAG &DAG,
4809                                        const TargetLowering &TLI) {
4810   if (NumNonZero > 8)
4811     return SDValue();
4812
4813   DebugLoc dl = Op.getDebugLoc();
4814   SDValue V(0, 0);
4815   bool First = true;
4816   for (unsigned i = 0; i < 16; ++i) {
4817     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4818     if (ThisIsNonZero && First) {
4819       if (NumZero)
4820         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4821       else
4822         V = DAG.getUNDEF(MVT::v8i16);
4823       First = false;
4824     }
4825
4826     if ((i & 1) != 0) {
4827       SDValue ThisElt(0, 0), LastElt(0, 0);
4828       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4829       if (LastIsNonZero) {
4830         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4831                               MVT::i16, Op.getOperand(i-1));
4832       }
4833       if (ThisIsNonZero) {
4834         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4835         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4836                               ThisElt, DAG.getConstant(8, MVT::i8));
4837         if (LastIsNonZero)
4838           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4839       } else
4840         ThisElt = LastElt;
4841
4842       if (ThisElt.getNode())
4843         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4844                         DAG.getIntPtrConstant(i/2));
4845     }
4846   }
4847
4848   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4849 }
4850
4851 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4852 ///
4853 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4854                                      unsigned NumNonZero, unsigned NumZero,
4855                                      SelectionDAG &DAG,
4856                                      const TargetLowering &TLI) {
4857   if (NumNonZero > 4)
4858     return SDValue();
4859
4860   DebugLoc dl = Op.getDebugLoc();
4861   SDValue V(0, 0);
4862   bool First = true;
4863   for (unsigned i = 0; i < 8; ++i) {
4864     bool isNonZero = (NonZeros & (1 << i)) != 0;
4865     if (isNonZero) {
4866       if (First) {
4867         if (NumZero)
4868           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4869         else
4870           V = DAG.getUNDEF(MVT::v8i16);
4871         First = false;
4872       }
4873       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4874                       MVT::v8i16, V, Op.getOperand(i),
4875                       DAG.getIntPtrConstant(i));
4876     }
4877   }
4878
4879   return V;
4880 }
4881
4882 /// getVShift - Return a vector logical shift node.
4883 ///
4884 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4885                          unsigned NumBits, SelectionDAG &DAG,
4886                          const TargetLowering &TLI, DebugLoc dl) {
4887   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4888   EVT ShVT = MVT::v2i64;
4889   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4890   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4891   return DAG.getNode(ISD::BITCAST, dl, VT,
4892                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4893                              DAG.getConstant(NumBits,
4894                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4895 }
4896
4897 SDValue
4898 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4899                                           SelectionDAG &DAG) const {
4900
4901   // Check if the scalar load can be widened into a vector load. And if
4902   // the address is "base + cst" see if the cst can be "absorbed" into
4903   // the shuffle mask.
4904   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4905     SDValue Ptr = LD->getBasePtr();
4906     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4907       return SDValue();
4908     EVT PVT = LD->getValueType(0);
4909     if (PVT != MVT::i32 && PVT != MVT::f32)
4910       return SDValue();
4911
4912     int FI = -1;
4913     int64_t Offset = 0;
4914     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4915       FI = FINode->getIndex();
4916       Offset = 0;
4917     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4918                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4919       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4920       Offset = Ptr.getConstantOperandVal(1);
4921       Ptr = Ptr.getOperand(0);
4922     } else {
4923       return SDValue();
4924     }
4925
4926     // FIXME: 256-bit vector instructions don't require a strict alignment,
4927     // improve this code to support it better.
4928     unsigned RequiredAlign = VT.getSizeInBits()/8;
4929     SDValue Chain = LD->getChain();
4930     // Make sure the stack object alignment is at least 16 or 32.
4931     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4932     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4933       if (MFI->isFixedObjectIndex(FI)) {
4934         // Can't change the alignment. FIXME: It's possible to compute
4935         // the exact stack offset and reference FI + adjust offset instead.
4936         // If someone *really* cares about this. That's the way to implement it.
4937         return SDValue();
4938       } else {
4939         MFI->setObjectAlignment(FI, RequiredAlign);
4940       }
4941     }
4942
4943     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4944     // Ptr + (Offset & ~15).
4945     if (Offset < 0)
4946       return SDValue();
4947     if ((Offset % RequiredAlign) & 3)
4948       return SDValue();
4949     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4950     if (StartOffset)
4951       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4952                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4953
4954     int EltNo = (Offset - StartOffset) >> 2;
4955     int NumElems = VT.getVectorNumElements();
4956
4957     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4958     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4959     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4960                              LD->getPointerInfo().getWithOffset(StartOffset),
4961                              false, false, 0);
4962
4963     // Canonicalize it to a v4i32 or v8i32 shuffle.
4964     SmallVector<int, 8> Mask;
4965     for (int i = 0; i < NumElems; ++i)
4966       Mask.push_back(EltNo);
4967
4968     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4969     return DAG.getNode(ISD::BITCAST, dl, NVT,
4970                        DAG.getVectorShuffle(CanonVT, dl, V1,
4971                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4972   }
4973
4974   return SDValue();
4975 }
4976
4977 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4978 /// vector of type 'VT', see if the elements can be replaced by a single large
4979 /// load which has the same value as a build_vector whose operands are 'elts'.
4980 ///
4981 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4982 ///
4983 /// FIXME: we'd also like to handle the case where the last elements are zero
4984 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4985 /// There's even a handy isZeroNode for that purpose.
4986 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4987                                         DebugLoc &DL, SelectionDAG &DAG) {
4988   EVT EltVT = VT.getVectorElementType();
4989   unsigned NumElems = Elts.size();
4990
4991   LoadSDNode *LDBase = NULL;
4992   unsigned LastLoadedElt = -1U;
4993
4994   // For each element in the initializer, see if we've found a load or an undef.
4995   // If we don't find an initial load element, or later load elements are
4996   // non-consecutive, bail out.
4997   for (unsigned i = 0; i < NumElems; ++i) {
4998     SDValue Elt = Elts[i];
4999
5000     if (!Elt.getNode() ||
5001         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5002       return SDValue();
5003     if (!LDBase) {
5004       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5005         return SDValue();
5006       LDBase = cast<LoadSDNode>(Elt.getNode());
5007       LastLoadedElt = i;
5008       continue;
5009     }
5010     if (Elt.getOpcode() == ISD::UNDEF)
5011       continue;
5012
5013     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5014     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5015       return SDValue();
5016     LastLoadedElt = i;
5017   }
5018
5019   // If we have found an entire vector of loads and undefs, then return a large
5020   // load of the entire vector width starting at the base pointer.  If we found
5021   // consecutive loads for the low half, generate a vzext_load node.
5022   if (LastLoadedElt == NumElems - 1) {
5023     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5024       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5025                          LDBase->getPointerInfo(),
5026                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5027     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5028                        LDBase->getPointerInfo(),
5029                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5030                        LDBase->getAlignment());
5031   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5032              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5033     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5034     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5035     SDValue ResNode =
5036         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5037                                 LDBase->getPointerInfo(),
5038                                 LDBase->getAlignment(),
5039                                 false/*isVolatile*/, true/*ReadMem*/,
5040                                 false/*WriteMem*/);
5041     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5042   }
5043   return SDValue();
5044 }
5045
5046 SDValue
5047 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5048   DebugLoc dl = Op.getDebugLoc();
5049
5050   EVT VT = Op.getValueType();
5051   EVT ExtVT = VT.getVectorElementType();
5052   unsigned NumElems = Op.getNumOperands();
5053
5054   // Vectors containing all zeros can be matched by pxor and xorps later
5055   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5056     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5057     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5058     if (Op.getValueType() == MVT::v4i32 ||
5059         Op.getValueType() == MVT::v8i32)
5060       return Op;
5061
5062     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5063   }
5064
5065   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5066   // vectors or broken into v4i32 operations on 256-bit vectors.
5067   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5068     if (Op.getValueType() == MVT::v4i32)
5069       return Op;
5070
5071     return getOnesVector(Op.getValueType(), DAG, dl);
5072   }
5073
5074   unsigned EVTBits = ExtVT.getSizeInBits();
5075
5076   unsigned NumZero  = 0;
5077   unsigned NumNonZero = 0;
5078   unsigned NonZeros = 0;
5079   bool IsAllConstants = true;
5080   SmallSet<SDValue, 8> Values;
5081   for (unsigned i = 0; i < NumElems; ++i) {
5082     SDValue Elt = Op.getOperand(i);
5083     if (Elt.getOpcode() == ISD::UNDEF)
5084       continue;
5085     Values.insert(Elt);
5086     if (Elt.getOpcode() != ISD::Constant &&
5087         Elt.getOpcode() != ISD::ConstantFP)
5088       IsAllConstants = false;
5089     if (X86::isZeroNode(Elt))
5090       NumZero++;
5091     else {
5092       NonZeros |= (1 << i);
5093       NumNonZero++;
5094     }
5095   }
5096
5097   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5098   if (NumNonZero == 0)
5099     return DAG.getUNDEF(VT);
5100
5101   // Special case for single non-zero, non-undef, element.
5102   if (NumNonZero == 1) {
5103     unsigned Idx = CountTrailingZeros_32(NonZeros);
5104     SDValue Item = Op.getOperand(Idx);
5105
5106     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5107     // the value are obviously zero, truncate the value to i32 and do the
5108     // insertion that way.  Only do this if the value is non-constant or if the
5109     // value is a constant being inserted into element 0.  It is cheaper to do
5110     // a constant pool load than it is to do a movd + shuffle.
5111     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5112         (!IsAllConstants || Idx == 0)) {
5113       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5114         // Handle SSE only.
5115         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5116         EVT VecVT = MVT::v4i32;
5117         unsigned VecElts = 4;
5118
5119         // Truncate the value (which may itself be a constant) to i32, and
5120         // convert it to a vector with movd (S2V+shuffle to zero extend).
5121         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5122         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5123         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5124                                            Subtarget->hasXMMInt(), DAG);
5125
5126         // Now we have our 32-bit value zero extended in the low element of
5127         // a vector.  If Idx != 0, swizzle it into place.
5128         if (Idx != 0) {
5129           SmallVector<int, 4> Mask;
5130           Mask.push_back(Idx);
5131           for (unsigned i = 1; i != VecElts; ++i)
5132             Mask.push_back(i);
5133           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5134                                       DAG.getUNDEF(Item.getValueType()),
5135                                       &Mask[0]);
5136         }
5137         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5138       }
5139     }
5140
5141     // If we have a constant or non-constant insertion into the low element of
5142     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5143     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5144     // depending on what the source datatype is.
5145     if (Idx == 0) {
5146       if (NumZero == 0) {
5147         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5148       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5149           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5150         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5151         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5152         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5153                                            DAG);
5154       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5155         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5156         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5157         EVT MiddleVT = MVT::v4i32;
5158         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5159         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5160                                            Subtarget->hasXMMInt(), DAG);
5161         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5162       }
5163     }
5164
5165     // Is it a vector logical left shift?
5166     if (NumElems == 2 && Idx == 1 &&
5167         X86::isZeroNode(Op.getOperand(0)) &&
5168         !X86::isZeroNode(Op.getOperand(1))) {
5169       unsigned NumBits = VT.getSizeInBits();
5170       return getVShift(true, VT,
5171                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5172                                    VT, Op.getOperand(1)),
5173                        NumBits/2, DAG, *this, dl);
5174     }
5175
5176     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5177       return SDValue();
5178
5179     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5180     // is a non-constant being inserted into an element other than the low one,
5181     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5182     // movd/movss) to move this into the low element, then shuffle it into
5183     // place.
5184     if (EVTBits == 32) {
5185       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5186
5187       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5188       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5189                                          Subtarget->hasXMMInt(), DAG);
5190       SmallVector<int, 8> MaskVec;
5191       for (unsigned i = 0; i < NumElems; i++)
5192         MaskVec.push_back(i == Idx ? 0 : 1);
5193       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5194     }
5195   }
5196
5197   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5198   if (Values.size() == 1) {
5199     if (EVTBits == 32) {
5200       // Instead of a shuffle like this:
5201       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5202       // Check if it's possible to issue this instead.
5203       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5204       unsigned Idx = CountTrailingZeros_32(NonZeros);
5205       SDValue Item = Op.getOperand(Idx);
5206       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5207         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5208     }
5209     return SDValue();
5210   }
5211
5212   // A vector full of immediates; various special cases are already
5213   // handled, so this is best done with a single constant-pool load.
5214   if (IsAllConstants)
5215     return SDValue();
5216
5217   // For AVX-length vectors, build the individual 128-bit pieces and use
5218   // shuffles to put them in place.
5219   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5220     SmallVector<SDValue, 32> V;
5221     for (unsigned i = 0; i < NumElems; ++i)
5222       V.push_back(Op.getOperand(i));
5223
5224     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5225
5226     // Build both the lower and upper subvector.
5227     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5228     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5229                                 NumElems/2);
5230
5231     // Recreate the wider vector with the lower and upper part.
5232     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5233                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5234     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5235                               DAG, dl);
5236   }
5237
5238   // Let legalizer expand 2-wide build_vectors.
5239   if (EVTBits == 64) {
5240     if (NumNonZero == 1) {
5241       // One half is zero or undef.
5242       unsigned Idx = CountTrailingZeros_32(NonZeros);
5243       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5244                                  Op.getOperand(Idx));
5245       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5246                                          Subtarget->hasXMMInt(), DAG);
5247     }
5248     return SDValue();
5249   }
5250
5251   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5252   if (EVTBits == 8 && NumElems == 16) {
5253     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5254                                         *this);
5255     if (V.getNode()) return V;
5256   }
5257
5258   if (EVTBits == 16 && NumElems == 8) {
5259     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5260                                       *this);
5261     if (V.getNode()) return V;
5262   }
5263
5264   // If element VT is == 32 bits, turn it into a number of shuffles.
5265   SmallVector<SDValue, 8> V;
5266   V.resize(NumElems);
5267   if (NumElems == 4 && NumZero > 0) {
5268     for (unsigned i = 0; i < 4; ++i) {
5269       bool isZero = !(NonZeros & (1 << i));
5270       if (isZero)
5271         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5272       else
5273         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5274     }
5275
5276     for (unsigned i = 0; i < 2; ++i) {
5277       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5278         default: break;
5279         case 0:
5280           V[i] = V[i*2];  // Must be a zero vector.
5281           break;
5282         case 1:
5283           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5284           break;
5285         case 2:
5286           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5287           break;
5288         case 3:
5289           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5290           break;
5291       }
5292     }
5293
5294     SmallVector<int, 8> MaskVec;
5295     bool Reverse = (NonZeros & 0x3) == 2;
5296     for (unsigned i = 0; i < 2; ++i)
5297       MaskVec.push_back(Reverse ? 1-i : i);
5298     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5299     for (unsigned i = 0; i < 2; ++i)
5300       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5301     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5302   }
5303
5304   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5305     // Check for a build vector of consecutive loads.
5306     for (unsigned i = 0; i < NumElems; ++i)
5307       V[i] = Op.getOperand(i);
5308
5309     // Check for elements which are consecutive loads.
5310     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5311     if (LD.getNode())
5312       return LD;
5313
5314     // For SSE 4.1, use insertps to put the high elements into the low element.
5315     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5316       SDValue Result;
5317       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5318         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5319       else
5320         Result = DAG.getUNDEF(VT);
5321
5322       for (unsigned i = 1; i < NumElems; ++i) {
5323         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5324         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5325                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5326       }
5327       return Result;
5328     }
5329
5330     // Otherwise, expand into a number of unpckl*, start by extending each of
5331     // our (non-undef) elements to the full vector width with the element in the
5332     // bottom slot of the vector (which generates no code for SSE).
5333     for (unsigned i = 0; i < NumElems; ++i) {
5334       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5335         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5336       else
5337         V[i] = DAG.getUNDEF(VT);
5338     }
5339
5340     // Next, we iteratively mix elements, e.g. for v4f32:
5341     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5342     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5343     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5344     unsigned EltStride = NumElems >> 1;
5345     while (EltStride != 0) {
5346       for (unsigned i = 0; i < EltStride; ++i) {
5347         // If V[i+EltStride] is undef and this is the first round of mixing,
5348         // then it is safe to just drop this shuffle: V[i] is already in the
5349         // right place, the one element (since it's the first round) being
5350         // inserted as undef can be dropped.  This isn't safe for successive
5351         // rounds because they will permute elements within both vectors.
5352         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5353             EltStride == NumElems/2)
5354           continue;
5355
5356         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5357       }
5358       EltStride >>= 1;
5359     }
5360     return V[0];
5361   }
5362   return SDValue();
5363 }
5364
5365 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5366 // them in a MMX register.  This is better than doing a stack convert.
5367 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5368   DebugLoc dl = Op.getDebugLoc();
5369   EVT ResVT = Op.getValueType();
5370
5371   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5372          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5373   int Mask[2];
5374   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5375   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5376   InVec = Op.getOperand(1);
5377   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5378     unsigned NumElts = ResVT.getVectorNumElements();
5379     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5380     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5381                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5382   } else {
5383     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5384     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5385     Mask[0] = 0; Mask[1] = 2;
5386     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5387   }
5388   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5389 }
5390
5391 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5392 // to create 256-bit vectors from two other 128-bit ones.
5393 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5394   DebugLoc dl = Op.getDebugLoc();
5395   EVT ResVT = Op.getValueType();
5396
5397   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5398
5399   SDValue V1 = Op.getOperand(0);
5400   SDValue V2 = Op.getOperand(1);
5401   unsigned NumElems = ResVT.getVectorNumElements();
5402
5403   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5404                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5405   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5406                             DAG, dl);
5407 }
5408
5409 SDValue
5410 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5411   EVT ResVT = Op.getValueType();
5412
5413   assert(Op.getNumOperands() == 2);
5414   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5415          "Unsupported CONCAT_VECTORS for value type");
5416
5417   // We support concatenate two MMX registers and place them in a MMX register.
5418   // This is better than doing a stack convert.
5419   if (ResVT.is128BitVector())
5420     return LowerMMXCONCAT_VECTORS(Op, DAG);
5421
5422   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5423   // from two other 128-bit ones.
5424   return LowerAVXCONCAT_VECTORS(Op, DAG);
5425 }
5426
5427 // v8i16 shuffles - Prefer shuffles in the following order:
5428 // 1. [all]   pshuflw, pshufhw, optional move
5429 // 2. [ssse3] 1 x pshufb
5430 // 3. [ssse3] 2 x pshufb + 1 x por
5431 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5432 SDValue
5433 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5434                                             SelectionDAG &DAG) const {
5435   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5436   SDValue V1 = SVOp->getOperand(0);
5437   SDValue V2 = SVOp->getOperand(1);
5438   DebugLoc dl = SVOp->getDebugLoc();
5439   SmallVector<int, 8> MaskVals;
5440
5441   // Determine if more than 1 of the words in each of the low and high quadwords
5442   // of the result come from the same quadword of one of the two inputs.  Undef
5443   // mask values count as coming from any quadword, for better codegen.
5444   unsigned LoQuad[] = { 0, 0, 0, 0 };
5445   unsigned HiQuad[] = { 0, 0, 0, 0 };
5446   BitVector InputQuads(4);
5447   for (unsigned i = 0; i < 8; ++i) {
5448     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5449     int EltIdx = SVOp->getMaskElt(i);
5450     MaskVals.push_back(EltIdx);
5451     if (EltIdx < 0) {
5452       ++Quad[0];
5453       ++Quad[1];
5454       ++Quad[2];
5455       ++Quad[3];
5456       continue;
5457     }
5458     ++Quad[EltIdx / 4];
5459     InputQuads.set(EltIdx / 4);
5460   }
5461
5462   int BestLoQuad = -1;
5463   unsigned MaxQuad = 1;
5464   for (unsigned i = 0; i < 4; ++i) {
5465     if (LoQuad[i] > MaxQuad) {
5466       BestLoQuad = i;
5467       MaxQuad = LoQuad[i];
5468     }
5469   }
5470
5471   int BestHiQuad = -1;
5472   MaxQuad = 1;
5473   for (unsigned i = 0; i < 4; ++i) {
5474     if (HiQuad[i] > MaxQuad) {
5475       BestHiQuad = i;
5476       MaxQuad = HiQuad[i];
5477     }
5478   }
5479
5480   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5481   // of the two input vectors, shuffle them into one input vector so only a
5482   // single pshufb instruction is necessary. If There are more than 2 input
5483   // quads, disable the next transformation since it does not help SSSE3.
5484   bool V1Used = InputQuads[0] || InputQuads[1];
5485   bool V2Used = InputQuads[2] || InputQuads[3];
5486   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5487     if (InputQuads.count() == 2 && V1Used && V2Used) {
5488       BestLoQuad = InputQuads.find_first();
5489       BestHiQuad = InputQuads.find_next(BestLoQuad);
5490     }
5491     if (InputQuads.count() > 2) {
5492       BestLoQuad = -1;
5493       BestHiQuad = -1;
5494     }
5495   }
5496
5497   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5498   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5499   // words from all 4 input quadwords.
5500   SDValue NewV;
5501   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5502     SmallVector<int, 8> MaskV;
5503     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5504     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5505     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5506                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5507                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5508     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5509
5510     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5511     // source words for the shuffle, to aid later transformations.
5512     bool AllWordsInNewV = true;
5513     bool InOrder[2] = { true, true };
5514     for (unsigned i = 0; i != 8; ++i) {
5515       int idx = MaskVals[i];
5516       if (idx != (int)i)
5517         InOrder[i/4] = false;
5518       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5519         continue;
5520       AllWordsInNewV = false;
5521       break;
5522     }
5523
5524     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5525     if (AllWordsInNewV) {
5526       for (int i = 0; i != 8; ++i) {
5527         int idx = MaskVals[i];
5528         if (idx < 0)
5529           continue;
5530         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5531         if ((idx != i) && idx < 4)
5532           pshufhw = false;
5533         if ((idx != i) && idx > 3)
5534           pshuflw = false;
5535       }
5536       V1 = NewV;
5537       V2Used = false;
5538       BestLoQuad = 0;
5539       BestHiQuad = 1;
5540     }
5541
5542     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5543     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5544     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5545       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5546       unsigned TargetMask = 0;
5547       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5548                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5549       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5550                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5551       V1 = NewV.getOperand(0);
5552       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5553     }
5554   }
5555
5556   // If we have SSSE3, and all words of the result are from 1 input vector,
5557   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5558   // is present, fall back to case 4.
5559   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5560     SmallVector<SDValue,16> pshufbMask;
5561
5562     // If we have elements from both input vectors, set the high bit of the
5563     // shuffle mask element to zero out elements that come from V2 in the V1
5564     // mask, and elements that come from V1 in the V2 mask, so that the two
5565     // results can be OR'd together.
5566     bool TwoInputs = V1Used && V2Used;
5567     for (unsigned i = 0; i != 8; ++i) {
5568       int EltIdx = MaskVals[i] * 2;
5569       if (TwoInputs && (EltIdx >= 16)) {
5570         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5571         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5572         continue;
5573       }
5574       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5575       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5576     }
5577     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5578     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5579                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5580                                  MVT::v16i8, &pshufbMask[0], 16));
5581     if (!TwoInputs)
5582       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5583
5584     // Calculate the shuffle mask for the second input, shuffle it, and
5585     // OR it with the first shuffled input.
5586     pshufbMask.clear();
5587     for (unsigned i = 0; i != 8; ++i) {
5588       int EltIdx = MaskVals[i] * 2;
5589       if (EltIdx < 16) {
5590         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5591         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5592         continue;
5593       }
5594       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5595       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5596     }
5597     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5598     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5599                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5600                                  MVT::v16i8, &pshufbMask[0], 16));
5601     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5602     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5603   }
5604
5605   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5606   // and update MaskVals with new element order.
5607   BitVector InOrder(8);
5608   if (BestLoQuad >= 0) {
5609     SmallVector<int, 8> MaskV;
5610     for (int i = 0; i != 4; ++i) {
5611       int idx = MaskVals[i];
5612       if (idx < 0) {
5613         MaskV.push_back(-1);
5614         InOrder.set(i);
5615       } else if ((idx / 4) == BestLoQuad) {
5616         MaskV.push_back(idx & 3);
5617         InOrder.set(i);
5618       } else {
5619         MaskV.push_back(-1);
5620       }
5621     }
5622     for (unsigned i = 4; i != 8; ++i)
5623       MaskV.push_back(i);
5624     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5625                                 &MaskV[0]);
5626
5627     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5628         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5629       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5630                                NewV.getOperand(0),
5631                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5632                                DAG);
5633   }
5634
5635   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5636   // and update MaskVals with the new element order.
5637   if (BestHiQuad >= 0) {
5638     SmallVector<int, 8> MaskV;
5639     for (unsigned i = 0; i != 4; ++i)
5640       MaskV.push_back(i);
5641     for (unsigned i = 4; i != 8; ++i) {
5642       int idx = MaskVals[i];
5643       if (idx < 0) {
5644         MaskV.push_back(-1);
5645         InOrder.set(i);
5646       } else if ((idx / 4) == BestHiQuad) {
5647         MaskV.push_back((idx & 3) + 4);
5648         InOrder.set(i);
5649       } else {
5650         MaskV.push_back(-1);
5651       }
5652     }
5653     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5654                                 &MaskV[0]);
5655
5656     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5657         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5658       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5659                               NewV.getOperand(0),
5660                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5661                               DAG);
5662   }
5663
5664   // In case BestHi & BestLo were both -1, which means each quadword has a word
5665   // from each of the four input quadwords, calculate the InOrder bitvector now
5666   // before falling through to the insert/extract cleanup.
5667   if (BestLoQuad == -1 && BestHiQuad == -1) {
5668     NewV = V1;
5669     for (int i = 0; i != 8; ++i)
5670       if (MaskVals[i] < 0 || MaskVals[i] == i)
5671         InOrder.set(i);
5672   }
5673
5674   // The other elements are put in the right place using pextrw and pinsrw.
5675   for (unsigned i = 0; i != 8; ++i) {
5676     if (InOrder[i])
5677       continue;
5678     int EltIdx = MaskVals[i];
5679     if (EltIdx < 0)
5680       continue;
5681     SDValue ExtOp = (EltIdx < 8)
5682     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5683                   DAG.getIntPtrConstant(EltIdx))
5684     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5685                   DAG.getIntPtrConstant(EltIdx - 8));
5686     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5687                        DAG.getIntPtrConstant(i));
5688   }
5689   return NewV;
5690 }
5691
5692 // v16i8 shuffles - Prefer shuffles in the following order:
5693 // 1. [ssse3] 1 x pshufb
5694 // 2. [ssse3] 2 x pshufb + 1 x por
5695 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5696 static
5697 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5698                                  SelectionDAG &DAG,
5699                                  const X86TargetLowering &TLI) {
5700   SDValue V1 = SVOp->getOperand(0);
5701   SDValue V2 = SVOp->getOperand(1);
5702   DebugLoc dl = SVOp->getDebugLoc();
5703   SmallVector<int, 16> MaskVals;
5704   SVOp->getMask(MaskVals);
5705
5706   // If we have SSSE3, case 1 is generated when all result bytes come from
5707   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5708   // present, fall back to case 3.
5709   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5710   bool V1Only = true;
5711   bool V2Only = true;
5712   for (unsigned i = 0; i < 16; ++i) {
5713     int EltIdx = MaskVals[i];
5714     if (EltIdx < 0)
5715       continue;
5716     if (EltIdx < 16)
5717       V2Only = false;
5718     else
5719       V1Only = false;
5720   }
5721
5722   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5723   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5724     SmallVector<SDValue,16> pshufbMask;
5725
5726     // If all result elements are from one input vector, then only translate
5727     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5728     //
5729     // Otherwise, we have elements from both input vectors, and must zero out
5730     // elements that come from V2 in the first mask, and V1 in the second mask
5731     // so that we can OR them together.
5732     bool TwoInputs = !(V1Only || V2Only);
5733     for (unsigned i = 0; i != 16; ++i) {
5734       int EltIdx = MaskVals[i];
5735       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5736         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5737         continue;
5738       }
5739       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5740     }
5741     // If all the elements are from V2, assign it to V1 and return after
5742     // building the first pshufb.
5743     if (V2Only)
5744       V1 = V2;
5745     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5746                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5747                                  MVT::v16i8, &pshufbMask[0], 16));
5748     if (!TwoInputs)
5749       return V1;
5750
5751     // Calculate the shuffle mask for the second input, shuffle it, and
5752     // OR it with the first shuffled input.
5753     pshufbMask.clear();
5754     for (unsigned i = 0; i != 16; ++i) {
5755       int EltIdx = MaskVals[i];
5756       if (EltIdx < 16) {
5757         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5758         continue;
5759       }
5760       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5761     }
5762     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5763                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5764                                  MVT::v16i8, &pshufbMask[0], 16));
5765     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5766   }
5767
5768   // No SSSE3 - Calculate in place words and then fix all out of place words
5769   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5770   // the 16 different words that comprise the two doublequadword input vectors.
5771   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5772   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5773   SDValue NewV = V2Only ? V2 : V1;
5774   for (int i = 0; i != 8; ++i) {
5775     int Elt0 = MaskVals[i*2];
5776     int Elt1 = MaskVals[i*2+1];
5777
5778     // This word of the result is all undef, skip it.
5779     if (Elt0 < 0 && Elt1 < 0)
5780       continue;
5781
5782     // This word of the result is already in the correct place, skip it.
5783     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5784       continue;
5785     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5786       continue;
5787
5788     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5789     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5790     SDValue InsElt;
5791
5792     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5793     // using a single extract together, load it and store it.
5794     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5795       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5796                            DAG.getIntPtrConstant(Elt1 / 2));
5797       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5798                         DAG.getIntPtrConstant(i));
5799       continue;
5800     }
5801
5802     // If Elt1 is defined, extract it from the appropriate source.  If the
5803     // source byte is not also odd, shift the extracted word left 8 bits
5804     // otherwise clear the bottom 8 bits if we need to do an or.
5805     if (Elt1 >= 0) {
5806       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5807                            DAG.getIntPtrConstant(Elt1 / 2));
5808       if ((Elt1 & 1) == 0)
5809         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5810                              DAG.getConstant(8,
5811                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5812       else if (Elt0 >= 0)
5813         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5814                              DAG.getConstant(0xFF00, MVT::i16));
5815     }
5816     // If Elt0 is defined, extract it from the appropriate source.  If the
5817     // source byte is not also even, shift the extracted word right 8 bits. If
5818     // Elt1 was also defined, OR the extracted values together before
5819     // inserting them in the result.
5820     if (Elt0 >= 0) {
5821       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5822                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5823       if ((Elt0 & 1) != 0)
5824         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5825                               DAG.getConstant(8,
5826                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5827       else if (Elt1 >= 0)
5828         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5829                              DAG.getConstant(0x00FF, MVT::i16));
5830       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5831                          : InsElt0;
5832     }
5833     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5834                        DAG.getIntPtrConstant(i));
5835   }
5836   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5837 }
5838
5839 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5840 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5841 /// done when every pair / quad of shuffle mask elements point to elements in
5842 /// the right sequence. e.g.
5843 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5844 static
5845 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5846                                  SelectionDAG &DAG, DebugLoc dl) {
5847   EVT VT = SVOp->getValueType(0);
5848   SDValue V1 = SVOp->getOperand(0);
5849   SDValue V2 = SVOp->getOperand(1);
5850   unsigned NumElems = VT.getVectorNumElements();
5851   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5852   EVT NewVT;
5853   switch (VT.getSimpleVT().SimpleTy) {
5854   default: assert(false && "Unexpected!");
5855   case MVT::v4f32: NewVT = MVT::v2f64; break;
5856   case MVT::v4i32: NewVT = MVT::v2i64; break;
5857   case MVT::v8i16: NewVT = MVT::v4i32; break;
5858   case MVT::v16i8: NewVT = MVT::v4i32; break;
5859   }
5860
5861   int Scale = NumElems / NewWidth;
5862   SmallVector<int, 8> MaskVec;
5863   for (unsigned i = 0; i < NumElems; i += Scale) {
5864     int StartIdx = -1;
5865     for (int j = 0; j < Scale; ++j) {
5866       int EltIdx = SVOp->getMaskElt(i+j);
5867       if (EltIdx < 0)
5868         continue;
5869       if (StartIdx == -1)
5870         StartIdx = EltIdx - (EltIdx % Scale);
5871       if (EltIdx != StartIdx + j)
5872         return SDValue();
5873     }
5874     if (StartIdx == -1)
5875       MaskVec.push_back(-1);
5876     else
5877       MaskVec.push_back(StartIdx / Scale);
5878   }
5879
5880   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5881   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5882   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5883 }
5884
5885 /// getVZextMovL - Return a zero-extending vector move low node.
5886 ///
5887 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5888                             SDValue SrcOp, SelectionDAG &DAG,
5889                             const X86Subtarget *Subtarget, DebugLoc dl) {
5890   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5891     LoadSDNode *LD = NULL;
5892     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5893       LD = dyn_cast<LoadSDNode>(SrcOp);
5894     if (!LD) {
5895       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5896       // instead.
5897       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5898       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5899           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5900           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5901           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5902         // PR2108
5903         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5904         return DAG.getNode(ISD::BITCAST, dl, VT,
5905                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5906                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5907                                                    OpVT,
5908                                                    SrcOp.getOperand(0)
5909                                                           .getOperand(0))));
5910       }
5911     }
5912   }
5913
5914   return DAG.getNode(ISD::BITCAST, dl, VT,
5915                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5916                                  DAG.getNode(ISD::BITCAST, dl,
5917                                              OpVT, SrcOp)));
5918 }
5919
5920 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5921 /// shuffle node referes to only one lane in the sources.
5922 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5923   EVT VT = SVOp->getValueType(0);
5924   int NumElems = VT.getVectorNumElements();
5925   int HalfSize = NumElems/2;
5926   SmallVector<int, 16> M;
5927   SVOp->getMask(M);
5928   bool MatchA = false, MatchB = false;
5929
5930   for (int l = 0; l < NumElems*2; l += HalfSize) {
5931     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5932       MatchA = true;
5933       break;
5934     }
5935   }
5936
5937   for (int l = 0; l < NumElems*2; l += HalfSize) {
5938     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5939       MatchB = true;
5940       break;
5941     }
5942   }
5943
5944   return MatchA && MatchB;
5945 }
5946
5947 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5948 /// which could not be matched by any known target speficic shuffle
5949 static SDValue
5950 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5951   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5952     // If each half of a vector shuffle node referes to only one lane in the
5953     // source vectors, extract each used 128-bit lane and shuffle them using
5954     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5955     // the work to the legalizer.
5956     DebugLoc dl = SVOp->getDebugLoc();
5957     EVT VT = SVOp->getValueType(0);
5958     int NumElems = VT.getVectorNumElements();
5959     int HalfSize = NumElems/2;
5960
5961     // Extract the reference for each half
5962     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5963     int FstVecOpNum = 0, SndVecOpNum = 0;
5964     for (int i = 0; i < HalfSize; ++i) {
5965       int Elt = SVOp->getMaskElt(i);
5966       if (SVOp->getMaskElt(i) < 0)
5967         continue;
5968       FstVecOpNum = Elt/NumElems;
5969       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5970       break;
5971     }
5972     for (int i = HalfSize; i < NumElems; ++i) {
5973       int Elt = SVOp->getMaskElt(i);
5974       if (SVOp->getMaskElt(i) < 0)
5975         continue;
5976       SndVecOpNum = Elt/NumElems;
5977       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5978       break;
5979     }
5980
5981     // Extract the subvectors
5982     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5983                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5984     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5985                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5986
5987     // Generate 128-bit shuffles
5988     SmallVector<int, 16> MaskV1, MaskV2;
5989     for (int i = 0; i < HalfSize; ++i) {
5990       int Elt = SVOp->getMaskElt(i);
5991       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5992     }
5993     for (int i = HalfSize; i < NumElems; ++i) {
5994       int Elt = SVOp->getMaskElt(i);
5995       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5996     }
5997
5998     EVT NVT = V1.getValueType();
5999     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6000     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6001
6002     // Concatenate the result back
6003     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6004                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6005     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6006                               DAG, dl);
6007   }
6008
6009   return SDValue();
6010 }
6011
6012 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6013 /// 4 elements, and match them with several different shuffle types.
6014 static SDValue
6015 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6016   SDValue V1 = SVOp->getOperand(0);
6017   SDValue V2 = SVOp->getOperand(1);
6018   DebugLoc dl = SVOp->getDebugLoc();
6019   EVT VT = SVOp->getValueType(0);
6020
6021   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6022
6023   SmallVector<std::pair<int, int>, 8> Locs;
6024   Locs.resize(4);
6025   SmallVector<int, 8> Mask1(4U, -1);
6026   SmallVector<int, 8> PermMask;
6027   SVOp->getMask(PermMask);
6028
6029   unsigned NumHi = 0;
6030   unsigned NumLo = 0;
6031   for (unsigned i = 0; i != 4; ++i) {
6032     int Idx = PermMask[i];
6033     if (Idx < 0) {
6034       Locs[i] = std::make_pair(-1, -1);
6035     } else {
6036       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6037       if (Idx < 4) {
6038         Locs[i] = std::make_pair(0, NumLo);
6039         Mask1[NumLo] = Idx;
6040         NumLo++;
6041       } else {
6042         Locs[i] = std::make_pair(1, NumHi);
6043         if (2+NumHi < 4)
6044           Mask1[2+NumHi] = Idx;
6045         NumHi++;
6046       }
6047     }
6048   }
6049
6050   if (NumLo <= 2 && NumHi <= 2) {
6051     // If no more than two elements come from either vector. This can be
6052     // implemented with two shuffles. First shuffle gather the elements.
6053     // The second shuffle, which takes the first shuffle as both of its
6054     // vector operands, put the elements into the right order.
6055     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6056
6057     SmallVector<int, 8> Mask2(4U, -1);
6058
6059     for (unsigned i = 0; i != 4; ++i) {
6060       if (Locs[i].first == -1)
6061         continue;
6062       else {
6063         unsigned Idx = (i < 2) ? 0 : 4;
6064         Idx += Locs[i].first * 2 + Locs[i].second;
6065         Mask2[i] = Idx;
6066       }
6067     }
6068
6069     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6070   } else if (NumLo == 3 || NumHi == 3) {
6071     // Otherwise, we must have three elements from one vector, call it X, and
6072     // one element from the other, call it Y.  First, use a shufps to build an
6073     // intermediate vector with the one element from Y and the element from X
6074     // that will be in the same half in the final destination (the indexes don't
6075     // matter). Then, use a shufps to build the final vector, taking the half
6076     // containing the element from Y from the intermediate, and the other half
6077     // from X.
6078     if (NumHi == 3) {
6079       // Normalize it so the 3 elements come from V1.
6080       CommuteVectorShuffleMask(PermMask, VT);
6081       std::swap(V1, V2);
6082     }
6083
6084     // Find the element from V2.
6085     unsigned HiIndex;
6086     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6087       int Val = PermMask[HiIndex];
6088       if (Val < 0)
6089         continue;
6090       if (Val >= 4)
6091         break;
6092     }
6093
6094     Mask1[0] = PermMask[HiIndex];
6095     Mask1[1] = -1;
6096     Mask1[2] = PermMask[HiIndex^1];
6097     Mask1[3] = -1;
6098     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6099
6100     if (HiIndex >= 2) {
6101       Mask1[0] = PermMask[0];
6102       Mask1[1] = PermMask[1];
6103       Mask1[2] = HiIndex & 1 ? 6 : 4;
6104       Mask1[3] = HiIndex & 1 ? 4 : 6;
6105       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6106     } else {
6107       Mask1[0] = HiIndex & 1 ? 2 : 0;
6108       Mask1[1] = HiIndex & 1 ? 0 : 2;
6109       Mask1[2] = PermMask[2];
6110       Mask1[3] = PermMask[3];
6111       if (Mask1[2] >= 0)
6112         Mask1[2] += 4;
6113       if (Mask1[3] >= 0)
6114         Mask1[3] += 4;
6115       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6116     }
6117   }
6118
6119   // Break it into (shuffle shuffle_hi, shuffle_lo).
6120   Locs.clear();
6121   Locs.resize(4);
6122   SmallVector<int,8> LoMask(4U, -1);
6123   SmallVector<int,8> HiMask(4U, -1);
6124
6125   SmallVector<int,8> *MaskPtr = &LoMask;
6126   unsigned MaskIdx = 0;
6127   unsigned LoIdx = 0;
6128   unsigned HiIdx = 2;
6129   for (unsigned i = 0; i != 4; ++i) {
6130     if (i == 2) {
6131       MaskPtr = &HiMask;
6132       MaskIdx = 1;
6133       LoIdx = 0;
6134       HiIdx = 2;
6135     }
6136     int Idx = PermMask[i];
6137     if (Idx < 0) {
6138       Locs[i] = std::make_pair(-1, -1);
6139     } else if (Idx < 4) {
6140       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6141       (*MaskPtr)[LoIdx] = Idx;
6142       LoIdx++;
6143     } else {
6144       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6145       (*MaskPtr)[HiIdx] = Idx;
6146       HiIdx++;
6147     }
6148   }
6149
6150   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6151   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6152   SmallVector<int, 8> MaskOps;
6153   for (unsigned i = 0; i != 4; ++i) {
6154     if (Locs[i].first == -1) {
6155       MaskOps.push_back(-1);
6156     } else {
6157       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6158       MaskOps.push_back(Idx);
6159     }
6160   }
6161   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6162 }
6163
6164 static bool MayFoldVectorLoad(SDValue V) {
6165   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6166     V = V.getOperand(0);
6167   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6168     V = V.getOperand(0);
6169   if (MayFoldLoad(V))
6170     return true;
6171   return false;
6172 }
6173
6174 // FIXME: the version above should always be used. Since there's
6175 // a bug where several vector shuffles can't be folded because the
6176 // DAG is not updated during lowering and a node claims to have two
6177 // uses while it only has one, use this version, and let isel match
6178 // another instruction if the load really happens to have more than
6179 // one use. Remove this version after this bug get fixed.
6180 // rdar://8434668, PR8156
6181 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6182   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6183     V = V.getOperand(0);
6184   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6185     V = V.getOperand(0);
6186   if (ISD::isNormalLoad(V.getNode()))
6187     return true;
6188   return false;
6189 }
6190
6191 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6192 /// a vector extract, and if both can be later optimized into a single load.
6193 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6194 /// here because otherwise a target specific shuffle node is going to be
6195 /// emitted for this shuffle, and the optimization not done.
6196 /// FIXME: This is probably not the best approach, but fix the problem
6197 /// until the right path is decided.
6198 static
6199 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6200                                          const TargetLowering &TLI) {
6201   EVT VT = V.getValueType();
6202   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6203
6204   // Be sure that the vector shuffle is present in a pattern like this:
6205   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6206   if (!V.hasOneUse())
6207     return false;
6208
6209   SDNode *N = *V.getNode()->use_begin();
6210   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6211     return false;
6212
6213   SDValue EltNo = N->getOperand(1);
6214   if (!isa<ConstantSDNode>(EltNo))
6215     return false;
6216
6217   // If the bit convert changed the number of elements, it is unsafe
6218   // to examine the mask.
6219   bool HasShuffleIntoBitcast = false;
6220   if (V.getOpcode() == ISD::BITCAST) {
6221     EVT SrcVT = V.getOperand(0).getValueType();
6222     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6223       return false;
6224     V = V.getOperand(0);
6225     HasShuffleIntoBitcast = true;
6226   }
6227
6228   // Select the input vector, guarding against out of range extract vector.
6229   unsigned NumElems = VT.getVectorNumElements();
6230   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6231   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6232   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6233
6234   // Skip one more bit_convert if necessary
6235   if (V.getOpcode() == ISD::BITCAST)
6236     V = V.getOperand(0);
6237
6238   if (ISD::isNormalLoad(V.getNode())) {
6239     // Is the original load suitable?
6240     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6241
6242     // FIXME: avoid the multi-use bug that is preventing lots of
6243     // of foldings to be detected, this is still wrong of course, but
6244     // give the temporary desired behavior, and if it happens that
6245     // the load has real more uses, during isel it will not fold, and
6246     // will generate poor code.
6247     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6248       return false;
6249
6250     if (!HasShuffleIntoBitcast)
6251       return true;
6252
6253     // If there's a bitcast before the shuffle, check if the load type and
6254     // alignment is valid.
6255     unsigned Align = LN0->getAlignment();
6256     unsigned NewAlign =
6257       TLI.getTargetData()->getABITypeAlignment(
6258                                     VT.getTypeForEVT(*DAG.getContext()));
6259
6260     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6261       return false;
6262   }
6263
6264   return true;
6265 }
6266
6267 static
6268 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6269   EVT VT = Op.getValueType();
6270
6271   // Canonizalize to v2f64.
6272   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6273   return DAG.getNode(ISD::BITCAST, dl, VT,
6274                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6275                                           V1, DAG));
6276 }
6277
6278 static
6279 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6280                         bool HasXMMInt) {
6281   SDValue V1 = Op.getOperand(0);
6282   SDValue V2 = Op.getOperand(1);
6283   EVT VT = Op.getValueType();
6284
6285   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6286
6287   if (HasXMMInt && VT == MVT::v2f64)
6288     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6289
6290   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6291   return DAG.getNode(ISD::BITCAST, dl, VT,
6292                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6293                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6294                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6295 }
6296
6297 static
6298 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6299   SDValue V1 = Op.getOperand(0);
6300   SDValue V2 = Op.getOperand(1);
6301   EVT VT = Op.getValueType();
6302
6303   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6304          "unsupported shuffle type");
6305
6306   if (V2.getOpcode() == ISD::UNDEF)
6307     V2 = V1;
6308
6309   // v4i32 or v4f32
6310   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6311 }
6312
6313 static inline unsigned getSHUFPOpcode(EVT VT) {
6314   switch(VT.getSimpleVT().SimpleTy) {
6315   case MVT::v8i32: // Use fp unit for int unpack.
6316   case MVT::v8f32:
6317   case MVT::v4i32: // Use fp unit for int unpack.
6318   case MVT::v4f32: return X86ISD::SHUFPS;
6319   case MVT::v4i64: // Use fp unit for int unpack.
6320   case MVT::v4f64:
6321   case MVT::v2i64: // Use fp unit for int unpack.
6322   case MVT::v2f64: return X86ISD::SHUFPD;
6323   default:
6324     llvm_unreachable("Unknown type for shufp*");
6325   }
6326   return 0;
6327 }
6328
6329 static
6330 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6331   SDValue V1 = Op.getOperand(0);
6332   SDValue V2 = Op.getOperand(1);
6333   EVT VT = Op.getValueType();
6334   unsigned NumElems = VT.getVectorNumElements();
6335
6336   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6337   // operand of these instructions is only memory, so check if there's a
6338   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6339   // same masks.
6340   bool CanFoldLoad = false;
6341
6342   // Trivial case, when V2 comes from a load.
6343   if (MayFoldVectorLoad(V2))
6344     CanFoldLoad = true;
6345
6346   // When V1 is a load, it can be folded later into a store in isel, example:
6347   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6348   //    turns into:
6349   //  (MOVLPSmr addr:$src1, VR128:$src2)
6350   // So, recognize this potential and also use MOVLPS or MOVLPD
6351   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6352     CanFoldLoad = true;
6353
6354   // Both of them can't be memory operations though.
6355   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6356     CanFoldLoad = false;
6357
6358   if (CanFoldLoad) {
6359     if (HasXMMInt && NumElems == 2)
6360       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6361
6362     if (NumElems == 4)
6363       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6364   }
6365
6366   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6367   // movl and movlp will both match v2i64, but v2i64 is never matched by
6368   // movl earlier because we make it strict to avoid messing with the movlp load
6369   // folding logic (see the code above getMOVLP call). Match it here then,
6370   // this is horrible, but will stay like this until we move all shuffle
6371   // matching to x86 specific nodes. Note that for the 1st condition all
6372   // types are matched with movsd.
6373   if (HasXMMInt) {
6374     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6375     // as to remove this logic from here, as much as possible
6376     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6377       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6378     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6379   }
6380
6381   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6382
6383   // Invert the operand order and use SHUFPS to match it.
6384   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6385                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6386 }
6387
6388 static inline unsigned getUNPCKLOpcode(EVT VT) {
6389   switch(VT.getSimpleVT().SimpleTy) {
6390   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6391   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6392   case MVT::v4f32: return X86ISD::UNPCKLPS;
6393   case MVT::v2f64: return X86ISD::UNPCKLPD;
6394   case MVT::v8i32: // Use fp unit for int unpack.
6395   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6396   case MVT::v4i64: // Use fp unit for int unpack.
6397   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6398   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6399   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6400   default:
6401     llvm_unreachable("Unknown type for unpckl");
6402   }
6403   return 0;
6404 }
6405
6406 static inline unsigned getUNPCKHOpcode(EVT VT) {
6407   switch(VT.getSimpleVT().SimpleTy) {
6408   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6409   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6410   case MVT::v4f32: return X86ISD::UNPCKHPS;
6411   case MVT::v2f64: return X86ISD::UNPCKHPD;
6412   case MVT::v8i32: // Use fp unit for int unpack.
6413   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6414   case MVT::v4i64: // Use fp unit for int unpack.
6415   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6416   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6417   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6418   default:
6419     llvm_unreachable("Unknown type for unpckh");
6420   }
6421   return 0;
6422 }
6423
6424 static inline unsigned getVPERMILOpcode(EVT VT) {
6425   switch(VT.getSimpleVT().SimpleTy) {
6426   case MVT::v4i32:
6427   case MVT::v4f32: return X86ISD::VPERMILPS;
6428   case MVT::v2i64:
6429   case MVT::v2f64: return X86ISD::VPERMILPD;
6430   case MVT::v8i32:
6431   case MVT::v8f32: return X86ISD::VPERMILPSY;
6432   case MVT::v4i64:
6433   case MVT::v4f64: return X86ISD::VPERMILPDY;
6434   default:
6435     llvm_unreachable("Unknown type for vpermil");
6436   }
6437   return 0;
6438 }
6439
6440 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6441 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6442 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6443 static bool isVectorBroadcast(SDValue &Op) {
6444   EVT VT = Op.getValueType();
6445   bool Is256 = VT.getSizeInBits() == 256;
6446
6447   assert((VT.getSizeInBits() == 128 || Is256) &&
6448          "Unsupported type for vbroadcast node");
6449
6450   SDValue V = Op;
6451   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6452     V = V.getOperand(0);
6453
6454   if (Is256 && !(V.hasOneUse() &&
6455                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6456                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6457     return false;
6458
6459   if (Is256)
6460     V = V.getOperand(1);
6461
6462   if (!V.hasOneUse())
6463     return false;
6464
6465   // Check the source scalar_to_vector type. 256-bit broadcasts are
6466   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6467   // for 32-bit scalars.
6468   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6469     return false;
6470
6471   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6472   if (ScalarSize != 32 && ScalarSize != 64)
6473     return false;
6474   if (!Is256 && ScalarSize == 64)
6475     return false;
6476
6477   V = V.getOperand(0);
6478   if (!MayFoldLoad(V))
6479     return false;
6480
6481   // Return the load node
6482   Op = V;
6483   return true;
6484 }
6485
6486 static
6487 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6488                                const TargetLowering &TLI,
6489                                const X86Subtarget *Subtarget) {
6490   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6491   EVT VT = Op.getValueType();
6492   DebugLoc dl = Op.getDebugLoc();
6493   SDValue V1 = Op.getOperand(0);
6494   SDValue V2 = Op.getOperand(1);
6495
6496   if (isZeroShuffle(SVOp))
6497     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6498
6499   // Handle splat operations
6500   if (SVOp->isSplat()) {
6501     unsigned NumElem = VT.getVectorNumElements();
6502     int Size = VT.getSizeInBits();
6503     // Special case, this is the only place now where it's allowed to return
6504     // a vector_shuffle operation without using a target specific node, because
6505     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6506     // this be moved to DAGCombine instead?
6507     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6508       return Op;
6509
6510     // Use vbroadcast whenever the splat comes from a foldable load
6511     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6512       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6513
6514     // Handle splats by matching through known shuffle masks
6515     if ((Size == 128 && NumElem <= 4) ||
6516         (Size == 256 && NumElem < 8))
6517       return SDValue();
6518
6519     // All remaning splats are promoted to target supported vector shuffles.
6520     return PromoteSplat(SVOp, DAG);
6521   }
6522
6523   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6524   // do it!
6525   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6526     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6527     if (NewOp.getNode())
6528       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6529   } else if ((VT == MVT::v4i32 ||
6530              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6531     // FIXME: Figure out a cleaner way to do this.
6532     // Try to make use of movq to zero out the top part.
6533     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6534       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6535       if (NewOp.getNode()) {
6536         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6537           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6538                               DAG, Subtarget, dl);
6539       }
6540     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6541       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6542       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6543         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6544                             DAG, Subtarget, dl);
6545     }
6546   }
6547   return SDValue();
6548 }
6549
6550 SDValue
6551 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6552   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6553   SDValue V1 = Op.getOperand(0);
6554   SDValue V2 = Op.getOperand(1);
6555   EVT VT = Op.getValueType();
6556   DebugLoc dl = Op.getDebugLoc();
6557   unsigned NumElems = VT.getVectorNumElements();
6558   bool isMMX = VT.getSizeInBits() == 64;
6559   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6560   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6561   bool V1IsSplat = false;
6562   bool V2IsSplat = false;
6563   bool HasXMMInt = Subtarget->hasXMMInt();
6564   MachineFunction &MF = DAG.getMachineFunction();
6565   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6566
6567   // Shuffle operations on MMX not supported.
6568   if (isMMX)
6569     return Op;
6570
6571   // Vector shuffle lowering takes 3 steps:
6572   //
6573   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6574   //    narrowing and commutation of operands should be handled.
6575   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6576   //    shuffle nodes.
6577   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6578   //    so the shuffle can be broken into other shuffles and the legalizer can
6579   //    try the lowering again.
6580   //
6581   // The general ideia is that no vector_shuffle operation should be left to
6582   // be matched during isel, all of them must be converted to a target specific
6583   // node here.
6584
6585   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6586   // narrowing and commutation of operands should be handled. The actual code
6587   // doesn't include all of those, work in progress...
6588   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6589   if (NewOp.getNode())
6590     return NewOp;
6591
6592   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6593   // unpckh_undef). Only use pshufd if speed is more important than size.
6594   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6595     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6596   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6597     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6598
6599   if (X86::isMOVDDUPMask(SVOp) &&
6600       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6601       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6602     return getMOVDDup(Op, dl, V1, DAG);
6603
6604   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6605     return getMOVHighToLow(Op, dl, DAG);
6606
6607   // Use to match splats
6608   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6609       (VT == MVT::v2f64 || VT == MVT::v2i64))
6610     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6611
6612   if (X86::isPSHUFDMask(SVOp)) {
6613     // The actual implementation will match the mask in the if above and then
6614     // during isel it can match several different instructions, not only pshufd
6615     // as its name says, sad but true, emulate the behavior for now...
6616     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6617         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6618
6619     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6620
6621     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6622       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6623
6624     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6625                                 TargetMask, DAG);
6626   }
6627
6628   // Check if this can be converted into a logical shift.
6629   bool isLeft = false;
6630   unsigned ShAmt = 0;
6631   SDValue ShVal;
6632   bool isShift = getSubtarget()->hasXMMInt() &&
6633                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6634   if (isShift && ShVal.hasOneUse()) {
6635     // If the shifted value has multiple uses, it may be cheaper to use
6636     // v_set0 + movlhps or movhlps, etc.
6637     EVT EltVT = VT.getVectorElementType();
6638     ShAmt *= EltVT.getSizeInBits();
6639     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6640   }
6641
6642   if (X86::isMOVLMask(SVOp)) {
6643     if (V1IsUndef)
6644       return V2;
6645     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6646       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6647     if (!X86::isMOVLPMask(SVOp)) {
6648       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6649         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6650
6651       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6652         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6653     }
6654   }
6655
6656   // FIXME: fold these into legal mask.
6657   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6658     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6659
6660   if (X86::isMOVHLPSMask(SVOp))
6661     return getMOVHighToLow(Op, dl, DAG);
6662
6663   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6664     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6665
6666   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6667     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6668
6669   if (X86::isMOVLPMask(SVOp))
6670     return getMOVLP(Op, dl, DAG, HasXMMInt);
6671
6672   if (ShouldXformToMOVHLPS(SVOp) ||
6673       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6674     return CommuteVectorShuffle(SVOp, DAG);
6675
6676   if (isShift) {
6677     // No better options. Use a vshl / vsrl.
6678     EVT EltVT = VT.getVectorElementType();
6679     ShAmt *= EltVT.getSizeInBits();
6680     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6681   }
6682
6683   bool Commuted = false;
6684   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6685   // 1,1,1,1 -> v8i16 though.
6686   V1IsSplat = isSplatVector(V1.getNode());
6687   V2IsSplat = isSplatVector(V2.getNode());
6688
6689   // Canonicalize the splat or undef, if present, to be on the RHS.
6690   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6691     Op = CommuteVectorShuffle(SVOp, DAG);
6692     SVOp = cast<ShuffleVectorSDNode>(Op);
6693     V1 = SVOp->getOperand(0);
6694     V2 = SVOp->getOperand(1);
6695     std::swap(V1IsSplat, V2IsSplat);
6696     std::swap(V1IsUndef, V2IsUndef);
6697     Commuted = true;
6698   }
6699
6700   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6701     // Shuffling low element of v1 into undef, just return v1.
6702     if (V2IsUndef)
6703       return V1;
6704     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6705     // the instruction selector will not match, so get a canonical MOVL with
6706     // swapped operands to undo the commute.
6707     return getMOVL(DAG, dl, VT, V2, V1);
6708   }
6709
6710   if (X86::isUNPCKLMask(SVOp))
6711     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6712
6713   if (X86::isUNPCKHMask(SVOp))
6714     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6715
6716   if (V2IsSplat) {
6717     // Normalize mask so all entries that point to V2 points to its first
6718     // element then try to match unpck{h|l} again. If match, return a
6719     // new vector_shuffle with the corrected mask.
6720     SDValue NewMask = NormalizeMask(SVOp, DAG);
6721     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6722     if (NSVOp != SVOp) {
6723       if (X86::isUNPCKLMask(NSVOp, true)) {
6724         return NewMask;
6725       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6726         return NewMask;
6727       }
6728     }
6729   }
6730
6731   if (Commuted) {
6732     // Commute is back and try unpck* again.
6733     // FIXME: this seems wrong.
6734     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6735     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6736
6737     if (X86::isUNPCKLMask(NewSVOp))
6738       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6739
6740     if (X86::isUNPCKHMask(NewSVOp))
6741       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6742   }
6743
6744   // Normalize the node to match x86 shuffle ops if needed
6745   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6746     return CommuteVectorShuffle(SVOp, DAG);
6747
6748   // The checks below are all present in isShuffleMaskLegal, but they are
6749   // inlined here right now to enable us to directly emit target specific
6750   // nodes, and remove one by one until they don't return Op anymore.
6751   SmallVector<int, 16> M;
6752   SVOp->getMask(M);
6753
6754   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6755     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6756                                 X86::getShufflePALIGNRImmediate(SVOp),
6757                                 DAG);
6758
6759   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6760       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6761     if (VT == MVT::v2f64)
6762       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6763     if (VT == MVT::v2i64)
6764       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6765   }
6766
6767   if (isPSHUFHWMask(M, VT))
6768     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6769                                 X86::getShufflePSHUFHWImmediate(SVOp),
6770                                 DAG);
6771
6772   if (isPSHUFLWMask(M, VT))
6773     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6774                                 X86::getShufflePSHUFLWImmediate(SVOp),
6775                                 DAG);
6776
6777   if (isSHUFPMask(M, VT))
6778     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6779                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6780
6781   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6782     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6783   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6784     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6785
6786   //===--------------------------------------------------------------------===//
6787   // Generate target specific nodes for 128 or 256-bit shuffles only
6788   // supported in the AVX instruction set.
6789   //
6790
6791   // Handle VMOVDDUPY permutations
6792   if (isMOVDDUPYMask(SVOp, Subtarget))
6793     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6794
6795   // Handle VPERMILPS* permutations
6796   if (isVPERMILPSMask(M, VT, Subtarget))
6797     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6798                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6799
6800   // Handle VPERMILPD* permutations
6801   if (isVPERMILPDMask(M, VT, Subtarget))
6802     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6803                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6804
6805   // Handle VPERM2F128 permutations
6806   if (isVPERM2F128Mask(M, VT, Subtarget))
6807     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6808                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6809
6810   // Handle VSHUFPSY permutations
6811   if (isVSHUFPSYMask(M, VT, Subtarget))
6812     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6813                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6814
6815   // Handle VSHUFPDY permutations
6816   if (isVSHUFPDYMask(M, VT, Subtarget))
6817     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6818                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6819
6820   //===--------------------------------------------------------------------===//
6821   // Since no target specific shuffle was selected for this generic one,
6822   // lower it into other known shuffles. FIXME: this isn't true yet, but
6823   // this is the plan.
6824   //
6825
6826   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6827   if (VT == MVT::v8i16) {
6828     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6829     if (NewOp.getNode())
6830       return NewOp;
6831   }
6832
6833   if (VT == MVT::v16i8) {
6834     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6835     if (NewOp.getNode())
6836       return NewOp;
6837   }
6838
6839   // Handle all 128-bit wide vectors with 4 elements, and match them with
6840   // several different shuffle types.
6841   if (NumElems == 4 && VT.getSizeInBits() == 128)
6842     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6843
6844   // Handle general 256-bit shuffles
6845   if (VT.is256BitVector())
6846     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6847
6848   return SDValue();
6849 }
6850
6851 SDValue
6852 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6853                                                 SelectionDAG &DAG) const {
6854   EVT VT = Op.getValueType();
6855   DebugLoc dl = Op.getDebugLoc();
6856
6857   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6858     return SDValue();
6859
6860   if (VT.getSizeInBits() == 8) {
6861     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6862                                     Op.getOperand(0), Op.getOperand(1));
6863     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6864                                     DAG.getValueType(VT));
6865     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6866   } else if (VT.getSizeInBits() == 16) {
6867     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6868     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6869     if (Idx == 0)
6870       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6871                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6872                                      DAG.getNode(ISD::BITCAST, dl,
6873                                                  MVT::v4i32,
6874                                                  Op.getOperand(0)),
6875                                      Op.getOperand(1)));
6876     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6877                                     Op.getOperand(0), Op.getOperand(1));
6878     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6879                                     DAG.getValueType(VT));
6880     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6881   } else if (VT == MVT::f32) {
6882     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6883     // the result back to FR32 register. It's only worth matching if the
6884     // result has a single use which is a store or a bitcast to i32.  And in
6885     // the case of a store, it's not worth it if the index is a constant 0,
6886     // because a MOVSSmr can be used instead, which is smaller and faster.
6887     if (!Op.hasOneUse())
6888       return SDValue();
6889     SDNode *User = *Op.getNode()->use_begin();
6890     if ((User->getOpcode() != ISD::STORE ||
6891          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6892           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6893         (User->getOpcode() != ISD::BITCAST ||
6894          User->getValueType(0) != MVT::i32))
6895       return SDValue();
6896     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6897                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6898                                               Op.getOperand(0)),
6899                                               Op.getOperand(1));
6900     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6901   } else if (VT == MVT::i32) {
6902     // ExtractPS works with constant index.
6903     if (isa<ConstantSDNode>(Op.getOperand(1)))
6904       return Op;
6905   }
6906   return SDValue();
6907 }
6908
6909
6910 SDValue
6911 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6912                                            SelectionDAG &DAG) const {
6913   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6914     return SDValue();
6915
6916   SDValue Vec = Op.getOperand(0);
6917   EVT VecVT = Vec.getValueType();
6918
6919   // If this is a 256-bit vector result, first extract the 128-bit vector and
6920   // then extract the element from the 128-bit vector.
6921   if (VecVT.getSizeInBits() == 256) {
6922     DebugLoc dl = Op.getNode()->getDebugLoc();
6923     unsigned NumElems = VecVT.getVectorNumElements();
6924     SDValue Idx = Op.getOperand(1);
6925     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6926
6927     // Get the 128-bit vector.
6928     bool Upper = IdxVal >= NumElems/2;
6929     Vec = Extract128BitVector(Vec,
6930                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6931
6932     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6933                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6934   }
6935
6936   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6937
6938   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6939     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6940     if (Res.getNode())
6941       return Res;
6942   }
6943
6944   EVT VT = Op.getValueType();
6945   DebugLoc dl = Op.getDebugLoc();
6946   // TODO: handle v16i8.
6947   if (VT.getSizeInBits() == 16) {
6948     SDValue Vec = Op.getOperand(0);
6949     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6950     if (Idx == 0)
6951       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6952                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6953                                      DAG.getNode(ISD::BITCAST, dl,
6954                                                  MVT::v4i32, Vec),
6955                                      Op.getOperand(1)));
6956     // Transform it so it match pextrw which produces a 32-bit result.
6957     EVT EltVT = MVT::i32;
6958     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6959                                     Op.getOperand(0), Op.getOperand(1));
6960     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6961                                     DAG.getValueType(VT));
6962     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6963   } else if (VT.getSizeInBits() == 32) {
6964     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6965     if (Idx == 0)
6966       return Op;
6967
6968     // SHUFPS the element to the lowest double word, then movss.
6969     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6970     EVT VVT = Op.getOperand(0).getValueType();
6971     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6972                                        DAG.getUNDEF(VVT), Mask);
6973     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6974                        DAG.getIntPtrConstant(0));
6975   } else if (VT.getSizeInBits() == 64) {
6976     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6977     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6978     //        to match extract_elt for f64.
6979     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6980     if (Idx == 0)
6981       return Op;
6982
6983     // UNPCKHPD the element to the lowest double word, then movsd.
6984     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6985     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6986     int Mask[2] = { 1, -1 };
6987     EVT VVT = Op.getOperand(0).getValueType();
6988     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6989                                        DAG.getUNDEF(VVT), Mask);
6990     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6991                        DAG.getIntPtrConstant(0));
6992   }
6993
6994   return SDValue();
6995 }
6996
6997 SDValue
6998 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6999                                                SelectionDAG &DAG) const {
7000   EVT VT = Op.getValueType();
7001   EVT EltVT = VT.getVectorElementType();
7002   DebugLoc dl = Op.getDebugLoc();
7003
7004   SDValue N0 = Op.getOperand(0);
7005   SDValue N1 = Op.getOperand(1);
7006   SDValue N2 = Op.getOperand(2);
7007
7008   if (VT.getSizeInBits() == 256)
7009     return SDValue();
7010
7011   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7012       isa<ConstantSDNode>(N2)) {
7013     unsigned Opc;
7014     if (VT == MVT::v8i16)
7015       Opc = X86ISD::PINSRW;
7016     else if (VT == MVT::v16i8)
7017       Opc = X86ISD::PINSRB;
7018     else
7019       Opc = X86ISD::PINSRB;
7020
7021     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7022     // argument.
7023     if (N1.getValueType() != MVT::i32)
7024       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7025     if (N2.getValueType() != MVT::i32)
7026       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7027     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7028   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7029     // Bits [7:6] of the constant are the source select.  This will always be
7030     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7031     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7032     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7033     // Bits [5:4] of the constant are the destination select.  This is the
7034     //  value of the incoming immediate.
7035     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7036     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7037     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7038     // Create this as a scalar to vector..
7039     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7040     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7041   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7042     // PINSR* works with constant index.
7043     return Op;
7044   }
7045   return SDValue();
7046 }
7047
7048 SDValue
7049 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7050   EVT VT = Op.getValueType();
7051   EVT EltVT = VT.getVectorElementType();
7052
7053   DebugLoc dl = Op.getDebugLoc();
7054   SDValue N0 = Op.getOperand(0);
7055   SDValue N1 = Op.getOperand(1);
7056   SDValue N2 = Op.getOperand(2);
7057
7058   // If this is a 256-bit vector result, first extract the 128-bit vector,
7059   // insert the element into the extracted half and then place it back.
7060   if (VT.getSizeInBits() == 256) {
7061     if (!isa<ConstantSDNode>(N2))
7062       return SDValue();
7063
7064     // Get the desired 128-bit vector half.
7065     unsigned NumElems = VT.getVectorNumElements();
7066     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7067     bool Upper = IdxVal >= NumElems/2;
7068     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7069     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7070
7071     // Insert the element into the desired half.
7072     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7073                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7074
7075     // Insert the changed part back to the 256-bit vector
7076     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7077   }
7078
7079   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7080     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7081
7082   if (EltVT == MVT::i8)
7083     return SDValue();
7084
7085   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7086     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7087     // as its second argument.
7088     if (N1.getValueType() != MVT::i32)
7089       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7090     if (N2.getValueType() != MVT::i32)
7091       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7092     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7093   }
7094   return SDValue();
7095 }
7096
7097 SDValue
7098 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7099   LLVMContext *Context = DAG.getContext();
7100   DebugLoc dl = Op.getDebugLoc();
7101   EVT OpVT = Op.getValueType();
7102
7103   // If this is a 256-bit vector result, first insert into a 128-bit
7104   // vector and then insert into the 256-bit vector.
7105   if (OpVT.getSizeInBits() > 128) {
7106     // Insert into a 128-bit vector.
7107     EVT VT128 = EVT::getVectorVT(*Context,
7108                                  OpVT.getVectorElementType(),
7109                                  OpVT.getVectorNumElements() / 2);
7110
7111     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7112
7113     // Insert the 128-bit vector.
7114     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7115                               DAG.getConstant(0, MVT::i32),
7116                               DAG, dl);
7117   }
7118
7119   if (Op.getValueType() == MVT::v1i64 &&
7120       Op.getOperand(0).getValueType() == MVT::i64)
7121     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7122
7123   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7124   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7125          "Expected an SSE type!");
7126   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7127                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7128 }
7129
7130 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7131 // a simple subregister reference or explicit instructions to grab
7132 // upper bits of a vector.
7133 SDValue
7134 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7135   if (Subtarget->hasAVX()) {
7136     DebugLoc dl = Op.getNode()->getDebugLoc();
7137     SDValue Vec = Op.getNode()->getOperand(0);
7138     SDValue Idx = Op.getNode()->getOperand(1);
7139
7140     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7141         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7142         return Extract128BitVector(Vec, Idx, DAG, dl);
7143     }
7144   }
7145   return SDValue();
7146 }
7147
7148 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7149 // simple superregister reference or explicit instructions to insert
7150 // the upper bits of a vector.
7151 SDValue
7152 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7153   if (Subtarget->hasAVX()) {
7154     DebugLoc dl = Op.getNode()->getDebugLoc();
7155     SDValue Vec = Op.getNode()->getOperand(0);
7156     SDValue SubVec = Op.getNode()->getOperand(1);
7157     SDValue Idx = Op.getNode()->getOperand(2);
7158
7159     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7160         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7161       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7162     }
7163   }
7164   return SDValue();
7165 }
7166
7167 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7168 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7169 // one of the above mentioned nodes. It has to be wrapped because otherwise
7170 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7171 // be used to form addressing mode. These wrapped nodes will be selected
7172 // into MOV32ri.
7173 SDValue
7174 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7175   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7176
7177   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7178   // global base reg.
7179   unsigned char OpFlag = 0;
7180   unsigned WrapperKind = X86ISD::Wrapper;
7181   CodeModel::Model M = getTargetMachine().getCodeModel();
7182
7183   if (Subtarget->isPICStyleRIPRel() &&
7184       (M == CodeModel::Small || M == CodeModel::Kernel))
7185     WrapperKind = X86ISD::WrapperRIP;
7186   else if (Subtarget->isPICStyleGOT())
7187     OpFlag = X86II::MO_GOTOFF;
7188   else if (Subtarget->isPICStyleStubPIC())
7189     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7190
7191   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7192                                              CP->getAlignment(),
7193                                              CP->getOffset(), OpFlag);
7194   DebugLoc DL = CP->getDebugLoc();
7195   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7196   // With PIC, the address is actually $g + Offset.
7197   if (OpFlag) {
7198     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7199                          DAG.getNode(X86ISD::GlobalBaseReg,
7200                                      DebugLoc(), getPointerTy()),
7201                          Result);
7202   }
7203
7204   return Result;
7205 }
7206
7207 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7208   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7209
7210   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7211   // global base reg.
7212   unsigned char OpFlag = 0;
7213   unsigned WrapperKind = X86ISD::Wrapper;
7214   CodeModel::Model M = getTargetMachine().getCodeModel();
7215
7216   if (Subtarget->isPICStyleRIPRel() &&
7217       (M == CodeModel::Small || M == CodeModel::Kernel))
7218     WrapperKind = X86ISD::WrapperRIP;
7219   else if (Subtarget->isPICStyleGOT())
7220     OpFlag = X86II::MO_GOTOFF;
7221   else if (Subtarget->isPICStyleStubPIC())
7222     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7223
7224   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7225                                           OpFlag);
7226   DebugLoc DL = JT->getDebugLoc();
7227   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7228
7229   // With PIC, the address is actually $g + Offset.
7230   if (OpFlag)
7231     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7232                          DAG.getNode(X86ISD::GlobalBaseReg,
7233                                      DebugLoc(), getPointerTy()),
7234                          Result);
7235
7236   return Result;
7237 }
7238
7239 SDValue
7240 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7241   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7242
7243   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7244   // global base reg.
7245   unsigned char OpFlag = 0;
7246   unsigned WrapperKind = X86ISD::Wrapper;
7247   CodeModel::Model M = getTargetMachine().getCodeModel();
7248
7249   if (Subtarget->isPICStyleRIPRel() &&
7250       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7251     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7252       OpFlag = X86II::MO_GOTPCREL;
7253     WrapperKind = X86ISD::WrapperRIP;
7254   } else if (Subtarget->isPICStyleGOT()) {
7255     OpFlag = X86II::MO_GOT;
7256   } else if (Subtarget->isPICStyleStubPIC()) {
7257     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7258   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7259     OpFlag = X86II::MO_DARWIN_NONLAZY;
7260   }
7261
7262   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7263
7264   DebugLoc DL = Op.getDebugLoc();
7265   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7266
7267
7268   // With PIC, the address is actually $g + Offset.
7269   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7270       !Subtarget->is64Bit()) {
7271     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7272                          DAG.getNode(X86ISD::GlobalBaseReg,
7273                                      DebugLoc(), getPointerTy()),
7274                          Result);
7275   }
7276
7277   // For symbols that require a load from a stub to get the address, emit the
7278   // load.
7279   if (isGlobalStubReference(OpFlag))
7280     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7281                          MachinePointerInfo::getGOT(), false, false, 0);
7282
7283   return Result;
7284 }
7285
7286 SDValue
7287 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7288   // Create the TargetBlockAddressAddress node.
7289   unsigned char OpFlags =
7290     Subtarget->ClassifyBlockAddressReference();
7291   CodeModel::Model M = getTargetMachine().getCodeModel();
7292   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7293   DebugLoc dl = Op.getDebugLoc();
7294   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7295                                        /*isTarget=*/true, OpFlags);
7296
7297   if (Subtarget->isPICStyleRIPRel() &&
7298       (M == CodeModel::Small || M == CodeModel::Kernel))
7299     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7300   else
7301     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7302
7303   // With PIC, the address is actually $g + Offset.
7304   if (isGlobalRelativeToPICBase(OpFlags)) {
7305     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7306                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7307                          Result);
7308   }
7309
7310   return Result;
7311 }
7312
7313 SDValue
7314 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7315                                       int64_t Offset,
7316                                       SelectionDAG &DAG) const {
7317   // Create the TargetGlobalAddress node, folding in the constant
7318   // offset if it is legal.
7319   unsigned char OpFlags =
7320     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7321   CodeModel::Model M = getTargetMachine().getCodeModel();
7322   SDValue Result;
7323   if (OpFlags == X86II::MO_NO_FLAG &&
7324       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7325     // A direct static reference to a global.
7326     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7327     Offset = 0;
7328   } else {
7329     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7330   }
7331
7332   if (Subtarget->isPICStyleRIPRel() &&
7333       (M == CodeModel::Small || M == CodeModel::Kernel))
7334     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7335   else
7336     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7337
7338   // With PIC, the address is actually $g + Offset.
7339   if (isGlobalRelativeToPICBase(OpFlags)) {
7340     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7341                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7342                          Result);
7343   }
7344
7345   // For globals that require a load from a stub to get the address, emit the
7346   // load.
7347   if (isGlobalStubReference(OpFlags))
7348     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7349                          MachinePointerInfo::getGOT(), false, false, 0);
7350
7351   // If there was a non-zero offset that we didn't fold, create an explicit
7352   // addition for it.
7353   if (Offset != 0)
7354     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7355                          DAG.getConstant(Offset, getPointerTy()));
7356
7357   return Result;
7358 }
7359
7360 SDValue
7361 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7362   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7363   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7364   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7365 }
7366
7367 static SDValue
7368 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7369            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7370            unsigned char OperandFlags) {
7371   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7372   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7373   DebugLoc dl = GA->getDebugLoc();
7374   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7375                                            GA->getValueType(0),
7376                                            GA->getOffset(),
7377                                            OperandFlags);
7378   if (InFlag) {
7379     SDValue Ops[] = { Chain,  TGA, *InFlag };
7380     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7381   } else {
7382     SDValue Ops[]  = { Chain, TGA };
7383     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7384   }
7385
7386   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7387   MFI->setAdjustsStack(true);
7388
7389   SDValue Flag = Chain.getValue(1);
7390   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7391 }
7392
7393 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7394 static SDValue
7395 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7396                                 const EVT PtrVT) {
7397   SDValue InFlag;
7398   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7399   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7400                                      DAG.getNode(X86ISD::GlobalBaseReg,
7401                                                  DebugLoc(), PtrVT), InFlag);
7402   InFlag = Chain.getValue(1);
7403
7404   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7405 }
7406
7407 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7408 static SDValue
7409 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7410                                 const EVT PtrVT) {
7411   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7412                     X86::RAX, X86II::MO_TLSGD);
7413 }
7414
7415 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7416 // "local exec" model.
7417 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7418                                    const EVT PtrVT, TLSModel::Model model,
7419                                    bool is64Bit) {
7420   DebugLoc dl = GA->getDebugLoc();
7421
7422   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7423   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7424                                                          is64Bit ? 257 : 256));
7425
7426   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7427                                       DAG.getIntPtrConstant(0),
7428                                       MachinePointerInfo(Ptr), false, false, 0);
7429
7430   unsigned char OperandFlags = 0;
7431   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7432   // initialexec.
7433   unsigned WrapperKind = X86ISD::Wrapper;
7434   if (model == TLSModel::LocalExec) {
7435     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7436   } else if (is64Bit) {
7437     assert(model == TLSModel::InitialExec);
7438     OperandFlags = X86II::MO_GOTTPOFF;
7439     WrapperKind = X86ISD::WrapperRIP;
7440   } else {
7441     assert(model == TLSModel::InitialExec);
7442     OperandFlags = X86II::MO_INDNTPOFF;
7443   }
7444
7445   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7446   // exec)
7447   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7448                                            GA->getValueType(0),
7449                                            GA->getOffset(), OperandFlags);
7450   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7451
7452   if (model == TLSModel::InitialExec)
7453     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7454                          MachinePointerInfo::getGOT(), false, false, 0);
7455
7456   // The address of the thread local variable is the add of the thread
7457   // pointer with the offset of the variable.
7458   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7459 }
7460
7461 SDValue
7462 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7463
7464   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7465   const GlobalValue *GV = GA->getGlobal();
7466
7467   if (Subtarget->isTargetELF()) {
7468     // TODO: implement the "local dynamic" model
7469     // TODO: implement the "initial exec"model for pic executables
7470
7471     // If GV is an alias then use the aliasee for determining
7472     // thread-localness.
7473     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7474       GV = GA->resolveAliasedGlobal(false);
7475
7476     TLSModel::Model model
7477       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7478
7479     switch (model) {
7480       case TLSModel::GeneralDynamic:
7481       case TLSModel::LocalDynamic: // not implemented
7482         if (Subtarget->is64Bit())
7483           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7484         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7485
7486       case TLSModel::InitialExec:
7487       case TLSModel::LocalExec:
7488         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7489                                    Subtarget->is64Bit());
7490     }
7491   } else if (Subtarget->isTargetDarwin()) {
7492     // Darwin only has one model of TLS.  Lower to that.
7493     unsigned char OpFlag = 0;
7494     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7495                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7496
7497     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7498     // global base reg.
7499     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7500                   !Subtarget->is64Bit();
7501     if (PIC32)
7502       OpFlag = X86II::MO_TLVP_PIC_BASE;
7503     else
7504       OpFlag = X86II::MO_TLVP;
7505     DebugLoc DL = Op.getDebugLoc();
7506     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7507                                                 GA->getValueType(0),
7508                                                 GA->getOffset(), OpFlag);
7509     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7510
7511     // With PIC32, the address is actually $g + Offset.
7512     if (PIC32)
7513       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7514                            DAG.getNode(X86ISD::GlobalBaseReg,
7515                                        DebugLoc(), getPointerTy()),
7516                            Offset);
7517
7518     // Lowering the machine isd will make sure everything is in the right
7519     // location.
7520     SDValue Chain = DAG.getEntryNode();
7521     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7522     SDValue Args[] = { Chain, Offset };
7523     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7524
7525     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7526     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7527     MFI->setAdjustsStack(true);
7528
7529     // And our return value (tls address) is in the standard call return value
7530     // location.
7531     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7532     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7533                               Chain.getValue(1));
7534   }
7535
7536   assert(false &&
7537          "TLS not implemented for this target.");
7538
7539   llvm_unreachable("Unreachable");
7540   return SDValue();
7541 }
7542
7543
7544 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7545 /// take a 2 x i32 value to shift plus a shift amount.
7546 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7547   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7548   EVT VT = Op.getValueType();
7549   unsigned VTBits = VT.getSizeInBits();
7550   DebugLoc dl = Op.getDebugLoc();
7551   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7552   SDValue ShOpLo = Op.getOperand(0);
7553   SDValue ShOpHi = Op.getOperand(1);
7554   SDValue ShAmt  = Op.getOperand(2);
7555   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7556                                      DAG.getConstant(VTBits - 1, MVT::i8))
7557                        : DAG.getConstant(0, VT);
7558
7559   SDValue Tmp2, Tmp3;
7560   if (Op.getOpcode() == ISD::SHL_PARTS) {
7561     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7562     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7563   } else {
7564     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7565     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7566   }
7567
7568   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7569                                 DAG.getConstant(VTBits, MVT::i8));
7570   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7571                              AndNode, DAG.getConstant(0, MVT::i8));
7572
7573   SDValue Hi, Lo;
7574   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7575   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7576   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7577
7578   if (Op.getOpcode() == ISD::SHL_PARTS) {
7579     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7580     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7581   } else {
7582     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7583     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7584   }
7585
7586   SDValue Ops[2] = { Lo, Hi };
7587   return DAG.getMergeValues(Ops, 2, dl);
7588 }
7589
7590 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7591                                            SelectionDAG &DAG) const {
7592   EVT SrcVT = Op.getOperand(0).getValueType();
7593
7594   if (SrcVT.isVector())
7595     return SDValue();
7596
7597   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7598          "Unknown SINT_TO_FP to lower!");
7599
7600   // These are really Legal; return the operand so the caller accepts it as
7601   // Legal.
7602   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7603     return Op;
7604   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7605       Subtarget->is64Bit()) {
7606     return Op;
7607   }
7608
7609   DebugLoc dl = Op.getDebugLoc();
7610   unsigned Size = SrcVT.getSizeInBits()/8;
7611   MachineFunction &MF = DAG.getMachineFunction();
7612   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7613   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7614   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7615                                StackSlot,
7616                                MachinePointerInfo::getFixedStack(SSFI),
7617                                false, false, 0);
7618   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7619 }
7620
7621 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7622                                      SDValue StackSlot,
7623                                      SelectionDAG &DAG) const {
7624   // Build the FILD
7625   DebugLoc DL = Op.getDebugLoc();
7626   SDVTList Tys;
7627   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7628   if (useSSE)
7629     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7630   else
7631     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7632
7633   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7634
7635   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7636   MachineMemOperand *MMO;
7637   if (FI) {
7638     int SSFI = FI->getIndex();
7639     MMO =
7640       DAG.getMachineFunction()
7641       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7642                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7643   } else {
7644     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7645     StackSlot = StackSlot.getOperand(1);
7646   }
7647   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7648   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7649                                            X86ISD::FILD, DL,
7650                                            Tys, Ops, array_lengthof(Ops),
7651                                            SrcVT, MMO);
7652
7653   if (useSSE) {
7654     Chain = Result.getValue(1);
7655     SDValue InFlag = Result.getValue(2);
7656
7657     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7658     // shouldn't be necessary except that RFP cannot be live across
7659     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7660     MachineFunction &MF = DAG.getMachineFunction();
7661     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7662     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7663     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7664     Tys = DAG.getVTList(MVT::Other);
7665     SDValue Ops[] = {
7666       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7667     };
7668     MachineMemOperand *MMO =
7669       DAG.getMachineFunction()
7670       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7671                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7672
7673     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7674                                     Ops, array_lengthof(Ops),
7675                                     Op.getValueType(), MMO);
7676     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7677                          MachinePointerInfo::getFixedStack(SSFI),
7678                          false, false, 0);
7679   }
7680
7681   return Result;
7682 }
7683
7684 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7685 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7686                                                SelectionDAG &DAG) const {
7687   // This algorithm is not obvious. Here it is in C code, more or less:
7688   /*
7689     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7690       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7691       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7692
7693       // Copy ints to xmm registers.
7694       __m128i xh = _mm_cvtsi32_si128( hi );
7695       __m128i xl = _mm_cvtsi32_si128( lo );
7696
7697       // Combine into low half of a single xmm register.
7698       __m128i x = _mm_unpacklo_epi32( xh, xl );
7699       __m128d d;
7700       double sd;
7701
7702       // Merge in appropriate exponents to give the integer bits the right
7703       // magnitude.
7704       x = _mm_unpacklo_epi32( x, exp );
7705
7706       // Subtract away the biases to deal with the IEEE-754 double precision
7707       // implicit 1.
7708       d = _mm_sub_pd( (__m128d) x, bias );
7709
7710       // All conversions up to here are exact. The correctly rounded result is
7711       // calculated using the current rounding mode using the following
7712       // horizontal add.
7713       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7714       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7715                                 // store doesn't really need to be here (except
7716                                 // maybe to zero the other double)
7717       return sd;
7718     }
7719   */
7720
7721   DebugLoc dl = Op.getDebugLoc();
7722   LLVMContext *Context = DAG.getContext();
7723
7724   // Build some magic constants.
7725   std::vector<Constant*> CV0;
7726   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7727   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7728   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7729   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7730   Constant *C0 = ConstantVector::get(CV0);
7731   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7732
7733   std::vector<Constant*> CV1;
7734   CV1.push_back(
7735     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7736   CV1.push_back(
7737     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7738   Constant *C1 = ConstantVector::get(CV1);
7739   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7740
7741   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7742                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7743                                         Op.getOperand(0),
7744                                         DAG.getIntPtrConstant(1)));
7745   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7746                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7747                                         Op.getOperand(0),
7748                                         DAG.getIntPtrConstant(0)));
7749   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7750   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7751                               MachinePointerInfo::getConstantPool(),
7752                               false, false, 16);
7753   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7754   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7755   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7756                               MachinePointerInfo::getConstantPool(),
7757                               false, false, 16);
7758   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7759
7760   // Add the halves; easiest way is to swap them into another reg first.
7761   int ShufMask[2] = { 1, -1 };
7762   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7763                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7764   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7765   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7766                      DAG.getIntPtrConstant(0));
7767 }
7768
7769 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7770 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7771                                                SelectionDAG &DAG) const {
7772   DebugLoc dl = Op.getDebugLoc();
7773   // FP constant to bias correct the final result.
7774   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7775                                    MVT::f64);
7776
7777   // Load the 32-bit value into an XMM register.
7778   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7779                              Op.getOperand(0));
7780
7781   // Zero out the upper parts of the register.
7782   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7783                                      DAG);
7784
7785   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7786                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7787                      DAG.getIntPtrConstant(0));
7788
7789   // Or the load with the bias.
7790   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7791                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7792                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7793                                                    MVT::v2f64, Load)),
7794                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7795                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7796                                                    MVT::v2f64, Bias)));
7797   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7798                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7799                    DAG.getIntPtrConstant(0));
7800
7801   // Subtract the bias.
7802   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7803
7804   // Handle final rounding.
7805   EVT DestVT = Op.getValueType();
7806
7807   if (DestVT.bitsLT(MVT::f64)) {
7808     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7809                        DAG.getIntPtrConstant(0));
7810   } else if (DestVT.bitsGT(MVT::f64)) {
7811     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7812   }
7813
7814   // Handle final rounding.
7815   return Sub;
7816 }
7817
7818 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7819                                            SelectionDAG &DAG) const {
7820   SDValue N0 = Op.getOperand(0);
7821   DebugLoc dl = Op.getDebugLoc();
7822
7823   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7824   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7825   // the optimization here.
7826   if (DAG.SignBitIsZero(N0))
7827     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7828
7829   EVT SrcVT = N0.getValueType();
7830   EVT DstVT = Op.getValueType();
7831   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7832     return LowerUINT_TO_FP_i64(Op, DAG);
7833   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7834     return LowerUINT_TO_FP_i32(Op, DAG);
7835
7836   // Make a 64-bit buffer, and use it to build an FILD.
7837   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7838   if (SrcVT == MVT::i32) {
7839     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7840     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7841                                      getPointerTy(), StackSlot, WordOff);
7842     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7843                                   StackSlot, MachinePointerInfo(),
7844                                   false, false, 0);
7845     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7846                                   OffsetSlot, MachinePointerInfo(),
7847                                   false, false, 0);
7848     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7849     return Fild;
7850   }
7851
7852   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7853   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7854                                 StackSlot, MachinePointerInfo(),
7855                                false, false, 0);
7856   // For i64 source, we need to add the appropriate power of 2 if the input
7857   // was negative.  This is the same as the optimization in
7858   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7859   // we must be careful to do the computation in x87 extended precision, not
7860   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7861   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7862   MachineMemOperand *MMO =
7863     DAG.getMachineFunction()
7864     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7865                           MachineMemOperand::MOLoad, 8, 8);
7866
7867   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7868   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7869   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7870                                          MVT::i64, MMO);
7871
7872   APInt FF(32, 0x5F800000ULL);
7873
7874   // Check whether the sign bit is set.
7875   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7876                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7877                                  ISD::SETLT);
7878
7879   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7880   SDValue FudgePtr = DAG.getConstantPool(
7881                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7882                                          getPointerTy());
7883
7884   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7885   SDValue Zero = DAG.getIntPtrConstant(0);
7886   SDValue Four = DAG.getIntPtrConstant(4);
7887   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7888                                Zero, Four);
7889   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7890
7891   // Load the value out, extending it from f32 to f80.
7892   // FIXME: Avoid the extend by constructing the right constant pool?
7893   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7894                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7895                                  MVT::f32, false, false, 4);
7896   // Extend everything to 80 bits to force it to be done on x87.
7897   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7898   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7899 }
7900
7901 std::pair<SDValue,SDValue> X86TargetLowering::
7902 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7903   DebugLoc DL = Op.getDebugLoc();
7904
7905   EVT DstTy = Op.getValueType();
7906
7907   if (!IsSigned) {
7908     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7909     DstTy = MVT::i64;
7910   }
7911
7912   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7913          DstTy.getSimpleVT() >= MVT::i16 &&
7914          "Unknown FP_TO_SINT to lower!");
7915
7916   // These are really Legal.
7917   if (DstTy == MVT::i32 &&
7918       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7919     return std::make_pair(SDValue(), SDValue());
7920   if (Subtarget->is64Bit() &&
7921       DstTy == MVT::i64 &&
7922       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7923     return std::make_pair(SDValue(), SDValue());
7924
7925   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7926   // stack slot.
7927   MachineFunction &MF = DAG.getMachineFunction();
7928   unsigned MemSize = DstTy.getSizeInBits()/8;
7929   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7930   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7931
7932
7933
7934   unsigned Opc;
7935   switch (DstTy.getSimpleVT().SimpleTy) {
7936   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7937   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7938   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7939   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7940   }
7941
7942   SDValue Chain = DAG.getEntryNode();
7943   SDValue Value = Op.getOperand(0);
7944   EVT TheVT = Op.getOperand(0).getValueType();
7945   if (isScalarFPTypeInSSEReg(TheVT)) {
7946     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7947     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7948                          MachinePointerInfo::getFixedStack(SSFI),
7949                          false, false, 0);
7950     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7951     SDValue Ops[] = {
7952       Chain, StackSlot, DAG.getValueType(TheVT)
7953     };
7954
7955     MachineMemOperand *MMO =
7956       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7957                               MachineMemOperand::MOLoad, MemSize, MemSize);
7958     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7959                                     DstTy, MMO);
7960     Chain = Value.getValue(1);
7961     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7962     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963   }
7964
7965   MachineMemOperand *MMO =
7966     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7967                             MachineMemOperand::MOStore, MemSize, MemSize);
7968
7969   // Build the FP_TO_INT*_IN_MEM
7970   SDValue Ops[] = { Chain, Value, StackSlot };
7971   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7972                                          Ops, 3, DstTy, MMO);
7973
7974   return std::make_pair(FIST, StackSlot);
7975 }
7976
7977 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7978                                            SelectionDAG &DAG) const {
7979   if (Op.getValueType().isVector())
7980     return SDValue();
7981
7982   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7983   SDValue FIST = Vals.first, StackSlot = Vals.second;
7984   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7985   if (FIST.getNode() == 0) return Op;
7986
7987   // Load the result.
7988   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7989                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7990 }
7991
7992 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7993                                            SelectionDAG &DAG) const {
7994   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7995   SDValue FIST = Vals.first, StackSlot = Vals.second;
7996   assert(FIST.getNode() && "Unexpected failure");
7997
7998   // Load the result.
7999   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8000                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
8001 }
8002
8003 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8004                                      SelectionDAG &DAG) const {
8005   LLVMContext *Context = DAG.getContext();
8006   DebugLoc dl = Op.getDebugLoc();
8007   EVT VT = Op.getValueType();
8008   EVT EltVT = VT;
8009   if (VT.isVector())
8010     EltVT = VT.getVectorElementType();
8011   std::vector<Constant*> CV;
8012   if (EltVT == MVT::f64) {
8013     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8014     CV.push_back(C);
8015     CV.push_back(C);
8016   } else {
8017     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8018     CV.push_back(C);
8019     CV.push_back(C);
8020     CV.push_back(C);
8021     CV.push_back(C);
8022   }
8023   Constant *C = ConstantVector::get(CV);
8024   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8025   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8026                              MachinePointerInfo::getConstantPool(),
8027                              false, false, 16);
8028   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8029 }
8030
8031 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8032   LLVMContext *Context = DAG.getContext();
8033   DebugLoc dl = Op.getDebugLoc();
8034   EVT VT = Op.getValueType();
8035   EVT EltVT = VT;
8036   if (VT.isVector())
8037     EltVT = VT.getVectorElementType();
8038   std::vector<Constant*> CV;
8039   if (EltVT == MVT::f64) {
8040     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8041     CV.push_back(C);
8042     CV.push_back(C);
8043   } else {
8044     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8045     CV.push_back(C);
8046     CV.push_back(C);
8047     CV.push_back(C);
8048     CV.push_back(C);
8049   }
8050   Constant *C = ConstantVector::get(CV);
8051   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8052   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8053                              MachinePointerInfo::getConstantPool(),
8054                              false, false, 16);
8055   if (VT.isVector()) {
8056     return DAG.getNode(ISD::BITCAST, dl, VT,
8057                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8058                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8059                                 Op.getOperand(0)),
8060                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8061   } else {
8062     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8063   }
8064 }
8065
8066 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8067   LLVMContext *Context = DAG.getContext();
8068   SDValue Op0 = Op.getOperand(0);
8069   SDValue Op1 = Op.getOperand(1);
8070   DebugLoc dl = Op.getDebugLoc();
8071   EVT VT = Op.getValueType();
8072   EVT SrcVT = Op1.getValueType();
8073
8074   // If second operand is smaller, extend it first.
8075   if (SrcVT.bitsLT(VT)) {
8076     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8077     SrcVT = VT;
8078   }
8079   // And if it is bigger, shrink it first.
8080   if (SrcVT.bitsGT(VT)) {
8081     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8082     SrcVT = VT;
8083   }
8084
8085   // At this point the operands and the result should have the same
8086   // type, and that won't be f80 since that is not custom lowered.
8087
8088   // First get the sign bit of second operand.
8089   std::vector<Constant*> CV;
8090   if (SrcVT == MVT::f64) {
8091     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8092     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8093   } else {
8094     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8095     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8096     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8097     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8098   }
8099   Constant *C = ConstantVector::get(CV);
8100   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8101   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8102                               MachinePointerInfo::getConstantPool(),
8103                               false, false, 16);
8104   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8105
8106   // Shift sign bit right or left if the two operands have different types.
8107   if (SrcVT.bitsGT(VT)) {
8108     // Op0 is MVT::f32, Op1 is MVT::f64.
8109     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8110     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8111                           DAG.getConstant(32, MVT::i32));
8112     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8113     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8114                           DAG.getIntPtrConstant(0));
8115   }
8116
8117   // Clear first operand sign bit.
8118   CV.clear();
8119   if (VT == MVT::f64) {
8120     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8121     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8122   } else {
8123     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8124     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8125     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8126     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8127   }
8128   C = ConstantVector::get(CV);
8129   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8130   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8131                               MachinePointerInfo::getConstantPool(),
8132                               false, false, 16);
8133   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8134
8135   // Or the value with the sign bit.
8136   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8137 }
8138
8139 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8140   SDValue N0 = Op.getOperand(0);
8141   DebugLoc dl = Op.getDebugLoc();
8142   EVT VT = Op.getValueType();
8143
8144   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8145   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8146                                   DAG.getConstant(1, VT));
8147   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8148 }
8149
8150 /// Emit nodes that will be selected as "test Op0,Op0", or something
8151 /// equivalent.
8152 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8153                                     SelectionDAG &DAG) const {
8154   DebugLoc dl = Op.getDebugLoc();
8155
8156   // CF and OF aren't always set the way we want. Determine which
8157   // of these we need.
8158   bool NeedCF = false;
8159   bool NeedOF = false;
8160   switch (X86CC) {
8161   default: break;
8162   case X86::COND_A: case X86::COND_AE:
8163   case X86::COND_B: case X86::COND_BE:
8164     NeedCF = true;
8165     break;
8166   case X86::COND_G: case X86::COND_GE:
8167   case X86::COND_L: case X86::COND_LE:
8168   case X86::COND_O: case X86::COND_NO:
8169     NeedOF = true;
8170     break;
8171   }
8172
8173   // See if we can use the EFLAGS value from the operand instead of
8174   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8175   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8176   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8177     // Emit a CMP with 0, which is the TEST pattern.
8178     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8179                        DAG.getConstant(0, Op.getValueType()));
8180
8181   unsigned Opcode = 0;
8182   unsigned NumOperands = 0;
8183   switch (Op.getNode()->getOpcode()) {
8184   case ISD::ADD:
8185     // Due to an isel shortcoming, be conservative if this add is likely to be
8186     // selected as part of a load-modify-store instruction. When the root node
8187     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8188     // uses of other nodes in the match, such as the ADD in this case. This
8189     // leads to the ADD being left around and reselected, with the result being
8190     // two adds in the output.  Alas, even if none our users are stores, that
8191     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8192     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8193     // climbing the DAG back to the root, and it doesn't seem to be worth the
8194     // effort.
8195     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8196            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8197       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8198         goto default_case;
8199
8200     if (ConstantSDNode *C =
8201         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8202       // An add of one will be selected as an INC.
8203       if (C->getAPIntValue() == 1) {
8204         Opcode = X86ISD::INC;
8205         NumOperands = 1;
8206         break;
8207       }
8208
8209       // An add of negative one (subtract of one) will be selected as a DEC.
8210       if (C->getAPIntValue().isAllOnesValue()) {
8211         Opcode = X86ISD::DEC;
8212         NumOperands = 1;
8213         break;
8214       }
8215     }
8216
8217     // Otherwise use a regular EFLAGS-setting add.
8218     Opcode = X86ISD::ADD;
8219     NumOperands = 2;
8220     break;
8221   case ISD::AND: {
8222     // If the primary and result isn't used, don't bother using X86ISD::AND,
8223     // because a TEST instruction will be better.
8224     bool NonFlagUse = false;
8225     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8226            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8227       SDNode *User = *UI;
8228       unsigned UOpNo = UI.getOperandNo();
8229       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8230         // Look pass truncate.
8231         UOpNo = User->use_begin().getOperandNo();
8232         User = *User->use_begin();
8233       }
8234
8235       if (User->getOpcode() != ISD::BRCOND &&
8236           User->getOpcode() != ISD::SETCC &&
8237           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8238         NonFlagUse = true;
8239         break;
8240       }
8241     }
8242
8243     if (!NonFlagUse)
8244       break;
8245   }
8246     // FALL THROUGH
8247   case ISD::SUB:
8248   case ISD::OR:
8249   case ISD::XOR:
8250     // Due to the ISEL shortcoming noted above, be conservative if this op is
8251     // likely to be selected as part of a load-modify-store instruction.
8252     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8253            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8254       if (UI->getOpcode() == ISD::STORE)
8255         goto default_case;
8256
8257     // Otherwise use a regular EFLAGS-setting instruction.
8258     switch (Op.getNode()->getOpcode()) {
8259     default: llvm_unreachable("unexpected operator!");
8260     case ISD::SUB: Opcode = X86ISD::SUB; break;
8261     case ISD::OR:  Opcode = X86ISD::OR;  break;
8262     case ISD::XOR: Opcode = X86ISD::XOR; break;
8263     case ISD::AND: Opcode = X86ISD::AND; break;
8264     }
8265
8266     NumOperands = 2;
8267     break;
8268   case X86ISD::ADD:
8269   case X86ISD::SUB:
8270   case X86ISD::INC:
8271   case X86ISD::DEC:
8272   case X86ISD::OR:
8273   case X86ISD::XOR:
8274   case X86ISD::AND:
8275     return SDValue(Op.getNode(), 1);
8276   default:
8277   default_case:
8278     break;
8279   }
8280
8281   if (Opcode == 0)
8282     // Emit a CMP with 0, which is the TEST pattern.
8283     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8284                        DAG.getConstant(0, Op.getValueType()));
8285
8286   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8287   SmallVector<SDValue, 4> Ops;
8288   for (unsigned i = 0; i != NumOperands; ++i)
8289     Ops.push_back(Op.getOperand(i));
8290
8291   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8292   DAG.ReplaceAllUsesWith(Op, New);
8293   return SDValue(New.getNode(), 1);
8294 }
8295
8296 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8297 /// equivalent.
8298 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8299                                    SelectionDAG &DAG) const {
8300   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8301     if (C->getAPIntValue() == 0)
8302       return EmitTest(Op0, X86CC, DAG);
8303
8304   DebugLoc dl = Op0.getDebugLoc();
8305   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8306 }
8307
8308 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8309 /// if it's possible.
8310 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8311                                      DebugLoc dl, SelectionDAG &DAG) const {
8312   SDValue Op0 = And.getOperand(0);
8313   SDValue Op1 = And.getOperand(1);
8314   if (Op0.getOpcode() == ISD::TRUNCATE)
8315     Op0 = Op0.getOperand(0);
8316   if (Op1.getOpcode() == ISD::TRUNCATE)
8317     Op1 = Op1.getOperand(0);
8318
8319   SDValue LHS, RHS;
8320   if (Op1.getOpcode() == ISD::SHL)
8321     std::swap(Op0, Op1);
8322   if (Op0.getOpcode() == ISD::SHL) {
8323     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8324       if (And00C->getZExtValue() == 1) {
8325         // If we looked past a truncate, check that it's only truncating away
8326         // known zeros.
8327         unsigned BitWidth = Op0.getValueSizeInBits();
8328         unsigned AndBitWidth = And.getValueSizeInBits();
8329         if (BitWidth > AndBitWidth) {
8330           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8331           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8332           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8333             return SDValue();
8334         }
8335         LHS = Op1;
8336         RHS = Op0.getOperand(1);
8337       }
8338   } else if (Op1.getOpcode() == ISD::Constant) {
8339     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8340     SDValue AndLHS = Op0;
8341     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8342       LHS = AndLHS.getOperand(0);
8343       RHS = AndLHS.getOperand(1);
8344     }
8345   }
8346
8347   if (LHS.getNode()) {
8348     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8349     // instruction.  Since the shift amount is in-range-or-undefined, we know
8350     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8351     // the encoding for the i16 version is larger than the i32 version.
8352     // Also promote i16 to i32 for performance / code size reason.
8353     if (LHS.getValueType() == MVT::i8 ||
8354         LHS.getValueType() == MVT::i16)
8355       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8356
8357     // If the operand types disagree, extend the shift amount to match.  Since
8358     // BT ignores high bits (like shifts) we can use anyextend.
8359     if (LHS.getValueType() != RHS.getValueType())
8360       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8361
8362     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8363     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8364     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8365                        DAG.getConstant(Cond, MVT::i8), BT);
8366   }
8367
8368   return SDValue();
8369 }
8370
8371 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8372
8373   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8374
8375   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8376   SDValue Op0 = Op.getOperand(0);
8377   SDValue Op1 = Op.getOperand(1);
8378   DebugLoc dl = Op.getDebugLoc();
8379   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8380
8381   // Optimize to BT if possible.
8382   // Lower (X & (1 << N)) == 0 to BT(X, N).
8383   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8384   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8385   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8386       Op1.getOpcode() == ISD::Constant &&
8387       cast<ConstantSDNode>(Op1)->isNullValue() &&
8388       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8389     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8390     if (NewSetCC.getNode())
8391       return NewSetCC;
8392   }
8393
8394   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8395   // these.
8396   if (Op1.getOpcode() == ISD::Constant &&
8397       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8398        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8399       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8400
8401     // If the input is a setcc, then reuse the input setcc or use a new one with
8402     // the inverted condition.
8403     if (Op0.getOpcode() == X86ISD::SETCC) {
8404       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8405       bool Invert = (CC == ISD::SETNE) ^
8406         cast<ConstantSDNode>(Op1)->isNullValue();
8407       if (!Invert) return Op0;
8408
8409       CCode = X86::GetOppositeBranchCondition(CCode);
8410       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8411                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8412     }
8413   }
8414
8415   bool isFP = Op1.getValueType().isFloatingPoint();
8416   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8417   if (X86CC == X86::COND_INVALID)
8418     return SDValue();
8419
8420   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8421   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8422                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8423 }
8424
8425 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8426 // ones, and then concatenate the result back.
8427 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8428   EVT VT = Op.getValueType();
8429
8430   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8431          "Unsupported value type for operation");
8432
8433   int NumElems = VT.getVectorNumElements();
8434   DebugLoc dl = Op.getDebugLoc();
8435   SDValue CC = Op.getOperand(2);
8436   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8437   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8438
8439   // Extract the LHS vectors
8440   SDValue LHS = Op.getOperand(0);
8441   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8442   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8443
8444   // Extract the RHS vectors
8445   SDValue RHS = Op.getOperand(1);
8446   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8447   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8448
8449   // Issue the operation on the smaller types and concatenate the result back
8450   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8451   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8452   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8453                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8454                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8455 }
8456
8457
8458 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8459   SDValue Cond;
8460   SDValue Op0 = Op.getOperand(0);
8461   SDValue Op1 = Op.getOperand(1);
8462   SDValue CC = Op.getOperand(2);
8463   EVT VT = Op.getValueType();
8464   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8465   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8466   DebugLoc dl = Op.getDebugLoc();
8467
8468   if (isFP) {
8469     unsigned SSECC = 8;
8470     EVT EltVT = Op0.getValueType().getVectorElementType();
8471     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8472
8473     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8474     bool Swap = false;
8475
8476     // SSE Condition code mapping:
8477     //  0 - EQ
8478     //  1 - LT
8479     //  2 - LE
8480     //  3 - UNORD
8481     //  4 - NEQ
8482     //  5 - NLT
8483     //  6 - NLE
8484     //  7 - ORD
8485     switch (SetCCOpcode) {
8486     default: break;
8487     case ISD::SETOEQ:
8488     case ISD::SETEQ:  SSECC = 0; break;
8489     case ISD::SETOGT:
8490     case ISD::SETGT: Swap = true; // Fallthrough
8491     case ISD::SETLT:
8492     case ISD::SETOLT: SSECC = 1; break;
8493     case ISD::SETOGE:
8494     case ISD::SETGE: Swap = true; // Fallthrough
8495     case ISD::SETLE:
8496     case ISD::SETOLE: SSECC = 2; break;
8497     case ISD::SETUO:  SSECC = 3; break;
8498     case ISD::SETUNE:
8499     case ISD::SETNE:  SSECC = 4; break;
8500     case ISD::SETULE: Swap = true;
8501     case ISD::SETUGE: SSECC = 5; break;
8502     case ISD::SETULT: Swap = true;
8503     case ISD::SETUGT: SSECC = 6; break;
8504     case ISD::SETO:   SSECC = 7; break;
8505     }
8506     if (Swap)
8507       std::swap(Op0, Op1);
8508
8509     // In the two special cases we can't handle, emit two comparisons.
8510     if (SSECC == 8) {
8511       if (SetCCOpcode == ISD::SETUEQ) {
8512         SDValue UNORD, EQ;
8513         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8514         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8515         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8516       }
8517       else if (SetCCOpcode == ISD::SETONE) {
8518         SDValue ORD, NEQ;
8519         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8520         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8521         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8522       }
8523       llvm_unreachable("Illegal FP comparison");
8524     }
8525     // Handle all other FP comparisons here.
8526     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8527   }
8528
8529   // Break 256-bit integer vector compare into smaller ones.
8530   if (!isFP && VT.getSizeInBits() == 256)
8531     return Lower256IntVSETCC(Op, DAG);
8532
8533   // We are handling one of the integer comparisons here.  Since SSE only has
8534   // GT and EQ comparisons for integer, swapping operands and multiple
8535   // operations may be required for some comparisons.
8536   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8537   bool Swap = false, Invert = false, FlipSigns = false;
8538
8539   switch (VT.getSimpleVT().SimpleTy) {
8540   default: break;
8541   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8542   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8543   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8544   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8545   }
8546
8547   switch (SetCCOpcode) {
8548   default: break;
8549   case ISD::SETNE:  Invert = true;
8550   case ISD::SETEQ:  Opc = EQOpc; break;
8551   case ISD::SETLT:  Swap = true;
8552   case ISD::SETGT:  Opc = GTOpc; break;
8553   case ISD::SETGE:  Swap = true;
8554   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8555   case ISD::SETULT: Swap = true;
8556   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8557   case ISD::SETUGE: Swap = true;
8558   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8559   }
8560   if (Swap)
8561     std::swap(Op0, Op1);
8562
8563   // Check that the operation in question is available (most are plain SSE2,
8564   // but PCMPGTQ and PCMPEQQ have different requirements).
8565   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8566     return SDValue();
8567   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8568     return SDValue();
8569
8570   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8571   // bits of the inputs before performing those operations.
8572   if (FlipSigns) {
8573     EVT EltVT = VT.getVectorElementType();
8574     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8575                                       EltVT);
8576     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8577     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8578                                     SignBits.size());
8579     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8580     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8581   }
8582
8583   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8584
8585   // If the logical-not of the result is required, perform that now.
8586   if (Invert)
8587     Result = DAG.getNOT(dl, Result, VT);
8588
8589   return Result;
8590 }
8591
8592 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8593 static bool isX86LogicalCmp(SDValue Op) {
8594   unsigned Opc = Op.getNode()->getOpcode();
8595   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8596     return true;
8597   if (Op.getResNo() == 1 &&
8598       (Opc == X86ISD::ADD ||
8599        Opc == X86ISD::SUB ||
8600        Opc == X86ISD::ADC ||
8601        Opc == X86ISD::SBB ||
8602        Opc == X86ISD::SMUL ||
8603        Opc == X86ISD::UMUL ||
8604        Opc == X86ISD::INC ||
8605        Opc == X86ISD::DEC ||
8606        Opc == X86ISD::OR ||
8607        Opc == X86ISD::XOR ||
8608        Opc == X86ISD::AND))
8609     return true;
8610
8611   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8612     return true;
8613
8614   return false;
8615 }
8616
8617 static bool isZero(SDValue V) {
8618   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8619   return C && C->isNullValue();
8620 }
8621
8622 static bool isAllOnes(SDValue V) {
8623   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8624   return C && C->isAllOnesValue();
8625 }
8626
8627 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8628   bool addTest = true;
8629   SDValue Cond  = Op.getOperand(0);
8630   SDValue Op1 = Op.getOperand(1);
8631   SDValue Op2 = Op.getOperand(2);
8632   DebugLoc DL = Op.getDebugLoc();
8633   SDValue CC;
8634
8635   if (Cond.getOpcode() == ISD::SETCC) {
8636     SDValue NewCond = LowerSETCC(Cond, DAG);
8637     if (NewCond.getNode())
8638       Cond = NewCond;
8639   }
8640
8641   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8642   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8643   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8644   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8645   if (Cond.getOpcode() == X86ISD::SETCC &&
8646       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8647       isZero(Cond.getOperand(1).getOperand(1))) {
8648     SDValue Cmp = Cond.getOperand(1);
8649
8650     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8651
8652     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8653         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8654       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8655
8656       SDValue CmpOp0 = Cmp.getOperand(0);
8657       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8658                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8659
8660       SDValue Res =   // Res = 0 or -1.
8661         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8662                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8663
8664       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8665         Res = DAG.getNOT(DL, Res, Res.getValueType());
8666
8667       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8668       if (N2C == 0 || !N2C->isNullValue())
8669         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8670       return Res;
8671     }
8672   }
8673
8674   // Look past (and (setcc_carry (cmp ...)), 1).
8675   if (Cond.getOpcode() == ISD::AND &&
8676       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8677     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8678     if (C && C->getAPIntValue() == 1)
8679       Cond = Cond.getOperand(0);
8680   }
8681
8682   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8683   // setting operand in place of the X86ISD::SETCC.
8684   if (Cond.getOpcode() == X86ISD::SETCC ||
8685       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8686     CC = Cond.getOperand(0);
8687
8688     SDValue Cmp = Cond.getOperand(1);
8689     unsigned Opc = Cmp.getOpcode();
8690     EVT VT = Op.getValueType();
8691
8692     bool IllegalFPCMov = false;
8693     if (VT.isFloatingPoint() && !VT.isVector() &&
8694         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8695       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8696
8697     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8698         Opc == X86ISD::BT) { // FIXME
8699       Cond = Cmp;
8700       addTest = false;
8701     }
8702   }
8703
8704   if (addTest) {
8705     // Look pass the truncate.
8706     if (Cond.getOpcode() == ISD::TRUNCATE)
8707       Cond = Cond.getOperand(0);
8708
8709     // We know the result of AND is compared against zero. Try to match
8710     // it to BT.
8711     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8712       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8713       if (NewSetCC.getNode()) {
8714         CC = NewSetCC.getOperand(0);
8715         Cond = NewSetCC.getOperand(1);
8716         addTest = false;
8717       }
8718     }
8719   }
8720
8721   if (addTest) {
8722     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8723     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8724   }
8725
8726   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8727   // a <  b ?  0 : -1 -> RES = setcc_carry
8728   // a >= b ? -1 :  0 -> RES = setcc_carry
8729   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8730   if (Cond.getOpcode() == X86ISD::CMP) {
8731     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8732
8733     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8734         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8735       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8736                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8737       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8738         return DAG.getNOT(DL, Res, Res.getValueType());
8739       return Res;
8740     }
8741   }
8742
8743   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8744   // condition is true.
8745   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8746   SDValue Ops[] = { Op2, Op1, CC, Cond };
8747   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8748 }
8749
8750 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8751 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8752 // from the AND / OR.
8753 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8754   Opc = Op.getOpcode();
8755   if (Opc != ISD::OR && Opc != ISD::AND)
8756     return false;
8757   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8758           Op.getOperand(0).hasOneUse() &&
8759           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8760           Op.getOperand(1).hasOneUse());
8761 }
8762
8763 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8764 // 1 and that the SETCC node has a single use.
8765 static bool isXor1OfSetCC(SDValue Op) {
8766   if (Op.getOpcode() != ISD::XOR)
8767     return false;
8768   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8769   if (N1C && N1C->getAPIntValue() == 1) {
8770     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8771       Op.getOperand(0).hasOneUse();
8772   }
8773   return false;
8774 }
8775
8776 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8777   bool addTest = true;
8778   SDValue Chain = Op.getOperand(0);
8779   SDValue Cond  = Op.getOperand(1);
8780   SDValue Dest  = Op.getOperand(2);
8781   DebugLoc dl = Op.getDebugLoc();
8782   SDValue CC;
8783
8784   if (Cond.getOpcode() == ISD::SETCC) {
8785     SDValue NewCond = LowerSETCC(Cond, DAG);
8786     if (NewCond.getNode())
8787       Cond = NewCond;
8788   }
8789 #if 0
8790   // FIXME: LowerXALUO doesn't handle these!!
8791   else if (Cond.getOpcode() == X86ISD::ADD  ||
8792            Cond.getOpcode() == X86ISD::SUB  ||
8793            Cond.getOpcode() == X86ISD::SMUL ||
8794            Cond.getOpcode() == X86ISD::UMUL)
8795     Cond = LowerXALUO(Cond, DAG);
8796 #endif
8797
8798   // Look pass (and (setcc_carry (cmp ...)), 1).
8799   if (Cond.getOpcode() == ISD::AND &&
8800       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8801     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8802     if (C && C->getAPIntValue() == 1)
8803       Cond = Cond.getOperand(0);
8804   }
8805
8806   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8807   // setting operand in place of the X86ISD::SETCC.
8808   if (Cond.getOpcode() == X86ISD::SETCC ||
8809       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8810     CC = Cond.getOperand(0);
8811
8812     SDValue Cmp = Cond.getOperand(1);
8813     unsigned Opc = Cmp.getOpcode();
8814     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8815     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8816       Cond = Cmp;
8817       addTest = false;
8818     } else {
8819       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8820       default: break;
8821       case X86::COND_O:
8822       case X86::COND_B:
8823         // These can only come from an arithmetic instruction with overflow,
8824         // e.g. SADDO, UADDO.
8825         Cond = Cond.getNode()->getOperand(1);
8826         addTest = false;
8827         break;
8828       }
8829     }
8830   } else {
8831     unsigned CondOpc;
8832     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8833       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8834       if (CondOpc == ISD::OR) {
8835         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8836         // two branches instead of an explicit OR instruction with a
8837         // separate test.
8838         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8839             isX86LogicalCmp(Cmp)) {
8840           CC = Cond.getOperand(0).getOperand(0);
8841           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8842                               Chain, Dest, CC, Cmp);
8843           CC = Cond.getOperand(1).getOperand(0);
8844           Cond = Cmp;
8845           addTest = false;
8846         }
8847       } else { // ISD::AND
8848         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8849         // two branches instead of an explicit AND instruction with a
8850         // separate test. However, we only do this if this block doesn't
8851         // have a fall-through edge, because this requires an explicit
8852         // jmp when the condition is false.
8853         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8854             isX86LogicalCmp(Cmp) &&
8855             Op.getNode()->hasOneUse()) {
8856           X86::CondCode CCode =
8857             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8858           CCode = X86::GetOppositeBranchCondition(CCode);
8859           CC = DAG.getConstant(CCode, MVT::i8);
8860           SDNode *User = *Op.getNode()->use_begin();
8861           // Look for an unconditional branch following this conditional branch.
8862           // We need this because we need to reverse the successors in order
8863           // to implement FCMP_OEQ.
8864           if (User->getOpcode() == ISD::BR) {
8865             SDValue FalseBB = User->getOperand(1);
8866             SDNode *NewBR =
8867               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8868             assert(NewBR == User);
8869             (void)NewBR;
8870             Dest = FalseBB;
8871
8872             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8873                                 Chain, Dest, CC, Cmp);
8874             X86::CondCode CCode =
8875               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8876             CCode = X86::GetOppositeBranchCondition(CCode);
8877             CC = DAG.getConstant(CCode, MVT::i8);
8878             Cond = Cmp;
8879             addTest = false;
8880           }
8881         }
8882       }
8883     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8884       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8885       // It should be transformed during dag combiner except when the condition
8886       // is set by a arithmetics with overflow node.
8887       X86::CondCode CCode =
8888         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8889       CCode = X86::GetOppositeBranchCondition(CCode);
8890       CC = DAG.getConstant(CCode, MVT::i8);
8891       Cond = Cond.getOperand(0).getOperand(1);
8892       addTest = false;
8893     }
8894   }
8895
8896   if (addTest) {
8897     // Look pass the truncate.
8898     if (Cond.getOpcode() == ISD::TRUNCATE)
8899       Cond = Cond.getOperand(0);
8900
8901     // We know the result of AND is compared against zero. Try to match
8902     // it to BT.
8903     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8904       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8905       if (NewSetCC.getNode()) {
8906         CC = NewSetCC.getOperand(0);
8907         Cond = NewSetCC.getOperand(1);
8908         addTest = false;
8909       }
8910     }
8911   }
8912
8913   if (addTest) {
8914     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8915     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8916   }
8917   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8918                      Chain, Dest, CC, Cond);
8919 }
8920
8921
8922 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8923 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8924 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8925 // that the guard pages used by the OS virtual memory manager are allocated in
8926 // correct sequence.
8927 SDValue
8928 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8929                                            SelectionDAG &DAG) const {
8930   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8931           EnableSegmentedStacks) &&
8932          "This should be used only on Windows targets or when segmented stacks "
8933          "are being used");
8934   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8935   DebugLoc dl = Op.getDebugLoc();
8936
8937   // Get the inputs.
8938   SDValue Chain = Op.getOperand(0);
8939   SDValue Size  = Op.getOperand(1);
8940   // FIXME: Ensure alignment here
8941
8942   bool Is64Bit = Subtarget->is64Bit();
8943   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8944
8945   if (EnableSegmentedStacks) {
8946     MachineFunction &MF = DAG.getMachineFunction();
8947     MachineRegisterInfo &MRI = MF.getRegInfo();
8948
8949     if (Is64Bit) {
8950       // The 64 bit implementation of segmented stacks needs to clobber both r10
8951       // r11. This makes it impossible to use it along with nested parameters.
8952       const Function *F = MF.getFunction();
8953
8954       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8955            I != E; I++)
8956         if (I->hasNestAttr())
8957           report_fatal_error("Cannot use segmented stacks with functions that "
8958                              "have nested arguments.");
8959     }
8960
8961     const TargetRegisterClass *AddrRegClass =
8962       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8963     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8964     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8965     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8966                                 DAG.getRegister(Vreg, SPTy));
8967     SDValue Ops1[2] = { Value, Chain };
8968     return DAG.getMergeValues(Ops1, 2, dl);
8969   } else {
8970     SDValue Flag;
8971     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8972
8973     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8974     Flag = Chain.getValue(1);
8975     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8976
8977     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8978     Flag = Chain.getValue(1);
8979
8980     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8981
8982     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8983     return DAG.getMergeValues(Ops1, 2, dl);
8984   }
8985 }
8986
8987 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8988   MachineFunction &MF = DAG.getMachineFunction();
8989   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8990
8991   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8992   DebugLoc DL = Op.getDebugLoc();
8993
8994   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8995     // vastart just stores the address of the VarArgsFrameIndex slot into the
8996     // memory location argument.
8997     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8998                                    getPointerTy());
8999     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9000                         MachinePointerInfo(SV), false, false, 0);
9001   }
9002
9003   // __va_list_tag:
9004   //   gp_offset         (0 - 6 * 8)
9005   //   fp_offset         (48 - 48 + 8 * 16)
9006   //   overflow_arg_area (point to parameters coming in memory).
9007   //   reg_save_area
9008   SmallVector<SDValue, 8> MemOps;
9009   SDValue FIN = Op.getOperand(1);
9010   // Store gp_offset
9011   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9012                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9013                                                MVT::i32),
9014                                FIN, MachinePointerInfo(SV), false, false, 0);
9015   MemOps.push_back(Store);
9016
9017   // Store fp_offset
9018   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9019                     FIN, DAG.getIntPtrConstant(4));
9020   Store = DAG.getStore(Op.getOperand(0), DL,
9021                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9022                                        MVT::i32),
9023                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9024   MemOps.push_back(Store);
9025
9026   // Store ptr to overflow_arg_area
9027   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9028                     FIN, DAG.getIntPtrConstant(4));
9029   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9030                                     getPointerTy());
9031   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9032                        MachinePointerInfo(SV, 8),
9033                        false, false, 0);
9034   MemOps.push_back(Store);
9035
9036   // Store ptr to reg_save_area.
9037   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9038                     FIN, DAG.getIntPtrConstant(8));
9039   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9040                                     getPointerTy());
9041   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9042                        MachinePointerInfo(SV, 16), false, false, 0);
9043   MemOps.push_back(Store);
9044   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9045                      &MemOps[0], MemOps.size());
9046 }
9047
9048 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9049   assert(Subtarget->is64Bit() &&
9050          "LowerVAARG only handles 64-bit va_arg!");
9051   assert((Subtarget->isTargetLinux() ||
9052           Subtarget->isTargetDarwin()) &&
9053           "Unhandled target in LowerVAARG");
9054   assert(Op.getNode()->getNumOperands() == 4);
9055   SDValue Chain = Op.getOperand(0);
9056   SDValue SrcPtr = Op.getOperand(1);
9057   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9058   unsigned Align = Op.getConstantOperandVal(3);
9059   DebugLoc dl = Op.getDebugLoc();
9060
9061   EVT ArgVT = Op.getNode()->getValueType(0);
9062   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9063   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9064   uint8_t ArgMode;
9065
9066   // Decide which area this value should be read from.
9067   // TODO: Implement the AMD64 ABI in its entirety. This simple
9068   // selection mechanism works only for the basic types.
9069   if (ArgVT == MVT::f80) {
9070     llvm_unreachable("va_arg for f80 not yet implemented");
9071   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9072     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9073   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9074     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9075   } else {
9076     llvm_unreachable("Unhandled argument type in LowerVAARG");
9077   }
9078
9079   if (ArgMode == 2) {
9080     // Sanity Check: Make sure using fp_offset makes sense.
9081     assert(!UseSoftFloat &&
9082            !(DAG.getMachineFunction()
9083                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9084            Subtarget->hasXMM());
9085   }
9086
9087   // Insert VAARG_64 node into the DAG
9088   // VAARG_64 returns two values: Variable Argument Address, Chain
9089   SmallVector<SDValue, 11> InstOps;
9090   InstOps.push_back(Chain);
9091   InstOps.push_back(SrcPtr);
9092   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9093   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9094   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9095   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9096   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9097                                           VTs, &InstOps[0], InstOps.size(),
9098                                           MVT::i64,
9099                                           MachinePointerInfo(SV),
9100                                           /*Align=*/0,
9101                                           /*Volatile=*/false,
9102                                           /*ReadMem=*/true,
9103                                           /*WriteMem=*/true);
9104   Chain = VAARG.getValue(1);
9105
9106   // Load the next argument and return it
9107   return DAG.getLoad(ArgVT, dl,
9108                      Chain,
9109                      VAARG,
9110                      MachinePointerInfo(),
9111                      false, false, 0);
9112 }
9113
9114 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9115   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9116   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9117   SDValue Chain = Op.getOperand(0);
9118   SDValue DstPtr = Op.getOperand(1);
9119   SDValue SrcPtr = Op.getOperand(2);
9120   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9121   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9122   DebugLoc DL = Op.getDebugLoc();
9123
9124   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9125                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9126                        false,
9127                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9128 }
9129
9130 SDValue
9131 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9132   DebugLoc dl = Op.getDebugLoc();
9133   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9134   switch (IntNo) {
9135   default: return SDValue();    // Don't custom lower most intrinsics.
9136   // Comparison intrinsics.
9137   case Intrinsic::x86_sse_comieq_ss:
9138   case Intrinsic::x86_sse_comilt_ss:
9139   case Intrinsic::x86_sse_comile_ss:
9140   case Intrinsic::x86_sse_comigt_ss:
9141   case Intrinsic::x86_sse_comige_ss:
9142   case Intrinsic::x86_sse_comineq_ss:
9143   case Intrinsic::x86_sse_ucomieq_ss:
9144   case Intrinsic::x86_sse_ucomilt_ss:
9145   case Intrinsic::x86_sse_ucomile_ss:
9146   case Intrinsic::x86_sse_ucomigt_ss:
9147   case Intrinsic::x86_sse_ucomige_ss:
9148   case Intrinsic::x86_sse_ucomineq_ss:
9149   case Intrinsic::x86_sse2_comieq_sd:
9150   case Intrinsic::x86_sse2_comilt_sd:
9151   case Intrinsic::x86_sse2_comile_sd:
9152   case Intrinsic::x86_sse2_comigt_sd:
9153   case Intrinsic::x86_sse2_comige_sd:
9154   case Intrinsic::x86_sse2_comineq_sd:
9155   case Intrinsic::x86_sse2_ucomieq_sd:
9156   case Intrinsic::x86_sse2_ucomilt_sd:
9157   case Intrinsic::x86_sse2_ucomile_sd:
9158   case Intrinsic::x86_sse2_ucomigt_sd:
9159   case Intrinsic::x86_sse2_ucomige_sd:
9160   case Intrinsic::x86_sse2_ucomineq_sd: {
9161     unsigned Opc = 0;
9162     ISD::CondCode CC = ISD::SETCC_INVALID;
9163     switch (IntNo) {
9164     default: break;
9165     case Intrinsic::x86_sse_comieq_ss:
9166     case Intrinsic::x86_sse2_comieq_sd:
9167       Opc = X86ISD::COMI;
9168       CC = ISD::SETEQ;
9169       break;
9170     case Intrinsic::x86_sse_comilt_ss:
9171     case Intrinsic::x86_sse2_comilt_sd:
9172       Opc = X86ISD::COMI;
9173       CC = ISD::SETLT;
9174       break;
9175     case Intrinsic::x86_sse_comile_ss:
9176     case Intrinsic::x86_sse2_comile_sd:
9177       Opc = X86ISD::COMI;
9178       CC = ISD::SETLE;
9179       break;
9180     case Intrinsic::x86_sse_comigt_ss:
9181     case Intrinsic::x86_sse2_comigt_sd:
9182       Opc = X86ISD::COMI;
9183       CC = ISD::SETGT;
9184       break;
9185     case Intrinsic::x86_sse_comige_ss:
9186     case Intrinsic::x86_sse2_comige_sd:
9187       Opc = X86ISD::COMI;
9188       CC = ISD::SETGE;
9189       break;
9190     case Intrinsic::x86_sse_comineq_ss:
9191     case Intrinsic::x86_sse2_comineq_sd:
9192       Opc = X86ISD::COMI;
9193       CC = ISD::SETNE;
9194       break;
9195     case Intrinsic::x86_sse_ucomieq_ss:
9196     case Intrinsic::x86_sse2_ucomieq_sd:
9197       Opc = X86ISD::UCOMI;
9198       CC = ISD::SETEQ;
9199       break;
9200     case Intrinsic::x86_sse_ucomilt_ss:
9201     case Intrinsic::x86_sse2_ucomilt_sd:
9202       Opc = X86ISD::UCOMI;
9203       CC = ISD::SETLT;
9204       break;
9205     case Intrinsic::x86_sse_ucomile_ss:
9206     case Intrinsic::x86_sse2_ucomile_sd:
9207       Opc = X86ISD::UCOMI;
9208       CC = ISD::SETLE;
9209       break;
9210     case Intrinsic::x86_sse_ucomigt_ss:
9211     case Intrinsic::x86_sse2_ucomigt_sd:
9212       Opc = X86ISD::UCOMI;
9213       CC = ISD::SETGT;
9214       break;
9215     case Intrinsic::x86_sse_ucomige_ss:
9216     case Intrinsic::x86_sse2_ucomige_sd:
9217       Opc = X86ISD::UCOMI;
9218       CC = ISD::SETGE;
9219       break;
9220     case Intrinsic::x86_sse_ucomineq_ss:
9221     case Intrinsic::x86_sse2_ucomineq_sd:
9222       Opc = X86ISD::UCOMI;
9223       CC = ISD::SETNE;
9224       break;
9225     }
9226
9227     SDValue LHS = Op.getOperand(1);
9228     SDValue RHS = Op.getOperand(2);
9229     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9230     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9231     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9232     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9233                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9234     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9235   }
9236   // Arithmetic intrinsics.
9237   case Intrinsic::x86_sse3_hadd_ps:
9238   case Intrinsic::x86_sse3_hadd_pd:
9239   case Intrinsic::x86_avx_hadd_ps_256:
9240   case Intrinsic::x86_avx_hadd_pd_256:
9241     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9242                        Op.getOperand(1), Op.getOperand(2));
9243   case Intrinsic::x86_sse3_hsub_ps:
9244   case Intrinsic::x86_sse3_hsub_pd:
9245   case Intrinsic::x86_avx_hsub_ps_256:
9246   case Intrinsic::x86_avx_hsub_pd_256:
9247     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9248                        Op.getOperand(1), Op.getOperand(2));
9249   // ptest and testp intrinsics. The intrinsic these come from are designed to
9250   // return an integer value, not just an instruction so lower it to the ptest
9251   // or testp pattern and a setcc for the result.
9252   case Intrinsic::x86_sse41_ptestz:
9253   case Intrinsic::x86_sse41_ptestc:
9254   case Intrinsic::x86_sse41_ptestnzc:
9255   case Intrinsic::x86_avx_ptestz_256:
9256   case Intrinsic::x86_avx_ptestc_256:
9257   case Intrinsic::x86_avx_ptestnzc_256:
9258   case Intrinsic::x86_avx_vtestz_ps:
9259   case Intrinsic::x86_avx_vtestc_ps:
9260   case Intrinsic::x86_avx_vtestnzc_ps:
9261   case Intrinsic::x86_avx_vtestz_pd:
9262   case Intrinsic::x86_avx_vtestc_pd:
9263   case Intrinsic::x86_avx_vtestnzc_pd:
9264   case Intrinsic::x86_avx_vtestz_ps_256:
9265   case Intrinsic::x86_avx_vtestc_ps_256:
9266   case Intrinsic::x86_avx_vtestnzc_ps_256:
9267   case Intrinsic::x86_avx_vtestz_pd_256:
9268   case Intrinsic::x86_avx_vtestc_pd_256:
9269   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9270     bool IsTestPacked = false;
9271     unsigned X86CC = 0;
9272     switch (IntNo) {
9273     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9274     case Intrinsic::x86_avx_vtestz_ps:
9275     case Intrinsic::x86_avx_vtestz_pd:
9276     case Intrinsic::x86_avx_vtestz_ps_256:
9277     case Intrinsic::x86_avx_vtestz_pd_256:
9278       IsTestPacked = true; // Fallthrough
9279     case Intrinsic::x86_sse41_ptestz:
9280     case Intrinsic::x86_avx_ptestz_256:
9281       // ZF = 1
9282       X86CC = X86::COND_E;
9283       break;
9284     case Intrinsic::x86_avx_vtestc_ps:
9285     case Intrinsic::x86_avx_vtestc_pd:
9286     case Intrinsic::x86_avx_vtestc_ps_256:
9287     case Intrinsic::x86_avx_vtestc_pd_256:
9288       IsTestPacked = true; // Fallthrough
9289     case Intrinsic::x86_sse41_ptestc:
9290     case Intrinsic::x86_avx_ptestc_256:
9291       // CF = 1
9292       X86CC = X86::COND_B;
9293       break;
9294     case Intrinsic::x86_avx_vtestnzc_ps:
9295     case Intrinsic::x86_avx_vtestnzc_pd:
9296     case Intrinsic::x86_avx_vtestnzc_ps_256:
9297     case Intrinsic::x86_avx_vtestnzc_pd_256:
9298       IsTestPacked = true; // Fallthrough
9299     case Intrinsic::x86_sse41_ptestnzc:
9300     case Intrinsic::x86_avx_ptestnzc_256:
9301       // ZF and CF = 0
9302       X86CC = X86::COND_A;
9303       break;
9304     }
9305
9306     SDValue LHS = Op.getOperand(1);
9307     SDValue RHS = Op.getOperand(2);
9308     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9309     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9310     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9311     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9312     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9313   }
9314
9315   // Fix vector shift instructions where the last operand is a non-immediate
9316   // i32 value.
9317   case Intrinsic::x86_sse2_pslli_w:
9318   case Intrinsic::x86_sse2_pslli_d:
9319   case Intrinsic::x86_sse2_pslli_q:
9320   case Intrinsic::x86_sse2_psrli_w:
9321   case Intrinsic::x86_sse2_psrli_d:
9322   case Intrinsic::x86_sse2_psrli_q:
9323   case Intrinsic::x86_sse2_psrai_w:
9324   case Intrinsic::x86_sse2_psrai_d:
9325   case Intrinsic::x86_mmx_pslli_w:
9326   case Intrinsic::x86_mmx_pslli_d:
9327   case Intrinsic::x86_mmx_pslli_q:
9328   case Intrinsic::x86_mmx_psrli_w:
9329   case Intrinsic::x86_mmx_psrli_d:
9330   case Intrinsic::x86_mmx_psrli_q:
9331   case Intrinsic::x86_mmx_psrai_w:
9332   case Intrinsic::x86_mmx_psrai_d: {
9333     SDValue ShAmt = Op.getOperand(2);
9334     if (isa<ConstantSDNode>(ShAmt))
9335       return SDValue();
9336
9337     unsigned NewIntNo = 0;
9338     EVT ShAmtVT = MVT::v4i32;
9339     switch (IntNo) {
9340     case Intrinsic::x86_sse2_pslli_w:
9341       NewIntNo = Intrinsic::x86_sse2_psll_w;
9342       break;
9343     case Intrinsic::x86_sse2_pslli_d:
9344       NewIntNo = Intrinsic::x86_sse2_psll_d;
9345       break;
9346     case Intrinsic::x86_sse2_pslli_q:
9347       NewIntNo = Intrinsic::x86_sse2_psll_q;
9348       break;
9349     case Intrinsic::x86_sse2_psrli_w:
9350       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9351       break;
9352     case Intrinsic::x86_sse2_psrli_d:
9353       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9354       break;
9355     case Intrinsic::x86_sse2_psrli_q:
9356       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9357       break;
9358     case Intrinsic::x86_sse2_psrai_w:
9359       NewIntNo = Intrinsic::x86_sse2_psra_w;
9360       break;
9361     case Intrinsic::x86_sse2_psrai_d:
9362       NewIntNo = Intrinsic::x86_sse2_psra_d;
9363       break;
9364     default: {
9365       ShAmtVT = MVT::v2i32;
9366       switch (IntNo) {
9367       case Intrinsic::x86_mmx_pslli_w:
9368         NewIntNo = Intrinsic::x86_mmx_psll_w;
9369         break;
9370       case Intrinsic::x86_mmx_pslli_d:
9371         NewIntNo = Intrinsic::x86_mmx_psll_d;
9372         break;
9373       case Intrinsic::x86_mmx_pslli_q:
9374         NewIntNo = Intrinsic::x86_mmx_psll_q;
9375         break;
9376       case Intrinsic::x86_mmx_psrli_w:
9377         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9378         break;
9379       case Intrinsic::x86_mmx_psrli_d:
9380         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9381         break;
9382       case Intrinsic::x86_mmx_psrli_q:
9383         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9384         break;
9385       case Intrinsic::x86_mmx_psrai_w:
9386         NewIntNo = Intrinsic::x86_mmx_psra_w;
9387         break;
9388       case Intrinsic::x86_mmx_psrai_d:
9389         NewIntNo = Intrinsic::x86_mmx_psra_d;
9390         break;
9391       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9392       }
9393       break;
9394     }
9395     }
9396
9397     // The vector shift intrinsics with scalars uses 32b shift amounts but
9398     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9399     // to be zero.
9400     SDValue ShOps[4];
9401     ShOps[0] = ShAmt;
9402     ShOps[1] = DAG.getConstant(0, MVT::i32);
9403     if (ShAmtVT == MVT::v4i32) {
9404       ShOps[2] = DAG.getUNDEF(MVT::i32);
9405       ShOps[3] = DAG.getUNDEF(MVT::i32);
9406       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9407     } else {
9408       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9409 // FIXME this must be lowered to get rid of the invalid type.
9410     }
9411
9412     EVT VT = Op.getValueType();
9413     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9414     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9415                        DAG.getConstant(NewIntNo, MVT::i32),
9416                        Op.getOperand(1), ShAmt);
9417   }
9418   }
9419 }
9420
9421 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9422                                            SelectionDAG &DAG) const {
9423   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9424   MFI->setReturnAddressIsTaken(true);
9425
9426   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9427   DebugLoc dl = Op.getDebugLoc();
9428
9429   if (Depth > 0) {
9430     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9431     SDValue Offset =
9432       DAG.getConstant(TD->getPointerSize(),
9433                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9434     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9435                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9436                                    FrameAddr, Offset),
9437                        MachinePointerInfo(), false, false, 0);
9438   }
9439
9440   // Just load the return address.
9441   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9442   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9443                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9444 }
9445
9446 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9447   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9448   MFI->setFrameAddressIsTaken(true);
9449
9450   EVT VT = Op.getValueType();
9451   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9452   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9453   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9454   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9455   while (Depth--)
9456     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9457                             MachinePointerInfo(),
9458                             false, false, 0);
9459   return FrameAddr;
9460 }
9461
9462 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9463                                                      SelectionDAG &DAG) const {
9464   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9465 }
9466
9467 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9468   MachineFunction &MF = DAG.getMachineFunction();
9469   SDValue Chain     = Op.getOperand(0);
9470   SDValue Offset    = Op.getOperand(1);
9471   SDValue Handler   = Op.getOperand(2);
9472   DebugLoc dl       = Op.getDebugLoc();
9473
9474   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9475                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9476                                      getPointerTy());
9477   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9478
9479   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9480                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9481   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9482   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9483                        false, false, 0);
9484   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9485   MF.getRegInfo().addLiveOut(StoreAddrReg);
9486
9487   return DAG.getNode(X86ISD::EH_RETURN, dl,
9488                      MVT::Other,
9489                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9490 }
9491
9492 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9493                                                   SelectionDAG &DAG) const {
9494   return Op.getOperand(0);
9495 }
9496
9497 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9498                                                 SelectionDAG &DAG) const {
9499   SDValue Root = Op.getOperand(0);
9500   SDValue Trmp = Op.getOperand(1); // trampoline
9501   SDValue FPtr = Op.getOperand(2); // nested function
9502   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9503   DebugLoc dl  = Op.getDebugLoc();
9504
9505   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9506
9507   if (Subtarget->is64Bit()) {
9508     SDValue OutChains[6];
9509
9510     // Large code-model.
9511     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9512     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9513
9514     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9515     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9516
9517     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9518
9519     // Load the pointer to the nested function into R11.
9520     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9521     SDValue Addr = Trmp;
9522     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9523                                 Addr, MachinePointerInfo(TrmpAddr),
9524                                 false, false, 0);
9525
9526     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9527                        DAG.getConstant(2, MVT::i64));
9528     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9529                                 MachinePointerInfo(TrmpAddr, 2),
9530                                 false, false, 2);
9531
9532     // Load the 'nest' parameter value into R10.
9533     // R10 is specified in X86CallingConv.td
9534     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9535     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9536                        DAG.getConstant(10, MVT::i64));
9537     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9538                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9539                                 false, false, 0);
9540
9541     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9542                        DAG.getConstant(12, MVT::i64));
9543     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9544                                 MachinePointerInfo(TrmpAddr, 12),
9545                                 false, false, 2);
9546
9547     // Jump to the nested function.
9548     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9549     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9550                        DAG.getConstant(20, MVT::i64));
9551     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9552                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9553                                 false, false, 0);
9554
9555     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9556     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9557                        DAG.getConstant(22, MVT::i64));
9558     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9559                                 MachinePointerInfo(TrmpAddr, 22),
9560                                 false, false, 0);
9561
9562     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9563   } else {
9564     const Function *Func =
9565       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9566     CallingConv::ID CC = Func->getCallingConv();
9567     unsigned NestReg;
9568
9569     switch (CC) {
9570     default:
9571       llvm_unreachable("Unsupported calling convention");
9572     case CallingConv::C:
9573     case CallingConv::X86_StdCall: {
9574       // Pass 'nest' parameter in ECX.
9575       // Must be kept in sync with X86CallingConv.td
9576       NestReg = X86::ECX;
9577
9578       // Check that ECX wasn't needed by an 'inreg' parameter.
9579       FunctionType *FTy = Func->getFunctionType();
9580       const AttrListPtr &Attrs = Func->getAttributes();
9581
9582       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9583         unsigned InRegCount = 0;
9584         unsigned Idx = 1;
9585
9586         for (FunctionType::param_iterator I = FTy->param_begin(),
9587              E = FTy->param_end(); I != E; ++I, ++Idx)
9588           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9589             // FIXME: should only count parameters that are lowered to integers.
9590             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9591
9592         if (InRegCount > 2) {
9593           report_fatal_error("Nest register in use - reduce number of inreg"
9594                              " parameters!");
9595         }
9596       }
9597       break;
9598     }
9599     case CallingConv::X86_FastCall:
9600     case CallingConv::X86_ThisCall:
9601     case CallingConv::Fast:
9602       // Pass 'nest' parameter in EAX.
9603       // Must be kept in sync with X86CallingConv.td
9604       NestReg = X86::EAX;
9605       break;
9606     }
9607
9608     SDValue OutChains[4];
9609     SDValue Addr, Disp;
9610
9611     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9612                        DAG.getConstant(10, MVT::i32));
9613     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9614
9615     // This is storing the opcode for MOV32ri.
9616     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9617     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9618     OutChains[0] = DAG.getStore(Root, dl,
9619                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9620                                 Trmp, MachinePointerInfo(TrmpAddr),
9621                                 false, false, 0);
9622
9623     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9624                        DAG.getConstant(1, MVT::i32));
9625     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9626                                 MachinePointerInfo(TrmpAddr, 1),
9627                                 false, false, 1);
9628
9629     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9630     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9631                        DAG.getConstant(5, MVT::i32));
9632     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9633                                 MachinePointerInfo(TrmpAddr, 5),
9634                                 false, false, 1);
9635
9636     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9637                        DAG.getConstant(6, MVT::i32));
9638     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9639                                 MachinePointerInfo(TrmpAddr, 6),
9640                                 false, false, 1);
9641
9642     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9643   }
9644 }
9645
9646 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9647                                             SelectionDAG &DAG) const {
9648   /*
9649    The rounding mode is in bits 11:10 of FPSR, and has the following
9650    settings:
9651      00 Round to nearest
9652      01 Round to -inf
9653      10 Round to +inf
9654      11 Round to 0
9655
9656   FLT_ROUNDS, on the other hand, expects the following:
9657     -1 Undefined
9658      0 Round to 0
9659      1 Round to nearest
9660      2 Round to +inf
9661      3 Round to -inf
9662
9663   To perform the conversion, we do:
9664     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9665   */
9666
9667   MachineFunction &MF = DAG.getMachineFunction();
9668   const TargetMachine &TM = MF.getTarget();
9669   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9670   unsigned StackAlignment = TFI.getStackAlignment();
9671   EVT VT = Op.getValueType();
9672   DebugLoc DL = Op.getDebugLoc();
9673
9674   // Save FP Control Word to stack slot
9675   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9676   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9677
9678
9679   MachineMemOperand *MMO =
9680    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9681                            MachineMemOperand::MOStore, 2, 2);
9682
9683   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9684   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9685                                           DAG.getVTList(MVT::Other),
9686                                           Ops, 2, MVT::i16, MMO);
9687
9688   // Load FP Control Word from stack slot
9689   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9690                             MachinePointerInfo(), false, false, 0);
9691
9692   // Transform as necessary
9693   SDValue CWD1 =
9694     DAG.getNode(ISD::SRL, DL, MVT::i16,
9695                 DAG.getNode(ISD::AND, DL, MVT::i16,
9696                             CWD, DAG.getConstant(0x800, MVT::i16)),
9697                 DAG.getConstant(11, MVT::i8));
9698   SDValue CWD2 =
9699     DAG.getNode(ISD::SRL, DL, MVT::i16,
9700                 DAG.getNode(ISD::AND, DL, MVT::i16,
9701                             CWD, DAG.getConstant(0x400, MVT::i16)),
9702                 DAG.getConstant(9, MVT::i8));
9703
9704   SDValue RetVal =
9705     DAG.getNode(ISD::AND, DL, MVT::i16,
9706                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9707                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9708                             DAG.getConstant(1, MVT::i16)),
9709                 DAG.getConstant(3, MVT::i16));
9710
9711
9712   return DAG.getNode((VT.getSizeInBits() < 16 ?
9713                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9714 }
9715
9716 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9717   EVT VT = Op.getValueType();
9718   EVT OpVT = VT;
9719   unsigned NumBits = VT.getSizeInBits();
9720   DebugLoc dl = Op.getDebugLoc();
9721
9722   Op = Op.getOperand(0);
9723   if (VT == MVT::i8) {
9724     // Zero extend to i32 since there is not an i8 bsr.
9725     OpVT = MVT::i32;
9726     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9727   }
9728
9729   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9730   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9731   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9732
9733   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9734   SDValue Ops[] = {
9735     Op,
9736     DAG.getConstant(NumBits+NumBits-1, OpVT),
9737     DAG.getConstant(X86::COND_E, MVT::i8),
9738     Op.getValue(1)
9739   };
9740   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9741
9742   // Finally xor with NumBits-1.
9743   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9744
9745   if (VT == MVT::i8)
9746     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9747   return Op;
9748 }
9749
9750 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9751   EVT VT = Op.getValueType();
9752   EVT OpVT = VT;
9753   unsigned NumBits = VT.getSizeInBits();
9754   DebugLoc dl = Op.getDebugLoc();
9755
9756   Op = Op.getOperand(0);
9757   if (VT == MVT::i8) {
9758     OpVT = MVT::i32;
9759     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9760   }
9761
9762   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9763   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9764   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9765
9766   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9767   SDValue Ops[] = {
9768     Op,
9769     DAG.getConstant(NumBits, OpVT),
9770     DAG.getConstant(X86::COND_E, MVT::i8),
9771     Op.getValue(1)
9772   };
9773   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9774
9775   if (VT == MVT::i8)
9776     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9777   return Op;
9778 }
9779
9780 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9781 // ones, and then concatenate the result back.
9782 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9783   EVT VT = Op.getValueType();
9784
9785   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9786          "Unsupported value type for operation");
9787
9788   int NumElems = VT.getVectorNumElements();
9789   DebugLoc dl = Op.getDebugLoc();
9790   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9791   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9792
9793   // Extract the LHS vectors
9794   SDValue LHS = Op.getOperand(0);
9795   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9796   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9797
9798   // Extract the RHS vectors
9799   SDValue RHS = Op.getOperand(1);
9800   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9801   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9802
9803   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9804   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9805
9806   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9807                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9808                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9809 }
9810
9811 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9812   assert(Op.getValueType().getSizeInBits() == 256 &&
9813          Op.getValueType().isInteger() &&
9814          "Only handle AVX 256-bit vector integer operation");
9815   return Lower256IntArith(Op, DAG);
9816 }
9817
9818 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9819   assert(Op.getValueType().getSizeInBits() == 256 &&
9820          Op.getValueType().isInteger() &&
9821          "Only handle AVX 256-bit vector integer operation");
9822   return Lower256IntArith(Op, DAG);
9823 }
9824
9825 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9826   EVT VT = Op.getValueType();
9827
9828   // Decompose 256-bit ops into smaller 128-bit ops.
9829   if (VT.getSizeInBits() == 256)
9830     return Lower256IntArith(Op, DAG);
9831
9832   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9833   DebugLoc dl = Op.getDebugLoc();
9834
9835   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9836   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9837   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9838   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9839   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9840   //
9841   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9842   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9843   //  return AloBlo + AloBhi + AhiBlo;
9844
9845   SDValue A = Op.getOperand(0);
9846   SDValue B = Op.getOperand(1);
9847
9848   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9849                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9850                        A, DAG.getConstant(32, MVT::i32));
9851   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9852                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9853                        B, DAG.getConstant(32, MVT::i32));
9854   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9855                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9856                        A, B);
9857   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9858                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9859                        A, Bhi);
9860   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9861                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9862                        Ahi, B);
9863   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9864                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9865                        AloBhi, DAG.getConstant(32, MVT::i32));
9866   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9867                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9868                        AhiBlo, DAG.getConstant(32, MVT::i32));
9869   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9870   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9871   return Res;
9872 }
9873
9874 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9875
9876   EVT VT = Op.getValueType();
9877   DebugLoc dl = Op.getDebugLoc();
9878   SDValue R = Op.getOperand(0);
9879   SDValue Amt = Op.getOperand(1);
9880   LLVMContext *Context = DAG.getContext();
9881
9882   if (!Subtarget->hasXMMInt())
9883     return SDValue();
9884
9885   // Decompose 256-bit shifts into smaller 128-bit shifts.
9886   if (VT.getSizeInBits() == 256) {
9887     int NumElems = VT.getVectorNumElements();
9888     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9889     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9890
9891     // Extract the two vectors
9892     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9893     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9894                                      DAG, dl);
9895
9896     // Recreate the shift amount vectors
9897     SDValue Amt1, Amt2;
9898     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9899       // Constant shift amount
9900       SmallVector<SDValue, 4> Amt1Csts;
9901       SmallVector<SDValue, 4> Amt2Csts;
9902       for (int i = 0; i < NumElems/2; ++i)
9903         Amt1Csts.push_back(Amt->getOperand(i));
9904       for (int i = NumElems/2; i < NumElems; ++i)
9905         Amt2Csts.push_back(Amt->getOperand(i));
9906
9907       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9908                                  &Amt1Csts[0], NumElems/2);
9909       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9910                                  &Amt2Csts[0], NumElems/2);
9911     } else {
9912       // Variable shift amount
9913       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9914       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9915                                  DAG, dl);
9916     }
9917
9918     // Issue new vector shifts for the smaller types
9919     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9920     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9921
9922     // Concatenate the result back
9923     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9924   }
9925
9926   // Optimize shl/srl/sra with constant shift amount.
9927   if (isSplatVector(Amt.getNode())) {
9928     SDValue SclrAmt = Amt->getOperand(0);
9929     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9930       uint64_t ShiftAmt = C->getZExtValue();
9931
9932       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9933        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9934                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9935                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9936
9937       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9938        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9939                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9940                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9941
9942       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9943        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9944                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9945                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9946
9947       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9948        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9949                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9950                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9951
9952       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9953        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9954                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9955                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9956
9957       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9958        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9959                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9960                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9961
9962       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9963        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9964                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9965                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9966
9967       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9968        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9969                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9970                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9971     }
9972   }
9973
9974   // Lower SHL with variable shift amount.
9975   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9976     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9977                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9978                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9979
9980     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9981
9982     std::vector<Constant*> CV(4, CI);
9983     Constant *C = ConstantVector::get(CV);
9984     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9985     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9986                                  MachinePointerInfo::getConstantPool(),
9987                                  false, false, 16);
9988
9989     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9990     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9991     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9992     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9993   }
9994   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9995     // a = a << 5;
9996     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9997                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9998                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9999
10000     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10001     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10002
10003     std::vector<Constant*> CVM1(16, CM1);
10004     std::vector<Constant*> CVM2(16, CM2);
10005     Constant *C = ConstantVector::get(CVM1);
10006     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10007     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10008                             MachinePointerInfo::getConstantPool(),
10009                             false, false, 16);
10010
10011     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10012     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10013     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10014                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10015                     DAG.getConstant(4, MVT::i32));
10016     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10017     // a += a
10018     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10019
10020     C = ConstantVector::get(CVM2);
10021     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10022     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10023                     MachinePointerInfo::getConstantPool(),
10024                     false, false, 16);
10025
10026     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10027     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10028     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10029                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10030                     DAG.getConstant(2, MVT::i32));
10031     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10032     // a += a
10033     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10034
10035     // return pblendv(r, r+r, a);
10036     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10037                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10038     return R;
10039   }
10040   return SDValue();
10041 }
10042
10043 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10044   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10045   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10046   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10047   // has only one use.
10048   SDNode *N = Op.getNode();
10049   SDValue LHS = N->getOperand(0);
10050   SDValue RHS = N->getOperand(1);
10051   unsigned BaseOp = 0;
10052   unsigned Cond = 0;
10053   DebugLoc DL = Op.getDebugLoc();
10054   switch (Op.getOpcode()) {
10055   default: llvm_unreachable("Unknown ovf instruction!");
10056   case ISD::SADDO:
10057     // A subtract of one will be selected as a INC. Note that INC doesn't
10058     // set CF, so we can't do this for UADDO.
10059     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10060       if (C->isOne()) {
10061         BaseOp = X86ISD::INC;
10062         Cond = X86::COND_O;
10063         break;
10064       }
10065     BaseOp = X86ISD::ADD;
10066     Cond = X86::COND_O;
10067     break;
10068   case ISD::UADDO:
10069     BaseOp = X86ISD::ADD;
10070     Cond = X86::COND_B;
10071     break;
10072   case ISD::SSUBO:
10073     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10074     // set CF, so we can't do this for USUBO.
10075     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10076       if (C->isOne()) {
10077         BaseOp = X86ISD::DEC;
10078         Cond = X86::COND_O;
10079         break;
10080       }
10081     BaseOp = X86ISD::SUB;
10082     Cond = X86::COND_O;
10083     break;
10084   case ISD::USUBO:
10085     BaseOp = X86ISD::SUB;
10086     Cond = X86::COND_B;
10087     break;
10088   case ISD::SMULO:
10089     BaseOp = X86ISD::SMUL;
10090     Cond = X86::COND_O;
10091     break;
10092   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10093     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10094                                  MVT::i32);
10095     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10096
10097     SDValue SetCC =
10098       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10099                   DAG.getConstant(X86::COND_O, MVT::i32),
10100                   SDValue(Sum.getNode(), 2));
10101
10102     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10103   }
10104   }
10105
10106   // Also sets EFLAGS.
10107   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10108   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10109
10110   SDValue SetCC =
10111     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10112                 DAG.getConstant(Cond, MVT::i32),
10113                 SDValue(Sum.getNode(), 1));
10114
10115   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10116 }
10117
10118 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10119   DebugLoc dl = Op.getDebugLoc();
10120   SDNode* Node = Op.getNode();
10121   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10122   EVT VT = Node->getValueType(0);
10123   if (Subtarget->hasXMMInt() && VT.isVector()) {
10124     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10125                         ExtraVT.getScalarType().getSizeInBits();
10126     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10127
10128     unsigned SHLIntrinsicsID = 0;
10129     unsigned SRAIntrinsicsID = 0;
10130     switch (VT.getSimpleVT().SimpleTy) {
10131       default:
10132         return SDValue();
10133       case MVT::v4i32: {
10134         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10135         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10136         break;
10137       }
10138       case MVT::v8i16: {
10139         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10140         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10141         break;
10142       }
10143     }
10144
10145     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10146                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10147                          Node->getOperand(0), ShAmt);
10148
10149     // In case of 1 bit sext, no need to shr
10150     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10151
10152     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10153                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10154                        Tmp1, ShAmt);
10155   }
10156
10157   return SDValue();
10158 }
10159
10160
10161 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10162   DebugLoc dl = Op.getDebugLoc();
10163
10164   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10165   // There isn't any reason to disable it if the target processor supports it.
10166   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10167     SDValue Chain = Op.getOperand(0);
10168     SDValue Zero = DAG.getConstant(0, MVT::i32);
10169     SDValue Ops[] = {
10170       DAG.getRegister(X86::ESP, MVT::i32), // Base
10171       DAG.getTargetConstant(1, MVT::i8),   // Scale
10172       DAG.getRegister(0, MVT::i32),        // Index
10173       DAG.getTargetConstant(0, MVT::i32),  // Disp
10174       DAG.getRegister(0, MVT::i32),        // Segment.
10175       Zero,
10176       Chain
10177     };
10178     SDNode *Res =
10179       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10180                           array_lengthof(Ops));
10181     return SDValue(Res, 0);
10182   }
10183
10184   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10185   if (!isDev)
10186     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10187
10188   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10189   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10190   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10191   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10192
10193   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10194   if (!Op1 && !Op2 && !Op3 && Op4)
10195     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10196
10197   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10198   if (Op1 && !Op2 && !Op3 && !Op4)
10199     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10200
10201   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10202   //           (MFENCE)>;
10203   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10204 }
10205
10206 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10207                                              SelectionDAG &DAG) const {
10208   DebugLoc dl = Op.getDebugLoc();
10209   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10210     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10211   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10212     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10213
10214   // The only fence that needs an instruction is a sequentially-consistent
10215   // cross-thread fence.
10216   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10217     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10218     // no-sse2). There isn't any reason to disable it if the target processor
10219     // supports it.
10220     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10221       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10222
10223     SDValue Chain = Op.getOperand(0);
10224     SDValue Zero = DAG.getConstant(0, MVT::i32);
10225     SDValue Ops[] = {
10226       DAG.getRegister(X86::ESP, MVT::i32), // Base
10227       DAG.getTargetConstant(1, MVT::i8),   // Scale
10228       DAG.getRegister(0, MVT::i32),        // Index
10229       DAG.getTargetConstant(0, MVT::i32),  // Disp
10230       DAG.getRegister(0, MVT::i32),        // Segment.
10231       Zero,
10232       Chain
10233     };
10234     SDNode *Res =
10235       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10236                          array_lengthof(Ops));
10237     return SDValue(Res, 0);
10238   }
10239
10240   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10241   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10242 }
10243
10244
10245 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10246   EVT T = Op.getValueType();
10247   DebugLoc DL = Op.getDebugLoc();
10248   unsigned Reg = 0;
10249   unsigned size = 0;
10250   switch(T.getSimpleVT().SimpleTy) {
10251   default:
10252     assert(false && "Invalid value type!");
10253   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10254   case MVT::i16: Reg = X86::AX;  size = 2; break;
10255   case MVT::i32: Reg = X86::EAX; size = 4; break;
10256   case MVT::i64:
10257     assert(Subtarget->is64Bit() && "Node not type legal!");
10258     Reg = X86::RAX; size = 8;
10259     break;
10260   }
10261   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10262                                     Op.getOperand(2), SDValue());
10263   SDValue Ops[] = { cpIn.getValue(0),
10264                     Op.getOperand(1),
10265                     Op.getOperand(3),
10266                     DAG.getTargetConstant(size, MVT::i8),
10267                     cpIn.getValue(1) };
10268   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10269   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10270   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10271                                            Ops, 5, T, MMO);
10272   SDValue cpOut =
10273     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10274   return cpOut;
10275 }
10276
10277 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10278                                                  SelectionDAG &DAG) const {
10279   assert(Subtarget->is64Bit() && "Result not type legalized?");
10280   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10281   SDValue TheChain = Op.getOperand(0);
10282   DebugLoc dl = Op.getDebugLoc();
10283   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10284   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10285   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10286                                    rax.getValue(2));
10287   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10288                             DAG.getConstant(32, MVT::i8));
10289   SDValue Ops[] = {
10290     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10291     rdx.getValue(1)
10292   };
10293   return DAG.getMergeValues(Ops, 2, dl);
10294 }
10295
10296 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10297                                             SelectionDAG &DAG) const {
10298   EVT SrcVT = Op.getOperand(0).getValueType();
10299   EVT DstVT = Op.getValueType();
10300   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10301          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10302   assert((DstVT == MVT::i64 ||
10303           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10304          "Unexpected custom BITCAST");
10305   // i64 <=> MMX conversions are Legal.
10306   if (SrcVT==MVT::i64 && DstVT.isVector())
10307     return Op;
10308   if (DstVT==MVT::i64 && SrcVT.isVector())
10309     return Op;
10310   // MMX <=> MMX conversions are Legal.
10311   if (SrcVT.isVector() && DstVT.isVector())
10312     return Op;
10313   // All other conversions need to be expanded.
10314   return SDValue();
10315 }
10316
10317 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10318   SDNode *Node = Op.getNode();
10319   DebugLoc dl = Node->getDebugLoc();
10320   EVT T = Node->getValueType(0);
10321   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10322                               DAG.getConstant(0, T), Node->getOperand(2));
10323   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10324                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10325                        Node->getOperand(0),
10326                        Node->getOperand(1), negOp,
10327                        cast<AtomicSDNode>(Node)->getSrcValue(),
10328                        cast<AtomicSDNode>(Node)->getAlignment(),
10329                        cast<AtomicSDNode>(Node)->getOrdering(),
10330                        cast<AtomicSDNode>(Node)->getSynchScope());
10331 }
10332
10333 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10334   SDNode *Node = Op.getNode();
10335   DebugLoc dl = Node->getDebugLoc();
10336   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10337
10338   // Convert seq_cst store -> xchg
10339   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10340   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10341   //        (The only way to get a 16-byte store is cmpxchg16b)
10342   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10343   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10344       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10345     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10346                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10347                                  Node->getOperand(0),
10348                                  Node->getOperand(1), Node->getOperand(2),
10349                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10350                                  cast<AtomicSDNode>(Node)->getOrdering(),
10351                                  cast<AtomicSDNode>(Node)->getSynchScope());
10352     return Swap.getValue(1);
10353   }
10354   // Other atomic stores have a simple pattern.
10355   return Op;
10356 }
10357
10358 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10359   EVT VT = Op.getNode()->getValueType(0);
10360
10361   // Let legalize expand this if it isn't a legal type yet.
10362   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10363     return SDValue();
10364
10365   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10366
10367   unsigned Opc;
10368   bool ExtraOp = false;
10369   switch (Op.getOpcode()) {
10370   default: assert(0 && "Invalid code");
10371   case ISD::ADDC: Opc = X86ISD::ADD; break;
10372   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10373   case ISD::SUBC: Opc = X86ISD::SUB; break;
10374   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10375   }
10376
10377   if (!ExtraOp)
10378     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10379                        Op.getOperand(1));
10380   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10381                      Op.getOperand(1), Op.getOperand(2));
10382 }
10383
10384 /// LowerOperation - Provide custom lowering hooks for some operations.
10385 ///
10386 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10387   switch (Op.getOpcode()) {
10388   default: llvm_unreachable("Should not custom lower this!");
10389   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10390   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10391   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10392   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10393   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10394   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10395   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10396   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10397   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10398   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10399   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10400   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10401   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10402   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10403   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10404   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10405   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10406   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10407   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10408   case ISD::SHL_PARTS:
10409   case ISD::SRA_PARTS:
10410   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10411   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10412   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10413   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10414   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10415   case ISD::FABS:               return LowerFABS(Op, DAG);
10416   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10417   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10418   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10419   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10420   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10421   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10422   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10423   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10424   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10425   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10426   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10427   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10428   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10429   case ISD::FRAME_TO_ARGS_OFFSET:
10430                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10431   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10432   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10433   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10434   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10435   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10436   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10437   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10438   case ISD::MUL:                return LowerMUL(Op, DAG);
10439   case ISD::SRA:
10440   case ISD::SRL:
10441   case ISD::SHL:                return LowerShift(Op, DAG);
10442   case ISD::SADDO:
10443   case ISD::UADDO:
10444   case ISD::SSUBO:
10445   case ISD::USUBO:
10446   case ISD::SMULO:
10447   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10448   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10449   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10450   case ISD::ADDC:
10451   case ISD::ADDE:
10452   case ISD::SUBC:
10453   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10454   case ISD::ADD:                return LowerADD(Op, DAG);
10455   case ISD::SUB:                return LowerSUB(Op, DAG);
10456   }
10457 }
10458
10459 static void ReplaceATOMIC_LOAD(SDNode *Node,
10460                                   SmallVectorImpl<SDValue> &Results,
10461                                   SelectionDAG &DAG) {
10462   DebugLoc dl = Node->getDebugLoc();
10463   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10464
10465   // Convert wide load -> cmpxchg8b/cmpxchg16b
10466   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10467   //        (The only way to get a 16-byte load is cmpxchg16b)
10468   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10469   SDValue Zero = DAG.getConstant(0, VT);
10470   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10471                                Node->getOperand(0),
10472                                Node->getOperand(1), Zero, Zero,
10473                                cast<AtomicSDNode>(Node)->getMemOperand(),
10474                                cast<AtomicSDNode>(Node)->getOrdering(),
10475                                cast<AtomicSDNode>(Node)->getSynchScope());
10476   Results.push_back(Swap.getValue(0));
10477   Results.push_back(Swap.getValue(1));
10478 }
10479
10480 void X86TargetLowering::
10481 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10482                         SelectionDAG &DAG, unsigned NewOp) const {
10483   DebugLoc dl = Node->getDebugLoc();
10484   assert (Node->getValueType(0) == MVT::i64 &&
10485           "Only know how to expand i64 atomics");
10486
10487   SDValue Chain = Node->getOperand(0);
10488   SDValue In1 = Node->getOperand(1);
10489   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10490                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10491   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10492                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10493   SDValue Ops[] = { Chain, In1, In2L, In2H };
10494   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10495   SDValue Result =
10496     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10497                             cast<MemSDNode>(Node)->getMemOperand());
10498   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10499   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10500   Results.push_back(Result.getValue(2));
10501 }
10502
10503 /// ReplaceNodeResults - Replace a node with an illegal result type
10504 /// with a new node built out of custom code.
10505 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10506                                            SmallVectorImpl<SDValue>&Results,
10507                                            SelectionDAG &DAG) const {
10508   DebugLoc dl = N->getDebugLoc();
10509   switch (N->getOpcode()) {
10510   default:
10511     assert(false && "Do not know how to custom type legalize this operation!");
10512     return;
10513   case ISD::SIGN_EXTEND_INREG:
10514   case ISD::ADDC:
10515   case ISD::ADDE:
10516   case ISD::SUBC:
10517   case ISD::SUBE:
10518     // We don't want to expand or promote these.
10519     return;
10520   case ISD::FP_TO_SINT: {
10521     std::pair<SDValue,SDValue> Vals =
10522         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10523     SDValue FIST = Vals.first, StackSlot = Vals.second;
10524     if (FIST.getNode() != 0) {
10525       EVT VT = N->getValueType(0);
10526       // Return a load from the stack slot.
10527       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10528                                     MachinePointerInfo(), false, false, 0));
10529     }
10530     return;
10531   }
10532   case ISD::READCYCLECOUNTER: {
10533     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10534     SDValue TheChain = N->getOperand(0);
10535     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10536     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10537                                      rd.getValue(1));
10538     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10539                                      eax.getValue(2));
10540     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10541     SDValue Ops[] = { eax, edx };
10542     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10543     Results.push_back(edx.getValue(1));
10544     return;
10545   }
10546   case ISD::ATOMIC_CMP_SWAP: {
10547     EVT T = N->getValueType(0);
10548     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10549     bool Regs64bit = T == MVT::i128;
10550     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10551     SDValue cpInL, cpInH;
10552     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10553                         DAG.getConstant(0, HalfT));
10554     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10555                         DAG.getConstant(1, HalfT));
10556     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10557                              Regs64bit ? X86::RAX : X86::EAX,
10558                              cpInL, SDValue());
10559     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10560                              Regs64bit ? X86::RDX : X86::EDX,
10561                              cpInH, cpInL.getValue(1));
10562     SDValue swapInL, swapInH;
10563     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10564                           DAG.getConstant(0, HalfT));
10565     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10566                           DAG.getConstant(1, HalfT));
10567     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10568                                Regs64bit ? X86::RBX : X86::EBX,
10569                                swapInL, cpInH.getValue(1));
10570     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10571                                Regs64bit ? X86::RCX : X86::ECX, 
10572                                swapInH, swapInL.getValue(1));
10573     SDValue Ops[] = { swapInH.getValue(0),
10574                       N->getOperand(1),
10575                       swapInH.getValue(1) };
10576     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10577     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10578     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10579                                   X86ISD::LCMPXCHG8_DAG;
10580     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10581                                              Ops, 3, T, MMO);
10582     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10583                                         Regs64bit ? X86::RAX : X86::EAX,
10584                                         HalfT, Result.getValue(1));
10585     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10586                                         Regs64bit ? X86::RDX : X86::EDX,
10587                                         HalfT, cpOutL.getValue(2));
10588     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10589     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10590     Results.push_back(cpOutH.getValue(1));
10591     return;
10592   }
10593   case ISD::ATOMIC_LOAD_ADD:
10594     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10595     return;
10596   case ISD::ATOMIC_LOAD_AND:
10597     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10598     return;
10599   case ISD::ATOMIC_LOAD_NAND:
10600     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10601     return;
10602   case ISD::ATOMIC_LOAD_OR:
10603     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10604     return;
10605   case ISD::ATOMIC_LOAD_SUB:
10606     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10607     return;
10608   case ISD::ATOMIC_LOAD_XOR:
10609     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10610     return;
10611   case ISD::ATOMIC_SWAP:
10612     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10613     return;
10614   case ISD::ATOMIC_LOAD:
10615     ReplaceATOMIC_LOAD(N, Results, DAG);
10616   }
10617 }
10618
10619 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10620   switch (Opcode) {
10621   default: return NULL;
10622   case X86ISD::BSF:                return "X86ISD::BSF";
10623   case X86ISD::BSR:                return "X86ISD::BSR";
10624   case X86ISD::SHLD:               return "X86ISD::SHLD";
10625   case X86ISD::SHRD:               return "X86ISD::SHRD";
10626   case X86ISD::FAND:               return "X86ISD::FAND";
10627   case X86ISD::FOR:                return "X86ISD::FOR";
10628   case X86ISD::FXOR:               return "X86ISD::FXOR";
10629   case X86ISD::FSRL:               return "X86ISD::FSRL";
10630   case X86ISD::FILD:               return "X86ISD::FILD";
10631   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10632   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10633   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10634   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10635   case X86ISD::FLD:                return "X86ISD::FLD";
10636   case X86ISD::FST:                return "X86ISD::FST";
10637   case X86ISD::CALL:               return "X86ISD::CALL";
10638   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10639   case X86ISD::BT:                 return "X86ISD::BT";
10640   case X86ISD::CMP:                return "X86ISD::CMP";
10641   case X86ISD::COMI:               return "X86ISD::COMI";
10642   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10643   case X86ISD::SETCC:              return "X86ISD::SETCC";
10644   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10645   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10646   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10647   case X86ISD::CMOV:               return "X86ISD::CMOV";
10648   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10649   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10650   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10651   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10652   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10653   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10654   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10655   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10656   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10657   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10658   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10659   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10660   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10661   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10662   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10663   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10664   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10665   case X86ISD::FMAX:               return "X86ISD::FMAX";
10666   case X86ISD::FMIN:               return "X86ISD::FMIN";
10667   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10668   case X86ISD::FRCP:               return "X86ISD::FRCP";
10669   case X86ISD::FHADD:              return "X86ISD::FHADD";
10670   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10671   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10672   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10673   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10674   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10675   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10676   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10677   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10678   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10679   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10680   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10681   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10682   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10683   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10684   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10685   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10686   case X86ISD::VSHL:               return "X86ISD::VSHL";
10687   case X86ISD::VSRL:               return "X86ISD::VSRL";
10688   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10689   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10690   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10691   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10692   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10693   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10694   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10695   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10696   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10697   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10698   case X86ISD::ADD:                return "X86ISD::ADD";
10699   case X86ISD::SUB:                return "X86ISD::SUB";
10700   case X86ISD::ADC:                return "X86ISD::ADC";
10701   case X86ISD::SBB:                return "X86ISD::SBB";
10702   case X86ISD::SMUL:               return "X86ISD::SMUL";
10703   case X86ISD::UMUL:               return "X86ISD::UMUL";
10704   case X86ISD::INC:                return "X86ISD::INC";
10705   case X86ISD::DEC:                return "X86ISD::DEC";
10706   case X86ISD::OR:                 return "X86ISD::OR";
10707   case X86ISD::XOR:                return "X86ISD::XOR";
10708   case X86ISD::AND:                return "X86ISD::AND";
10709   case X86ISD::ANDN:               return "X86ISD::ANDN";
10710   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10711   case X86ISD::PTEST:              return "X86ISD::PTEST";
10712   case X86ISD::TESTP:              return "X86ISD::TESTP";
10713   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10714   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10715   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10716   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10717   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10718   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10719   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10720   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10721   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10722   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10723   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10724   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10725   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10726   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10727   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10728   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10729   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10730   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10731   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10732   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10733   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10734   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10735   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10736   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10737   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10738   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10739   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10740   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10741   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10742   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10743   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10744   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10745   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10746   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10747   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10748   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10749   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10750   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10751   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10752   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10753   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10754   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10755   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10756   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10757   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10758   }
10759 }
10760
10761 // isLegalAddressingMode - Return true if the addressing mode represented
10762 // by AM is legal for this target, for a load/store of the specified type.
10763 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10764                                               Type *Ty) const {
10765   // X86 supports extremely general addressing modes.
10766   CodeModel::Model M = getTargetMachine().getCodeModel();
10767   Reloc::Model R = getTargetMachine().getRelocationModel();
10768
10769   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10770   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10771     return false;
10772
10773   if (AM.BaseGV) {
10774     unsigned GVFlags =
10775       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10776
10777     // If a reference to this global requires an extra load, we can't fold it.
10778     if (isGlobalStubReference(GVFlags))
10779       return false;
10780
10781     // If BaseGV requires a register for the PIC base, we cannot also have a
10782     // BaseReg specified.
10783     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10784       return false;
10785
10786     // If lower 4G is not available, then we must use rip-relative addressing.
10787     if ((M != CodeModel::Small || R != Reloc::Static) &&
10788         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10789       return false;
10790   }
10791
10792   switch (AM.Scale) {
10793   case 0:
10794   case 1:
10795   case 2:
10796   case 4:
10797   case 8:
10798     // These scales always work.
10799     break;
10800   case 3:
10801   case 5:
10802   case 9:
10803     // These scales are formed with basereg+scalereg.  Only accept if there is
10804     // no basereg yet.
10805     if (AM.HasBaseReg)
10806       return false;
10807     break;
10808   default:  // Other stuff never works.
10809     return false;
10810   }
10811
10812   return true;
10813 }
10814
10815
10816 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10817   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10818     return false;
10819   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10820   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10821   if (NumBits1 <= NumBits2)
10822     return false;
10823   return true;
10824 }
10825
10826 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10827   if (!VT1.isInteger() || !VT2.isInteger())
10828     return false;
10829   unsigned NumBits1 = VT1.getSizeInBits();
10830   unsigned NumBits2 = VT2.getSizeInBits();
10831   if (NumBits1 <= NumBits2)
10832     return false;
10833   return true;
10834 }
10835
10836 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10837   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10838   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10839 }
10840
10841 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10842   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10843   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10844 }
10845
10846 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10847   // i16 instructions are longer (0x66 prefix) and potentially slower.
10848   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10849 }
10850
10851 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10852 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10853 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10854 /// are assumed to be legal.
10855 bool
10856 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10857                                       EVT VT) const {
10858   // Very little shuffling can be done for 64-bit vectors right now.
10859   if (VT.getSizeInBits() == 64)
10860     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
10861
10862   // FIXME: pshufb, blends, shifts.
10863   return (VT.getVectorNumElements() == 2 ||
10864           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10865           isMOVLMask(M, VT) ||
10866           isSHUFPMask(M, VT) ||
10867           isPSHUFDMask(M, VT) ||
10868           isPSHUFHWMask(M, VT) ||
10869           isPSHUFLWMask(M, VT) ||
10870           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
10871           isUNPCKLMask(M, VT) ||
10872           isUNPCKHMask(M, VT) ||
10873           isUNPCKL_v_undef_Mask(M, VT) ||
10874           isUNPCKH_v_undef_Mask(M, VT));
10875 }
10876
10877 bool
10878 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10879                                           EVT VT) const {
10880   unsigned NumElts = VT.getVectorNumElements();
10881   // FIXME: This collection of masks seems suspect.
10882   if (NumElts == 2)
10883     return true;
10884   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10885     return (isMOVLMask(Mask, VT)  ||
10886             isCommutedMOVLMask(Mask, VT, true) ||
10887             isSHUFPMask(Mask, VT) ||
10888             isCommutedSHUFPMask(Mask, VT));
10889   }
10890   return false;
10891 }
10892
10893 //===----------------------------------------------------------------------===//
10894 //                           X86 Scheduler Hooks
10895 //===----------------------------------------------------------------------===//
10896
10897 // private utility function
10898 MachineBasicBlock *
10899 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10900                                                        MachineBasicBlock *MBB,
10901                                                        unsigned regOpc,
10902                                                        unsigned immOpc,
10903                                                        unsigned LoadOpc,
10904                                                        unsigned CXchgOpc,
10905                                                        unsigned notOpc,
10906                                                        unsigned EAXreg,
10907                                                        TargetRegisterClass *RC,
10908                                                        bool invSrc) const {
10909   // For the atomic bitwise operator, we generate
10910   //   thisMBB:
10911   //   newMBB:
10912   //     ld  t1 = [bitinstr.addr]
10913   //     op  t2 = t1, [bitinstr.val]
10914   //     mov EAX = t1
10915   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10916   //     bz  newMBB
10917   //     fallthrough -->nextMBB
10918   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10919   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10920   MachineFunction::iterator MBBIter = MBB;
10921   ++MBBIter;
10922
10923   /// First build the CFG
10924   MachineFunction *F = MBB->getParent();
10925   MachineBasicBlock *thisMBB = MBB;
10926   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10927   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10928   F->insert(MBBIter, newMBB);
10929   F->insert(MBBIter, nextMBB);
10930
10931   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10932   nextMBB->splice(nextMBB->begin(), thisMBB,
10933                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10934                   thisMBB->end());
10935   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10936
10937   // Update thisMBB to fall through to newMBB
10938   thisMBB->addSuccessor(newMBB);
10939
10940   // newMBB jumps to itself and fall through to nextMBB
10941   newMBB->addSuccessor(nextMBB);
10942   newMBB->addSuccessor(newMBB);
10943
10944   // Insert instructions into newMBB based on incoming instruction
10945   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10946          "unexpected number of operands");
10947   DebugLoc dl = bInstr->getDebugLoc();
10948   MachineOperand& destOper = bInstr->getOperand(0);
10949   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10950   int numArgs = bInstr->getNumOperands() - 1;
10951   for (int i=0; i < numArgs; ++i)
10952     argOpers[i] = &bInstr->getOperand(i+1);
10953
10954   // x86 address has 4 operands: base, index, scale, and displacement
10955   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10956   int valArgIndx = lastAddrIndx + 1;
10957
10958   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10959   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10960   for (int i=0; i <= lastAddrIndx; ++i)
10961     (*MIB).addOperand(*argOpers[i]);
10962
10963   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10964   if (invSrc) {
10965     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10966   }
10967   else
10968     tt = t1;
10969
10970   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10971   assert((argOpers[valArgIndx]->isReg() ||
10972           argOpers[valArgIndx]->isImm()) &&
10973          "invalid operand");
10974   if (argOpers[valArgIndx]->isReg())
10975     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10976   else
10977     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10978   MIB.addReg(tt);
10979   (*MIB).addOperand(*argOpers[valArgIndx]);
10980
10981   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10982   MIB.addReg(t1);
10983
10984   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10985   for (int i=0; i <= lastAddrIndx; ++i)
10986     (*MIB).addOperand(*argOpers[i]);
10987   MIB.addReg(t2);
10988   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10989   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10990                     bInstr->memoperands_end());
10991
10992   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10993   MIB.addReg(EAXreg);
10994
10995   // insert branch
10996   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10997
10998   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10999   return nextMBB;
11000 }
11001
11002 // private utility function:  64 bit atomics on 32 bit host.
11003 MachineBasicBlock *
11004 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11005                                                        MachineBasicBlock *MBB,
11006                                                        unsigned regOpcL,
11007                                                        unsigned regOpcH,
11008                                                        unsigned immOpcL,
11009                                                        unsigned immOpcH,
11010                                                        bool invSrc) const {
11011   // For the atomic bitwise operator, we generate
11012   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11013   //     ld t1,t2 = [bitinstr.addr]
11014   //   newMBB:
11015   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11016   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11017   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11018   //     mov ECX, EBX <- t5, t6
11019   //     mov EAX, EDX <- t1, t2
11020   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11021   //     mov t3, t4 <- EAX, EDX
11022   //     bz  newMBB
11023   //     result in out1, out2
11024   //     fallthrough -->nextMBB
11025
11026   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11027   const unsigned LoadOpc = X86::MOV32rm;
11028   const unsigned NotOpc = X86::NOT32r;
11029   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11030   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11031   MachineFunction::iterator MBBIter = MBB;
11032   ++MBBIter;
11033
11034   /// First build the CFG
11035   MachineFunction *F = MBB->getParent();
11036   MachineBasicBlock *thisMBB = MBB;
11037   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11038   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11039   F->insert(MBBIter, newMBB);
11040   F->insert(MBBIter, nextMBB);
11041
11042   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11043   nextMBB->splice(nextMBB->begin(), thisMBB,
11044                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11045                   thisMBB->end());
11046   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11047
11048   // Update thisMBB to fall through to newMBB
11049   thisMBB->addSuccessor(newMBB);
11050
11051   // newMBB jumps to itself and fall through to nextMBB
11052   newMBB->addSuccessor(nextMBB);
11053   newMBB->addSuccessor(newMBB);
11054
11055   DebugLoc dl = bInstr->getDebugLoc();
11056   // Insert instructions into newMBB based on incoming instruction
11057   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11058   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11059          "unexpected number of operands");
11060   MachineOperand& dest1Oper = bInstr->getOperand(0);
11061   MachineOperand& dest2Oper = bInstr->getOperand(1);
11062   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11063   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11064     argOpers[i] = &bInstr->getOperand(i+2);
11065
11066     // We use some of the operands multiple times, so conservatively just
11067     // clear any kill flags that might be present.
11068     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11069       argOpers[i]->setIsKill(false);
11070   }
11071
11072   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11073   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11074
11075   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11076   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11077   for (int i=0; i <= lastAddrIndx; ++i)
11078     (*MIB).addOperand(*argOpers[i]);
11079   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11080   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11081   // add 4 to displacement.
11082   for (int i=0; i <= lastAddrIndx-2; ++i)
11083     (*MIB).addOperand(*argOpers[i]);
11084   MachineOperand newOp3 = *(argOpers[3]);
11085   if (newOp3.isImm())
11086     newOp3.setImm(newOp3.getImm()+4);
11087   else
11088     newOp3.setOffset(newOp3.getOffset()+4);
11089   (*MIB).addOperand(newOp3);
11090   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11091
11092   // t3/4 are defined later, at the bottom of the loop
11093   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11094   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11095   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11096     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11097   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11098     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11099
11100   // The subsequent operations should be using the destination registers of
11101   //the PHI instructions.
11102   if (invSrc) {
11103     t1 = F->getRegInfo().createVirtualRegister(RC);
11104     t2 = F->getRegInfo().createVirtualRegister(RC);
11105     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11106     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11107   } else {
11108     t1 = dest1Oper.getReg();
11109     t2 = dest2Oper.getReg();
11110   }
11111
11112   int valArgIndx = lastAddrIndx + 1;
11113   assert((argOpers[valArgIndx]->isReg() ||
11114           argOpers[valArgIndx]->isImm()) &&
11115          "invalid operand");
11116   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11117   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11118   if (argOpers[valArgIndx]->isReg())
11119     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11120   else
11121     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11122   if (regOpcL != X86::MOV32rr)
11123     MIB.addReg(t1);
11124   (*MIB).addOperand(*argOpers[valArgIndx]);
11125   assert(argOpers[valArgIndx + 1]->isReg() ==
11126          argOpers[valArgIndx]->isReg());
11127   assert(argOpers[valArgIndx + 1]->isImm() ==
11128          argOpers[valArgIndx]->isImm());
11129   if (argOpers[valArgIndx + 1]->isReg())
11130     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11131   else
11132     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11133   if (regOpcH != X86::MOV32rr)
11134     MIB.addReg(t2);
11135   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11136
11137   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11138   MIB.addReg(t1);
11139   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11140   MIB.addReg(t2);
11141
11142   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11143   MIB.addReg(t5);
11144   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11145   MIB.addReg(t6);
11146
11147   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11148   for (int i=0; i <= lastAddrIndx; ++i)
11149     (*MIB).addOperand(*argOpers[i]);
11150
11151   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11152   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11153                     bInstr->memoperands_end());
11154
11155   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11156   MIB.addReg(X86::EAX);
11157   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11158   MIB.addReg(X86::EDX);
11159
11160   // insert branch
11161   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11162
11163   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11164   return nextMBB;
11165 }
11166
11167 // private utility function
11168 MachineBasicBlock *
11169 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11170                                                       MachineBasicBlock *MBB,
11171                                                       unsigned cmovOpc) const {
11172   // For the atomic min/max operator, we generate
11173   //   thisMBB:
11174   //   newMBB:
11175   //     ld t1 = [min/max.addr]
11176   //     mov t2 = [min/max.val]
11177   //     cmp  t1, t2
11178   //     cmov[cond] t2 = t1
11179   //     mov EAX = t1
11180   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11181   //     bz   newMBB
11182   //     fallthrough -->nextMBB
11183   //
11184   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11185   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11186   MachineFunction::iterator MBBIter = MBB;
11187   ++MBBIter;
11188
11189   /// First build the CFG
11190   MachineFunction *F = MBB->getParent();
11191   MachineBasicBlock *thisMBB = MBB;
11192   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11193   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11194   F->insert(MBBIter, newMBB);
11195   F->insert(MBBIter, nextMBB);
11196
11197   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11198   nextMBB->splice(nextMBB->begin(), thisMBB,
11199                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11200                   thisMBB->end());
11201   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11202
11203   // Update thisMBB to fall through to newMBB
11204   thisMBB->addSuccessor(newMBB);
11205
11206   // newMBB jumps to newMBB and fall through to nextMBB
11207   newMBB->addSuccessor(nextMBB);
11208   newMBB->addSuccessor(newMBB);
11209
11210   DebugLoc dl = mInstr->getDebugLoc();
11211   // Insert instructions into newMBB based on incoming instruction
11212   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11213          "unexpected number of operands");
11214   MachineOperand& destOper = mInstr->getOperand(0);
11215   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11216   int numArgs = mInstr->getNumOperands() - 1;
11217   for (int i=0; i < numArgs; ++i)
11218     argOpers[i] = &mInstr->getOperand(i+1);
11219
11220   // x86 address has 4 operands: base, index, scale, and displacement
11221   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11222   int valArgIndx = lastAddrIndx + 1;
11223
11224   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11225   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11226   for (int i=0; i <= lastAddrIndx; ++i)
11227     (*MIB).addOperand(*argOpers[i]);
11228
11229   // We only support register and immediate values
11230   assert((argOpers[valArgIndx]->isReg() ||
11231           argOpers[valArgIndx]->isImm()) &&
11232          "invalid operand");
11233
11234   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11235   if (argOpers[valArgIndx]->isReg())
11236     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11237   else
11238     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11239   (*MIB).addOperand(*argOpers[valArgIndx]);
11240
11241   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11242   MIB.addReg(t1);
11243
11244   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11245   MIB.addReg(t1);
11246   MIB.addReg(t2);
11247
11248   // Generate movc
11249   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11250   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11251   MIB.addReg(t2);
11252   MIB.addReg(t1);
11253
11254   // Cmp and exchange if none has modified the memory location
11255   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11256   for (int i=0; i <= lastAddrIndx; ++i)
11257     (*MIB).addOperand(*argOpers[i]);
11258   MIB.addReg(t3);
11259   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11260   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11261                     mInstr->memoperands_end());
11262
11263   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11264   MIB.addReg(X86::EAX);
11265
11266   // insert branch
11267   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11268
11269   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11270   return nextMBB;
11271 }
11272
11273 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11274 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11275 // in the .td file.
11276 MachineBasicBlock *
11277 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11278                             unsigned numArgs, bool memArg) const {
11279   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11280          "Target must have SSE4.2 or AVX features enabled");
11281
11282   DebugLoc dl = MI->getDebugLoc();
11283   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11284   unsigned Opc;
11285   if (!Subtarget->hasAVX()) {
11286     if (memArg)
11287       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11288     else
11289       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11290   } else {
11291     if (memArg)
11292       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11293     else
11294       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11295   }
11296
11297   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11298   for (unsigned i = 0; i < numArgs; ++i) {
11299     MachineOperand &Op = MI->getOperand(i+1);
11300     if (!(Op.isReg() && Op.isImplicit()))
11301       MIB.addOperand(Op);
11302   }
11303   BuildMI(*BB, MI, dl,
11304     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11305              MI->getOperand(0).getReg())
11306     .addReg(X86::XMM0);
11307
11308   MI->eraseFromParent();
11309   return BB;
11310 }
11311
11312 MachineBasicBlock *
11313 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11314   DebugLoc dl = MI->getDebugLoc();
11315   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11316
11317   // Address into RAX/EAX, other two args into ECX, EDX.
11318   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11319   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11320   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11321   for (int i = 0; i < X86::AddrNumOperands; ++i)
11322     MIB.addOperand(MI->getOperand(i));
11323
11324   unsigned ValOps = X86::AddrNumOperands;
11325   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11326     .addReg(MI->getOperand(ValOps).getReg());
11327   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11328     .addReg(MI->getOperand(ValOps+1).getReg());
11329
11330   // The instruction doesn't actually take any operands though.
11331   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11332
11333   MI->eraseFromParent(); // The pseudo is gone now.
11334   return BB;
11335 }
11336
11337 MachineBasicBlock *
11338 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11339   DebugLoc dl = MI->getDebugLoc();
11340   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11341
11342   // First arg in ECX, the second in EAX.
11343   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11344     .addReg(MI->getOperand(0).getReg());
11345   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11346     .addReg(MI->getOperand(1).getReg());
11347
11348   // The instruction doesn't actually take any operands though.
11349   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11350
11351   MI->eraseFromParent(); // The pseudo is gone now.
11352   return BB;
11353 }
11354
11355 MachineBasicBlock *
11356 X86TargetLowering::EmitVAARG64WithCustomInserter(
11357                    MachineInstr *MI,
11358                    MachineBasicBlock *MBB) const {
11359   // Emit va_arg instruction on X86-64.
11360
11361   // Operands to this pseudo-instruction:
11362   // 0  ) Output        : destination address (reg)
11363   // 1-5) Input         : va_list address (addr, i64mem)
11364   // 6  ) ArgSize       : Size (in bytes) of vararg type
11365   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11366   // 8  ) Align         : Alignment of type
11367   // 9  ) EFLAGS (implicit-def)
11368
11369   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11370   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11371
11372   unsigned DestReg = MI->getOperand(0).getReg();
11373   MachineOperand &Base = MI->getOperand(1);
11374   MachineOperand &Scale = MI->getOperand(2);
11375   MachineOperand &Index = MI->getOperand(3);
11376   MachineOperand &Disp = MI->getOperand(4);
11377   MachineOperand &Segment = MI->getOperand(5);
11378   unsigned ArgSize = MI->getOperand(6).getImm();
11379   unsigned ArgMode = MI->getOperand(7).getImm();
11380   unsigned Align = MI->getOperand(8).getImm();
11381
11382   // Memory Reference
11383   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11384   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11385   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11386
11387   // Machine Information
11388   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11389   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11390   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11391   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11392   DebugLoc DL = MI->getDebugLoc();
11393
11394   // struct va_list {
11395   //   i32   gp_offset
11396   //   i32   fp_offset
11397   //   i64   overflow_area (address)
11398   //   i64   reg_save_area (address)
11399   // }
11400   // sizeof(va_list) = 24
11401   // alignment(va_list) = 8
11402
11403   unsigned TotalNumIntRegs = 6;
11404   unsigned TotalNumXMMRegs = 8;
11405   bool UseGPOffset = (ArgMode == 1);
11406   bool UseFPOffset = (ArgMode == 2);
11407   unsigned MaxOffset = TotalNumIntRegs * 8 +
11408                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11409
11410   /* Align ArgSize to a multiple of 8 */
11411   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11412   bool NeedsAlign = (Align > 8);
11413
11414   MachineBasicBlock *thisMBB = MBB;
11415   MachineBasicBlock *overflowMBB;
11416   MachineBasicBlock *offsetMBB;
11417   MachineBasicBlock *endMBB;
11418
11419   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11420   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11421   unsigned OffsetReg = 0;
11422
11423   if (!UseGPOffset && !UseFPOffset) {
11424     // If we only pull from the overflow region, we don't create a branch.
11425     // We don't need to alter control flow.
11426     OffsetDestReg = 0; // unused
11427     OverflowDestReg = DestReg;
11428
11429     offsetMBB = NULL;
11430     overflowMBB = thisMBB;
11431     endMBB = thisMBB;
11432   } else {
11433     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11434     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11435     // If not, pull from overflow_area. (branch to overflowMBB)
11436     //
11437     //       thisMBB
11438     //         |     .
11439     //         |        .
11440     //     offsetMBB   overflowMBB
11441     //         |        .
11442     //         |     .
11443     //        endMBB
11444
11445     // Registers for the PHI in endMBB
11446     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11447     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11448
11449     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11450     MachineFunction *MF = MBB->getParent();
11451     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11452     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11453     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11454
11455     MachineFunction::iterator MBBIter = MBB;
11456     ++MBBIter;
11457
11458     // Insert the new basic blocks
11459     MF->insert(MBBIter, offsetMBB);
11460     MF->insert(MBBIter, overflowMBB);
11461     MF->insert(MBBIter, endMBB);
11462
11463     // Transfer the remainder of MBB and its successor edges to endMBB.
11464     endMBB->splice(endMBB->begin(), thisMBB,
11465                     llvm::next(MachineBasicBlock::iterator(MI)),
11466                     thisMBB->end());
11467     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11468
11469     // Make offsetMBB and overflowMBB successors of thisMBB
11470     thisMBB->addSuccessor(offsetMBB);
11471     thisMBB->addSuccessor(overflowMBB);
11472
11473     // endMBB is a successor of both offsetMBB and overflowMBB
11474     offsetMBB->addSuccessor(endMBB);
11475     overflowMBB->addSuccessor(endMBB);
11476
11477     // Load the offset value into a register
11478     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11479     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11480       .addOperand(Base)
11481       .addOperand(Scale)
11482       .addOperand(Index)
11483       .addDisp(Disp, UseFPOffset ? 4 : 0)
11484       .addOperand(Segment)
11485       .setMemRefs(MMOBegin, MMOEnd);
11486
11487     // Check if there is enough room left to pull this argument.
11488     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11489       .addReg(OffsetReg)
11490       .addImm(MaxOffset + 8 - ArgSizeA8);
11491
11492     // Branch to "overflowMBB" if offset >= max
11493     // Fall through to "offsetMBB" otherwise
11494     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11495       .addMBB(overflowMBB);
11496   }
11497
11498   // In offsetMBB, emit code to use the reg_save_area.
11499   if (offsetMBB) {
11500     assert(OffsetReg != 0);
11501
11502     // Read the reg_save_area address.
11503     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11504     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11505       .addOperand(Base)
11506       .addOperand(Scale)
11507       .addOperand(Index)
11508       .addDisp(Disp, 16)
11509       .addOperand(Segment)
11510       .setMemRefs(MMOBegin, MMOEnd);
11511
11512     // Zero-extend the offset
11513     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11514       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11515         .addImm(0)
11516         .addReg(OffsetReg)
11517         .addImm(X86::sub_32bit);
11518
11519     // Add the offset to the reg_save_area to get the final address.
11520     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11521       .addReg(OffsetReg64)
11522       .addReg(RegSaveReg);
11523
11524     // Compute the offset for the next argument
11525     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11526     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11527       .addReg(OffsetReg)
11528       .addImm(UseFPOffset ? 16 : 8);
11529
11530     // Store it back into the va_list.
11531     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11532       .addOperand(Base)
11533       .addOperand(Scale)
11534       .addOperand(Index)
11535       .addDisp(Disp, UseFPOffset ? 4 : 0)
11536       .addOperand(Segment)
11537       .addReg(NextOffsetReg)
11538       .setMemRefs(MMOBegin, MMOEnd);
11539
11540     // Jump to endMBB
11541     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11542       .addMBB(endMBB);
11543   }
11544
11545   //
11546   // Emit code to use overflow area
11547   //
11548
11549   // Load the overflow_area address into a register.
11550   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11551   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11552     .addOperand(Base)
11553     .addOperand(Scale)
11554     .addOperand(Index)
11555     .addDisp(Disp, 8)
11556     .addOperand(Segment)
11557     .setMemRefs(MMOBegin, MMOEnd);
11558
11559   // If we need to align it, do so. Otherwise, just copy the address
11560   // to OverflowDestReg.
11561   if (NeedsAlign) {
11562     // Align the overflow address
11563     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11564     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11565
11566     // aligned_addr = (addr + (align-1)) & ~(align-1)
11567     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11568       .addReg(OverflowAddrReg)
11569       .addImm(Align-1);
11570
11571     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11572       .addReg(TmpReg)
11573       .addImm(~(uint64_t)(Align-1));
11574   } else {
11575     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11576       .addReg(OverflowAddrReg);
11577   }
11578
11579   // Compute the next overflow address after this argument.
11580   // (the overflow address should be kept 8-byte aligned)
11581   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11582   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11583     .addReg(OverflowDestReg)
11584     .addImm(ArgSizeA8);
11585
11586   // Store the new overflow address.
11587   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11588     .addOperand(Base)
11589     .addOperand(Scale)
11590     .addOperand(Index)
11591     .addDisp(Disp, 8)
11592     .addOperand(Segment)
11593     .addReg(NextAddrReg)
11594     .setMemRefs(MMOBegin, MMOEnd);
11595
11596   // If we branched, emit the PHI to the front of endMBB.
11597   if (offsetMBB) {
11598     BuildMI(*endMBB, endMBB->begin(), DL,
11599             TII->get(X86::PHI), DestReg)
11600       .addReg(OffsetDestReg).addMBB(offsetMBB)
11601       .addReg(OverflowDestReg).addMBB(overflowMBB);
11602   }
11603
11604   // Erase the pseudo instruction
11605   MI->eraseFromParent();
11606
11607   return endMBB;
11608 }
11609
11610 MachineBasicBlock *
11611 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11612                                                  MachineInstr *MI,
11613                                                  MachineBasicBlock *MBB) const {
11614   // Emit code to save XMM registers to the stack. The ABI says that the
11615   // number of registers to save is given in %al, so it's theoretically
11616   // possible to do an indirect jump trick to avoid saving all of them,
11617   // however this code takes a simpler approach and just executes all
11618   // of the stores if %al is non-zero. It's less code, and it's probably
11619   // easier on the hardware branch predictor, and stores aren't all that
11620   // expensive anyway.
11621
11622   // Create the new basic blocks. One block contains all the XMM stores,
11623   // and one block is the final destination regardless of whether any
11624   // stores were performed.
11625   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11626   MachineFunction *F = MBB->getParent();
11627   MachineFunction::iterator MBBIter = MBB;
11628   ++MBBIter;
11629   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11630   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11631   F->insert(MBBIter, XMMSaveMBB);
11632   F->insert(MBBIter, EndMBB);
11633
11634   // Transfer the remainder of MBB and its successor edges to EndMBB.
11635   EndMBB->splice(EndMBB->begin(), MBB,
11636                  llvm::next(MachineBasicBlock::iterator(MI)),
11637                  MBB->end());
11638   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11639
11640   // The original block will now fall through to the XMM save block.
11641   MBB->addSuccessor(XMMSaveMBB);
11642   // The XMMSaveMBB will fall through to the end block.
11643   XMMSaveMBB->addSuccessor(EndMBB);
11644
11645   // Now add the instructions.
11646   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11647   DebugLoc DL = MI->getDebugLoc();
11648
11649   unsigned CountReg = MI->getOperand(0).getReg();
11650   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11651   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11652
11653   if (!Subtarget->isTargetWin64()) {
11654     // If %al is 0, branch around the XMM save block.
11655     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11656     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11657     MBB->addSuccessor(EndMBB);
11658   }
11659
11660   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11661   // In the XMM save block, save all the XMM argument registers.
11662   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11663     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11664     MachineMemOperand *MMO =
11665       F->getMachineMemOperand(
11666           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11667         MachineMemOperand::MOStore,
11668         /*Size=*/16, /*Align=*/16);
11669     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11670       .addFrameIndex(RegSaveFrameIndex)
11671       .addImm(/*Scale=*/1)
11672       .addReg(/*IndexReg=*/0)
11673       .addImm(/*Disp=*/Offset)
11674       .addReg(/*Segment=*/0)
11675       .addReg(MI->getOperand(i).getReg())
11676       .addMemOperand(MMO);
11677   }
11678
11679   MI->eraseFromParent();   // The pseudo instruction is gone now.
11680
11681   return EndMBB;
11682 }
11683
11684 MachineBasicBlock *
11685 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11686                                      MachineBasicBlock *BB) const {
11687   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11688   DebugLoc DL = MI->getDebugLoc();
11689
11690   // To "insert" a SELECT_CC instruction, we actually have to insert the
11691   // diamond control-flow pattern.  The incoming instruction knows the
11692   // destination vreg to set, the condition code register to branch on, the
11693   // true/false values to select between, and a branch opcode to use.
11694   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11695   MachineFunction::iterator It = BB;
11696   ++It;
11697
11698   //  thisMBB:
11699   //  ...
11700   //   TrueVal = ...
11701   //   cmpTY ccX, r1, r2
11702   //   bCC copy1MBB
11703   //   fallthrough --> copy0MBB
11704   MachineBasicBlock *thisMBB = BB;
11705   MachineFunction *F = BB->getParent();
11706   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11707   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11708   F->insert(It, copy0MBB);
11709   F->insert(It, sinkMBB);
11710
11711   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11712   // live into the sink and copy blocks.
11713   if (!MI->killsRegister(X86::EFLAGS)) {
11714     copy0MBB->addLiveIn(X86::EFLAGS);
11715     sinkMBB->addLiveIn(X86::EFLAGS);
11716   }
11717
11718   // Transfer the remainder of BB and its successor edges to sinkMBB.
11719   sinkMBB->splice(sinkMBB->begin(), BB,
11720                   llvm::next(MachineBasicBlock::iterator(MI)),
11721                   BB->end());
11722   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11723
11724   // Add the true and fallthrough blocks as its successors.
11725   BB->addSuccessor(copy0MBB);
11726   BB->addSuccessor(sinkMBB);
11727
11728   // Create the conditional branch instruction.
11729   unsigned Opc =
11730     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11731   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11732
11733   //  copy0MBB:
11734   //   %FalseValue = ...
11735   //   # fallthrough to sinkMBB
11736   copy0MBB->addSuccessor(sinkMBB);
11737
11738   //  sinkMBB:
11739   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11740   //  ...
11741   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11742           TII->get(X86::PHI), MI->getOperand(0).getReg())
11743     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11744     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11745
11746   MI->eraseFromParent();   // The pseudo instruction is gone now.
11747   return sinkMBB;
11748 }
11749
11750 MachineBasicBlock *
11751 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11752                                         bool Is64Bit) const {
11753   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11754   DebugLoc DL = MI->getDebugLoc();
11755   MachineFunction *MF = BB->getParent();
11756   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11757
11758   assert(EnableSegmentedStacks);
11759
11760   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11761   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11762
11763   // BB:
11764   //  ... [Till the alloca]
11765   // If stacklet is not large enough, jump to mallocMBB
11766   //
11767   // bumpMBB:
11768   //  Allocate by subtracting from RSP
11769   //  Jump to continueMBB
11770   //
11771   // mallocMBB:
11772   //  Allocate by call to runtime
11773   //
11774   // continueMBB:
11775   //  ...
11776   //  [rest of original BB]
11777   //
11778
11779   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11780   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11781   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11782
11783   MachineRegisterInfo &MRI = MF->getRegInfo();
11784   const TargetRegisterClass *AddrRegClass =
11785     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11786
11787   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11788     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11789     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11790     sizeVReg = MI->getOperand(1).getReg(),
11791     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11792
11793   MachineFunction::iterator MBBIter = BB;
11794   ++MBBIter;
11795
11796   MF->insert(MBBIter, bumpMBB);
11797   MF->insert(MBBIter, mallocMBB);
11798   MF->insert(MBBIter, continueMBB);
11799
11800   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11801                       (MachineBasicBlock::iterator(MI)), BB->end());
11802   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11803
11804   // Add code to the main basic block to check if the stack limit has been hit,
11805   // and if so, jump to mallocMBB otherwise to bumpMBB.
11806   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11807   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11808     .addReg(tmpSPVReg).addReg(sizeVReg);
11809   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11810     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11811     .addReg(tmpSPVReg);
11812   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11813
11814   // bumpMBB simply decreases the stack pointer, since we know the current
11815   // stacklet has enough space.
11816   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11817     .addReg(tmpSPVReg);
11818   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11819     .addReg(tmpSPVReg);
11820   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11821
11822   // Calls into a routine in libgcc to allocate more space from the heap.
11823   if (Is64Bit) {
11824     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11825       .addReg(sizeVReg);
11826     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11827     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11828   } else {
11829     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11830       .addImm(12);
11831     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11832     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11833       .addExternalSymbol("__morestack_allocate_stack_space");
11834   }
11835
11836   if (!Is64Bit)
11837     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11838       .addImm(16);
11839
11840   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11841     .addReg(Is64Bit ? X86::RAX : X86::EAX);
11842   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11843
11844   // Set up the CFG correctly.
11845   BB->addSuccessor(bumpMBB);
11846   BB->addSuccessor(mallocMBB);
11847   mallocMBB->addSuccessor(continueMBB);
11848   bumpMBB->addSuccessor(continueMBB);
11849
11850   // Take care of the PHI nodes.
11851   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11852           MI->getOperand(0).getReg())
11853     .addReg(mallocPtrVReg).addMBB(mallocMBB)
11854     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11855
11856   // Delete the original pseudo instruction.
11857   MI->eraseFromParent();
11858
11859   // And we're done.
11860   return continueMBB;
11861 }
11862
11863 MachineBasicBlock *
11864 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11865                                           MachineBasicBlock *BB) const {
11866   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11867   DebugLoc DL = MI->getDebugLoc();
11868
11869   assert(!Subtarget->isTargetEnvMacho());
11870
11871   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11872   // non-trivial part is impdef of ESP.
11873
11874   if (Subtarget->isTargetWin64()) {
11875     if (Subtarget->isTargetCygMing()) {
11876       // ___chkstk(Mingw64):
11877       // Clobbers R10, R11, RAX and EFLAGS.
11878       // Updates RSP.
11879       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11880         .addExternalSymbol("___chkstk")
11881         .addReg(X86::RAX, RegState::Implicit)
11882         .addReg(X86::RSP, RegState::Implicit)
11883         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11884         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11885         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11886     } else {
11887       // __chkstk(MSVCRT): does not update stack pointer.
11888       // Clobbers R10, R11 and EFLAGS.
11889       // FIXME: RAX(allocated size) might be reused and not killed.
11890       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11891         .addExternalSymbol("__chkstk")
11892         .addReg(X86::RAX, RegState::Implicit)
11893         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11894       // RAX has the offset to subtracted from RSP.
11895       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11896         .addReg(X86::RSP)
11897         .addReg(X86::RAX);
11898     }
11899   } else {
11900     const char *StackProbeSymbol =
11901       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11902
11903     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11904       .addExternalSymbol(StackProbeSymbol)
11905       .addReg(X86::EAX, RegState::Implicit)
11906       .addReg(X86::ESP, RegState::Implicit)
11907       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11908       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11909       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11910   }
11911
11912   MI->eraseFromParent();   // The pseudo instruction is gone now.
11913   return BB;
11914 }
11915
11916 MachineBasicBlock *
11917 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11918                                       MachineBasicBlock *BB) const {
11919   // This is pretty easy.  We're taking the value that we received from
11920   // our load from the relocation, sticking it in either RDI (x86-64)
11921   // or EAX and doing an indirect call.  The return value will then
11922   // be in the normal return register.
11923   const X86InstrInfo *TII
11924     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11925   DebugLoc DL = MI->getDebugLoc();
11926   MachineFunction *F = BB->getParent();
11927
11928   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11929   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11930
11931   if (Subtarget->is64Bit()) {
11932     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11933                                       TII->get(X86::MOV64rm), X86::RDI)
11934     .addReg(X86::RIP)
11935     .addImm(0).addReg(0)
11936     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11937                       MI->getOperand(3).getTargetFlags())
11938     .addReg(0);
11939     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11940     addDirectMem(MIB, X86::RDI);
11941   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11942     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11943                                       TII->get(X86::MOV32rm), X86::EAX)
11944     .addReg(0)
11945     .addImm(0).addReg(0)
11946     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11947                       MI->getOperand(3).getTargetFlags())
11948     .addReg(0);
11949     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11950     addDirectMem(MIB, X86::EAX);
11951   } else {
11952     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11953                                       TII->get(X86::MOV32rm), X86::EAX)
11954     .addReg(TII->getGlobalBaseReg(F))
11955     .addImm(0).addReg(0)
11956     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11957                       MI->getOperand(3).getTargetFlags())
11958     .addReg(0);
11959     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11960     addDirectMem(MIB, X86::EAX);
11961   }
11962
11963   MI->eraseFromParent(); // The pseudo instruction is gone now.
11964   return BB;
11965 }
11966
11967 MachineBasicBlock *
11968 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11969                                                MachineBasicBlock *BB) const {
11970   switch (MI->getOpcode()) {
11971   default: assert(0 && "Unexpected instr type to insert");
11972   case X86::TAILJMPd64:
11973   case X86::TAILJMPr64:
11974   case X86::TAILJMPm64:
11975     assert(0 && "TAILJMP64 would not be touched here.");
11976   case X86::TCRETURNdi64:
11977   case X86::TCRETURNri64:
11978   case X86::TCRETURNmi64:
11979     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11980     // On AMD64, additional defs should be added before register allocation.
11981     if (!Subtarget->isTargetWin64()) {
11982       MI->addRegisterDefined(X86::RSI);
11983       MI->addRegisterDefined(X86::RDI);
11984       MI->addRegisterDefined(X86::XMM6);
11985       MI->addRegisterDefined(X86::XMM7);
11986       MI->addRegisterDefined(X86::XMM8);
11987       MI->addRegisterDefined(X86::XMM9);
11988       MI->addRegisterDefined(X86::XMM10);
11989       MI->addRegisterDefined(X86::XMM11);
11990       MI->addRegisterDefined(X86::XMM12);
11991       MI->addRegisterDefined(X86::XMM13);
11992       MI->addRegisterDefined(X86::XMM14);
11993       MI->addRegisterDefined(X86::XMM15);
11994     }
11995     return BB;
11996   case X86::WIN_ALLOCA:
11997     return EmitLoweredWinAlloca(MI, BB);
11998   case X86::SEG_ALLOCA_32:
11999     return EmitLoweredSegAlloca(MI, BB, false);
12000   case X86::SEG_ALLOCA_64:
12001     return EmitLoweredSegAlloca(MI, BB, true);
12002   case X86::TLSCall_32:
12003   case X86::TLSCall_64:
12004     return EmitLoweredTLSCall(MI, BB);
12005   case X86::CMOV_GR8:
12006   case X86::CMOV_FR32:
12007   case X86::CMOV_FR64:
12008   case X86::CMOV_V4F32:
12009   case X86::CMOV_V2F64:
12010   case X86::CMOV_V2I64:
12011   case X86::CMOV_V8F32:
12012   case X86::CMOV_V4F64:
12013   case X86::CMOV_V4I64:
12014   case X86::CMOV_GR16:
12015   case X86::CMOV_GR32:
12016   case X86::CMOV_RFP32:
12017   case X86::CMOV_RFP64:
12018   case X86::CMOV_RFP80:
12019     return EmitLoweredSelect(MI, BB);
12020
12021   case X86::FP32_TO_INT16_IN_MEM:
12022   case X86::FP32_TO_INT32_IN_MEM:
12023   case X86::FP32_TO_INT64_IN_MEM:
12024   case X86::FP64_TO_INT16_IN_MEM:
12025   case X86::FP64_TO_INT32_IN_MEM:
12026   case X86::FP64_TO_INT64_IN_MEM:
12027   case X86::FP80_TO_INT16_IN_MEM:
12028   case X86::FP80_TO_INT32_IN_MEM:
12029   case X86::FP80_TO_INT64_IN_MEM: {
12030     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12031     DebugLoc DL = MI->getDebugLoc();
12032
12033     // Change the floating point control register to use "round towards zero"
12034     // mode when truncating to an integer value.
12035     MachineFunction *F = BB->getParent();
12036     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12037     addFrameReference(BuildMI(*BB, MI, DL,
12038                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12039
12040     // Load the old value of the high byte of the control word...
12041     unsigned OldCW =
12042       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12043     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12044                       CWFrameIdx);
12045
12046     // Set the high part to be round to zero...
12047     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12048       .addImm(0xC7F);
12049
12050     // Reload the modified control word now...
12051     addFrameReference(BuildMI(*BB, MI, DL,
12052                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12053
12054     // Restore the memory image of control word to original value
12055     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12056       .addReg(OldCW);
12057
12058     // Get the X86 opcode to use.
12059     unsigned Opc;
12060     switch (MI->getOpcode()) {
12061     default: llvm_unreachable("illegal opcode!");
12062     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12063     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12064     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12065     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12066     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12067     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12068     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12069     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12070     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12071     }
12072
12073     X86AddressMode AM;
12074     MachineOperand &Op = MI->getOperand(0);
12075     if (Op.isReg()) {
12076       AM.BaseType = X86AddressMode::RegBase;
12077       AM.Base.Reg = Op.getReg();
12078     } else {
12079       AM.BaseType = X86AddressMode::FrameIndexBase;
12080       AM.Base.FrameIndex = Op.getIndex();
12081     }
12082     Op = MI->getOperand(1);
12083     if (Op.isImm())
12084       AM.Scale = Op.getImm();
12085     Op = MI->getOperand(2);
12086     if (Op.isImm())
12087       AM.IndexReg = Op.getImm();
12088     Op = MI->getOperand(3);
12089     if (Op.isGlobal()) {
12090       AM.GV = Op.getGlobal();
12091     } else {
12092       AM.Disp = Op.getImm();
12093     }
12094     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12095                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12096
12097     // Reload the original control word now.
12098     addFrameReference(BuildMI(*BB, MI, DL,
12099                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12100
12101     MI->eraseFromParent();   // The pseudo instruction is gone now.
12102     return BB;
12103   }
12104     // String/text processing lowering.
12105   case X86::PCMPISTRM128REG:
12106   case X86::VPCMPISTRM128REG:
12107     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12108   case X86::PCMPISTRM128MEM:
12109   case X86::VPCMPISTRM128MEM:
12110     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12111   case X86::PCMPESTRM128REG:
12112   case X86::VPCMPESTRM128REG:
12113     return EmitPCMP(MI, BB, 5, false /* in mem */);
12114   case X86::PCMPESTRM128MEM:
12115   case X86::VPCMPESTRM128MEM:
12116     return EmitPCMP(MI, BB, 5, true /* in mem */);
12117
12118     // Thread synchronization.
12119   case X86::MONITOR:
12120     return EmitMonitor(MI, BB);
12121   case X86::MWAIT:
12122     return EmitMwait(MI, BB);
12123
12124     // Atomic Lowering.
12125   case X86::ATOMAND32:
12126     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12127                                                X86::AND32ri, X86::MOV32rm,
12128                                                X86::LCMPXCHG32,
12129                                                X86::NOT32r, X86::EAX,
12130                                                X86::GR32RegisterClass);
12131   case X86::ATOMOR32:
12132     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12133                                                X86::OR32ri, X86::MOV32rm,
12134                                                X86::LCMPXCHG32,
12135                                                X86::NOT32r, X86::EAX,
12136                                                X86::GR32RegisterClass);
12137   case X86::ATOMXOR32:
12138     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12139                                                X86::XOR32ri, X86::MOV32rm,
12140                                                X86::LCMPXCHG32,
12141                                                X86::NOT32r, X86::EAX,
12142                                                X86::GR32RegisterClass);
12143   case X86::ATOMNAND32:
12144     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12145                                                X86::AND32ri, X86::MOV32rm,
12146                                                X86::LCMPXCHG32,
12147                                                X86::NOT32r, X86::EAX,
12148                                                X86::GR32RegisterClass, true);
12149   case X86::ATOMMIN32:
12150     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12151   case X86::ATOMMAX32:
12152     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12153   case X86::ATOMUMIN32:
12154     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12155   case X86::ATOMUMAX32:
12156     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12157
12158   case X86::ATOMAND16:
12159     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12160                                                X86::AND16ri, X86::MOV16rm,
12161                                                X86::LCMPXCHG16,
12162                                                X86::NOT16r, X86::AX,
12163                                                X86::GR16RegisterClass);
12164   case X86::ATOMOR16:
12165     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12166                                                X86::OR16ri, X86::MOV16rm,
12167                                                X86::LCMPXCHG16,
12168                                                X86::NOT16r, X86::AX,
12169                                                X86::GR16RegisterClass);
12170   case X86::ATOMXOR16:
12171     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12172                                                X86::XOR16ri, X86::MOV16rm,
12173                                                X86::LCMPXCHG16,
12174                                                X86::NOT16r, X86::AX,
12175                                                X86::GR16RegisterClass);
12176   case X86::ATOMNAND16:
12177     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12178                                                X86::AND16ri, X86::MOV16rm,
12179                                                X86::LCMPXCHG16,
12180                                                X86::NOT16r, X86::AX,
12181                                                X86::GR16RegisterClass, true);
12182   case X86::ATOMMIN16:
12183     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12184   case X86::ATOMMAX16:
12185     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12186   case X86::ATOMUMIN16:
12187     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12188   case X86::ATOMUMAX16:
12189     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12190
12191   case X86::ATOMAND8:
12192     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12193                                                X86::AND8ri, X86::MOV8rm,
12194                                                X86::LCMPXCHG8,
12195                                                X86::NOT8r, X86::AL,
12196                                                X86::GR8RegisterClass);
12197   case X86::ATOMOR8:
12198     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12199                                                X86::OR8ri, X86::MOV8rm,
12200                                                X86::LCMPXCHG8,
12201                                                X86::NOT8r, X86::AL,
12202                                                X86::GR8RegisterClass);
12203   case X86::ATOMXOR8:
12204     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12205                                                X86::XOR8ri, X86::MOV8rm,
12206                                                X86::LCMPXCHG8,
12207                                                X86::NOT8r, X86::AL,
12208                                                X86::GR8RegisterClass);
12209   case X86::ATOMNAND8:
12210     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12211                                                X86::AND8ri, X86::MOV8rm,
12212                                                X86::LCMPXCHG8,
12213                                                X86::NOT8r, X86::AL,
12214                                                X86::GR8RegisterClass, true);
12215   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12216   // This group is for 64-bit host.
12217   case X86::ATOMAND64:
12218     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12219                                                X86::AND64ri32, X86::MOV64rm,
12220                                                X86::LCMPXCHG64,
12221                                                X86::NOT64r, X86::RAX,
12222                                                X86::GR64RegisterClass);
12223   case X86::ATOMOR64:
12224     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12225                                                X86::OR64ri32, X86::MOV64rm,
12226                                                X86::LCMPXCHG64,
12227                                                X86::NOT64r, X86::RAX,
12228                                                X86::GR64RegisterClass);
12229   case X86::ATOMXOR64:
12230     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12231                                                X86::XOR64ri32, X86::MOV64rm,
12232                                                X86::LCMPXCHG64,
12233                                                X86::NOT64r, X86::RAX,
12234                                                X86::GR64RegisterClass);
12235   case X86::ATOMNAND64:
12236     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12237                                                X86::AND64ri32, X86::MOV64rm,
12238                                                X86::LCMPXCHG64,
12239                                                X86::NOT64r, X86::RAX,
12240                                                X86::GR64RegisterClass, true);
12241   case X86::ATOMMIN64:
12242     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12243   case X86::ATOMMAX64:
12244     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12245   case X86::ATOMUMIN64:
12246     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12247   case X86::ATOMUMAX64:
12248     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12249
12250   // This group does 64-bit operations on a 32-bit host.
12251   case X86::ATOMAND6432:
12252     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12253                                                X86::AND32rr, X86::AND32rr,
12254                                                X86::AND32ri, X86::AND32ri,
12255                                                false);
12256   case X86::ATOMOR6432:
12257     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12258                                                X86::OR32rr, X86::OR32rr,
12259                                                X86::OR32ri, X86::OR32ri,
12260                                                false);
12261   case X86::ATOMXOR6432:
12262     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12263                                                X86::XOR32rr, X86::XOR32rr,
12264                                                X86::XOR32ri, X86::XOR32ri,
12265                                                false);
12266   case X86::ATOMNAND6432:
12267     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12268                                                X86::AND32rr, X86::AND32rr,
12269                                                X86::AND32ri, X86::AND32ri,
12270                                                true);
12271   case X86::ATOMADD6432:
12272     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12273                                                X86::ADD32rr, X86::ADC32rr,
12274                                                X86::ADD32ri, X86::ADC32ri,
12275                                                false);
12276   case X86::ATOMSUB6432:
12277     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12278                                                X86::SUB32rr, X86::SBB32rr,
12279                                                X86::SUB32ri, X86::SBB32ri,
12280                                                false);
12281   case X86::ATOMSWAP6432:
12282     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12283                                                X86::MOV32rr, X86::MOV32rr,
12284                                                X86::MOV32ri, X86::MOV32ri,
12285                                                false);
12286   case X86::VASTART_SAVE_XMM_REGS:
12287     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12288
12289   case X86::VAARG_64:
12290     return EmitVAARG64WithCustomInserter(MI, BB);
12291   }
12292 }
12293
12294 //===----------------------------------------------------------------------===//
12295 //                           X86 Optimization Hooks
12296 //===----------------------------------------------------------------------===//
12297
12298 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12299                                                        const APInt &Mask,
12300                                                        APInt &KnownZero,
12301                                                        APInt &KnownOne,
12302                                                        const SelectionDAG &DAG,
12303                                                        unsigned Depth) const {
12304   unsigned Opc = Op.getOpcode();
12305   assert((Opc >= ISD::BUILTIN_OP_END ||
12306           Opc == ISD::INTRINSIC_WO_CHAIN ||
12307           Opc == ISD::INTRINSIC_W_CHAIN ||
12308           Opc == ISD::INTRINSIC_VOID) &&
12309          "Should use MaskedValueIsZero if you don't know whether Op"
12310          " is a target node!");
12311
12312   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12313   switch (Opc) {
12314   default: break;
12315   case X86ISD::ADD:
12316   case X86ISD::SUB:
12317   case X86ISD::ADC:
12318   case X86ISD::SBB:
12319   case X86ISD::SMUL:
12320   case X86ISD::UMUL:
12321   case X86ISD::INC:
12322   case X86ISD::DEC:
12323   case X86ISD::OR:
12324   case X86ISD::XOR:
12325   case X86ISD::AND:
12326     // These nodes' second result is a boolean.
12327     if (Op.getResNo() == 0)
12328       break;
12329     // Fallthrough
12330   case X86ISD::SETCC:
12331     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12332                                        Mask.getBitWidth() - 1);
12333     break;
12334   case ISD::INTRINSIC_WO_CHAIN: {
12335     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12336     unsigned NumLoBits = 0;
12337     switch (IntId) {
12338     default: break;
12339     case Intrinsic::x86_sse_movmsk_ps:
12340     case Intrinsic::x86_avx_movmsk_ps_256:
12341     case Intrinsic::x86_sse2_movmsk_pd:
12342     case Intrinsic::x86_avx_movmsk_pd_256:
12343     case Intrinsic::x86_mmx_pmovmskb:
12344     case Intrinsic::x86_sse2_pmovmskb_128: {
12345       // High bits of movmskp{s|d}, pmovmskb are known zero.
12346       switch (IntId) {
12347         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12348         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12349         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12350         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12351         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12352         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12353       }
12354       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12355                                         Mask.getBitWidth() - NumLoBits);
12356       break;
12357     }
12358     }
12359     break;
12360   }
12361   }
12362 }
12363
12364 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12365                                                          unsigned Depth) const {
12366   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12367   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12368     return Op.getValueType().getScalarType().getSizeInBits();
12369
12370   // Fallback case.
12371   return 1;
12372 }
12373
12374 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12375 /// node is a GlobalAddress + offset.
12376 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12377                                        const GlobalValue* &GA,
12378                                        int64_t &Offset) const {
12379   if (N->getOpcode() == X86ISD::Wrapper) {
12380     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12381       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12382       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12383       return true;
12384     }
12385   }
12386   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12387 }
12388
12389 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12390 /// same as extracting the high 128-bit part of 256-bit vector and then
12391 /// inserting the result into the low part of a new 256-bit vector
12392 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12393   EVT VT = SVOp->getValueType(0);
12394   int NumElems = VT.getVectorNumElements();
12395
12396   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12397   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12398     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12399         SVOp->getMaskElt(j) >= 0)
12400       return false;
12401
12402   return true;
12403 }
12404
12405 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12406 /// same as extracting the low 128-bit part of 256-bit vector and then
12407 /// inserting the result into the high part of a new 256-bit vector
12408 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12409   EVT VT = SVOp->getValueType(0);
12410   int NumElems = VT.getVectorNumElements();
12411
12412   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12413   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12414     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12415         SVOp->getMaskElt(j) >= 0)
12416       return false;
12417
12418   return true;
12419 }
12420
12421 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12422 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12423                                         TargetLowering::DAGCombinerInfo &DCI) {
12424   DebugLoc dl = N->getDebugLoc();
12425   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12426   SDValue V1 = SVOp->getOperand(0);
12427   SDValue V2 = SVOp->getOperand(1);
12428   EVT VT = SVOp->getValueType(0);
12429   int NumElems = VT.getVectorNumElements();
12430
12431   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12432       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12433     //
12434     //                   0,0,0,...
12435     //                      |
12436     //    V      UNDEF    BUILD_VECTOR    UNDEF
12437     //     \      /           \           /
12438     //  CONCAT_VECTOR         CONCAT_VECTOR
12439     //         \                  /
12440     //          \                /
12441     //          RESULT: V + zero extended
12442     //
12443     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12444         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12445         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12446       return SDValue();
12447
12448     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12449       return SDValue();
12450
12451     // To match the shuffle mask, the first half of the mask should
12452     // be exactly the first vector, and all the rest a splat with the
12453     // first element of the second one.
12454     for (int i = 0; i < NumElems/2; ++i)
12455       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12456           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12457         return SDValue();
12458
12459     // Emit a zeroed vector and insert the desired subvector on its
12460     // first half.
12461     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12462     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12463                          DAG.getConstant(0, MVT::i32), DAG, dl);
12464     return DCI.CombineTo(N, InsV);
12465   }
12466
12467   //===--------------------------------------------------------------------===//
12468   // Combine some shuffles into subvector extracts and inserts:
12469   //
12470
12471   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12472   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12473     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12474                                     DAG, dl);
12475     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12476                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12477     return DCI.CombineTo(N, InsV);
12478   }
12479
12480   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12481   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12482     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12483     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12484                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12485     return DCI.CombineTo(N, InsV);
12486   }
12487
12488   return SDValue();
12489 }
12490
12491 /// PerformShuffleCombine - Performs several different shuffle combines.
12492 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12493                                      TargetLowering::DAGCombinerInfo &DCI,
12494                                      const X86Subtarget *Subtarget) {
12495   DebugLoc dl = N->getDebugLoc();
12496   EVT VT = N->getValueType(0);
12497
12498   // Don't create instructions with illegal types after legalize types has run.
12499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12500   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12501     return SDValue();
12502
12503   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12504   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12505       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12506     return PerformShuffleCombine256(N, DAG, DCI);
12507
12508   // Only handle 128 wide vector from here on.
12509   if (VT.getSizeInBits() != 128)
12510     return SDValue();
12511
12512   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12513   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12514   // consecutive, non-overlapping, and in the right order.
12515   SmallVector<SDValue, 16> Elts;
12516   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12517     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12518
12519   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12520 }
12521
12522 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12523 /// generation and convert it from being a bunch of shuffles and extracts
12524 /// to a simple store and scalar loads to extract the elements.
12525 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12526                                                 const TargetLowering &TLI) {
12527   SDValue InputVector = N->getOperand(0);
12528
12529   // Only operate on vectors of 4 elements, where the alternative shuffling
12530   // gets to be more expensive.
12531   if (InputVector.getValueType() != MVT::v4i32)
12532     return SDValue();
12533
12534   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12535   // single use which is a sign-extend or zero-extend, and all elements are
12536   // used.
12537   SmallVector<SDNode *, 4> Uses;
12538   unsigned ExtractedElements = 0;
12539   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12540        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12541     if (UI.getUse().getResNo() != InputVector.getResNo())
12542       return SDValue();
12543
12544     SDNode *Extract = *UI;
12545     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12546       return SDValue();
12547
12548     if (Extract->getValueType(0) != MVT::i32)
12549       return SDValue();
12550     if (!Extract->hasOneUse())
12551       return SDValue();
12552     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12553         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12554       return SDValue();
12555     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12556       return SDValue();
12557
12558     // Record which element was extracted.
12559     ExtractedElements |=
12560       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12561
12562     Uses.push_back(Extract);
12563   }
12564
12565   // If not all the elements were used, this may not be worthwhile.
12566   if (ExtractedElements != 15)
12567     return SDValue();
12568
12569   // Ok, we've now decided to do the transformation.
12570   DebugLoc dl = InputVector.getDebugLoc();
12571
12572   // Store the value to a temporary stack slot.
12573   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12574   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12575                             MachinePointerInfo(), false, false, 0);
12576
12577   // Replace each use (extract) with a load of the appropriate element.
12578   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12579        UE = Uses.end(); UI != UE; ++UI) {
12580     SDNode *Extract = *UI;
12581
12582     // cOMpute the element's address.
12583     SDValue Idx = Extract->getOperand(1);
12584     unsigned EltSize =
12585         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12586     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12587     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12588
12589     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12590                                      StackPtr, OffsetVal);
12591
12592     // Load the scalar.
12593     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12594                                      ScalarAddr, MachinePointerInfo(),
12595                                      false, false, 0);
12596
12597     // Replace the exact with the load.
12598     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12599   }
12600
12601   // The replacement was made in place; don't return anything.
12602   return SDValue();
12603 }
12604
12605 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12606 /// nodes.
12607 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12608                                     const X86Subtarget *Subtarget) {
12609   DebugLoc DL = N->getDebugLoc();
12610   SDValue Cond = N->getOperand(0);
12611   // Get the LHS/RHS of the select.
12612   SDValue LHS = N->getOperand(1);
12613   SDValue RHS = N->getOperand(2);
12614   EVT VT = LHS.getValueType();
12615
12616   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12617   // instructions match the semantics of the common C idiom x<y?x:y but not
12618   // x<=y?x:y, because of how they handle negative zero (which can be
12619   // ignored in unsafe-math mode).
12620   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12621       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12622       (Subtarget->hasXMMInt() ||
12623        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12624     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12625
12626     unsigned Opcode = 0;
12627     // Check for x CC y ? x : y.
12628     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12629         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12630       switch (CC) {
12631       default: break;
12632       case ISD::SETULT:
12633         // Converting this to a min would handle NaNs incorrectly, and swapping
12634         // the operands would cause it to handle comparisons between positive
12635         // and negative zero incorrectly.
12636         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12637           if (!UnsafeFPMath &&
12638               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12639             break;
12640           std::swap(LHS, RHS);
12641         }
12642         Opcode = X86ISD::FMIN;
12643         break;
12644       case ISD::SETOLE:
12645         // Converting this to a min would handle comparisons between positive
12646         // and negative zero incorrectly.
12647         if (!UnsafeFPMath &&
12648             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12649           break;
12650         Opcode = X86ISD::FMIN;
12651         break;
12652       case ISD::SETULE:
12653         // Converting this to a min would handle both negative zeros and NaNs
12654         // incorrectly, but we can swap the operands to fix both.
12655         std::swap(LHS, RHS);
12656       case ISD::SETOLT:
12657       case ISD::SETLT:
12658       case ISD::SETLE:
12659         Opcode = X86ISD::FMIN;
12660         break;
12661
12662       case ISD::SETOGE:
12663         // Converting this to a max would handle comparisons between positive
12664         // and negative zero incorrectly.
12665         if (!UnsafeFPMath &&
12666             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12667           break;
12668         Opcode = X86ISD::FMAX;
12669         break;
12670       case ISD::SETUGT:
12671         // Converting this to a max would handle NaNs incorrectly, and swapping
12672         // the operands would cause it to handle comparisons between positive
12673         // and negative zero incorrectly.
12674         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12675           if (!UnsafeFPMath &&
12676               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12677             break;
12678           std::swap(LHS, RHS);
12679         }
12680         Opcode = X86ISD::FMAX;
12681         break;
12682       case ISD::SETUGE:
12683         // Converting this to a max would handle both negative zeros and NaNs
12684         // incorrectly, but we can swap the operands to fix both.
12685         std::swap(LHS, RHS);
12686       case ISD::SETOGT:
12687       case ISD::SETGT:
12688       case ISD::SETGE:
12689         Opcode = X86ISD::FMAX;
12690         break;
12691       }
12692     // Check for x CC y ? y : x -- a min/max with reversed arms.
12693     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12694                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12695       switch (CC) {
12696       default: break;
12697       case ISD::SETOGE:
12698         // Converting this to a min would handle comparisons between positive
12699         // and negative zero incorrectly, and swapping the operands would
12700         // cause it to handle NaNs incorrectly.
12701         if (!UnsafeFPMath &&
12702             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12703           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12704             break;
12705           std::swap(LHS, RHS);
12706         }
12707         Opcode = X86ISD::FMIN;
12708         break;
12709       case ISD::SETUGT:
12710         // Converting this to a min would handle NaNs incorrectly.
12711         if (!UnsafeFPMath &&
12712             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12713           break;
12714         Opcode = X86ISD::FMIN;
12715         break;
12716       case ISD::SETUGE:
12717         // Converting this to a min would handle both negative zeros and NaNs
12718         // incorrectly, but we can swap the operands to fix both.
12719         std::swap(LHS, RHS);
12720       case ISD::SETOGT:
12721       case ISD::SETGT:
12722       case ISD::SETGE:
12723         Opcode = X86ISD::FMIN;
12724         break;
12725
12726       case ISD::SETULT:
12727         // Converting this to a max would handle NaNs incorrectly.
12728         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12729           break;
12730         Opcode = X86ISD::FMAX;
12731         break;
12732       case ISD::SETOLE:
12733         // Converting this to a max would handle comparisons between positive
12734         // and negative zero incorrectly, and swapping the operands would
12735         // cause it to handle NaNs incorrectly.
12736         if (!UnsafeFPMath &&
12737             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12738           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12739             break;
12740           std::swap(LHS, RHS);
12741         }
12742         Opcode = X86ISD::FMAX;
12743         break;
12744       case ISD::SETULE:
12745         // Converting this to a max would handle both negative zeros and NaNs
12746         // incorrectly, but we can swap the operands to fix both.
12747         std::swap(LHS, RHS);
12748       case ISD::SETOLT:
12749       case ISD::SETLT:
12750       case ISD::SETLE:
12751         Opcode = X86ISD::FMAX;
12752         break;
12753       }
12754     }
12755
12756     if (Opcode)
12757       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12758   }
12759
12760   // If this is a select between two integer constants, try to do some
12761   // optimizations.
12762   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12763     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12764       // Don't do this for crazy integer types.
12765       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12766         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12767         // so that TrueC (the true value) is larger than FalseC.
12768         bool NeedsCondInvert = false;
12769
12770         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12771             // Efficiently invertible.
12772             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12773              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12774               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12775           NeedsCondInvert = true;
12776           std::swap(TrueC, FalseC);
12777         }
12778
12779         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12780         if (FalseC->getAPIntValue() == 0 &&
12781             TrueC->getAPIntValue().isPowerOf2()) {
12782           if (NeedsCondInvert) // Invert the condition if needed.
12783             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12784                                DAG.getConstant(1, Cond.getValueType()));
12785
12786           // Zero extend the condition if needed.
12787           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12788
12789           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12790           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12791                              DAG.getConstant(ShAmt, MVT::i8));
12792         }
12793
12794         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12795         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12796           if (NeedsCondInvert) // Invert the condition if needed.
12797             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12798                                DAG.getConstant(1, Cond.getValueType()));
12799
12800           // Zero extend the condition if needed.
12801           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12802                              FalseC->getValueType(0), Cond);
12803           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12804                              SDValue(FalseC, 0));
12805         }
12806
12807         // Optimize cases that will turn into an LEA instruction.  This requires
12808         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12809         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12810           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12811           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12812
12813           bool isFastMultiplier = false;
12814           if (Diff < 10) {
12815             switch ((unsigned char)Diff) {
12816               default: break;
12817               case 1:  // result = add base, cond
12818               case 2:  // result = lea base(    , cond*2)
12819               case 3:  // result = lea base(cond, cond*2)
12820               case 4:  // result = lea base(    , cond*4)
12821               case 5:  // result = lea base(cond, cond*4)
12822               case 8:  // result = lea base(    , cond*8)
12823               case 9:  // result = lea base(cond, cond*8)
12824                 isFastMultiplier = true;
12825                 break;
12826             }
12827           }
12828
12829           if (isFastMultiplier) {
12830             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12831             if (NeedsCondInvert) // Invert the condition if needed.
12832               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12833                                  DAG.getConstant(1, Cond.getValueType()));
12834
12835             // Zero extend the condition if needed.
12836             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12837                                Cond);
12838             // Scale the condition by the difference.
12839             if (Diff != 1)
12840               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12841                                  DAG.getConstant(Diff, Cond.getValueType()));
12842
12843             // Add the base if non-zero.
12844             if (FalseC->getAPIntValue() != 0)
12845               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12846                                  SDValue(FalseC, 0));
12847             return Cond;
12848           }
12849         }
12850       }
12851   }
12852
12853   return SDValue();
12854 }
12855
12856 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12857 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12858                                   TargetLowering::DAGCombinerInfo &DCI) {
12859   DebugLoc DL = N->getDebugLoc();
12860
12861   // If the flag operand isn't dead, don't touch this CMOV.
12862   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12863     return SDValue();
12864
12865   SDValue FalseOp = N->getOperand(0);
12866   SDValue TrueOp = N->getOperand(1);
12867   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12868   SDValue Cond = N->getOperand(3);
12869   if (CC == X86::COND_E || CC == X86::COND_NE) {
12870     switch (Cond.getOpcode()) {
12871     default: break;
12872     case X86ISD::BSR:
12873     case X86ISD::BSF:
12874       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12875       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12876         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12877     }
12878   }
12879
12880   // If this is a select between two integer constants, try to do some
12881   // optimizations.  Note that the operands are ordered the opposite of SELECT
12882   // operands.
12883   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12884     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12885       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12886       // larger than FalseC (the false value).
12887       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12888         CC = X86::GetOppositeBranchCondition(CC);
12889         std::swap(TrueC, FalseC);
12890       }
12891
12892       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12893       // This is efficient for any integer data type (including i8/i16) and
12894       // shift amount.
12895       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12896         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12897                            DAG.getConstant(CC, MVT::i8), Cond);
12898
12899         // Zero extend the condition if needed.
12900         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12901
12902         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12903         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12904                            DAG.getConstant(ShAmt, MVT::i8));
12905         if (N->getNumValues() == 2)  // Dead flag value?
12906           return DCI.CombineTo(N, Cond, SDValue());
12907         return Cond;
12908       }
12909
12910       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12911       // for any integer data type, including i8/i16.
12912       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12913         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12914                            DAG.getConstant(CC, MVT::i8), Cond);
12915
12916         // Zero extend the condition if needed.
12917         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12918                            FalseC->getValueType(0), Cond);
12919         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12920                            SDValue(FalseC, 0));
12921
12922         if (N->getNumValues() == 2)  // Dead flag value?
12923           return DCI.CombineTo(N, Cond, SDValue());
12924         return Cond;
12925       }
12926
12927       // Optimize cases that will turn into an LEA instruction.  This requires
12928       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12929       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12930         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12931         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12932
12933         bool isFastMultiplier = false;
12934         if (Diff < 10) {
12935           switch ((unsigned char)Diff) {
12936           default: break;
12937           case 1:  // result = add base, cond
12938           case 2:  // result = lea base(    , cond*2)
12939           case 3:  // result = lea base(cond, cond*2)
12940           case 4:  // result = lea base(    , cond*4)
12941           case 5:  // result = lea base(cond, cond*4)
12942           case 8:  // result = lea base(    , cond*8)
12943           case 9:  // result = lea base(cond, cond*8)
12944             isFastMultiplier = true;
12945             break;
12946           }
12947         }
12948
12949         if (isFastMultiplier) {
12950           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12951           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12952                              DAG.getConstant(CC, MVT::i8), Cond);
12953           // Zero extend the condition if needed.
12954           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12955                              Cond);
12956           // Scale the condition by the difference.
12957           if (Diff != 1)
12958             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12959                                DAG.getConstant(Diff, Cond.getValueType()));
12960
12961           // Add the base if non-zero.
12962           if (FalseC->getAPIntValue() != 0)
12963             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12964                                SDValue(FalseC, 0));
12965           if (N->getNumValues() == 2)  // Dead flag value?
12966             return DCI.CombineTo(N, Cond, SDValue());
12967           return Cond;
12968         }
12969       }
12970     }
12971   }
12972   return SDValue();
12973 }
12974
12975
12976 /// PerformMulCombine - Optimize a single multiply with constant into two
12977 /// in order to implement it with two cheaper instructions, e.g.
12978 /// LEA + SHL, LEA + LEA.
12979 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12980                                  TargetLowering::DAGCombinerInfo &DCI) {
12981   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12982     return SDValue();
12983
12984   EVT VT = N->getValueType(0);
12985   if (VT != MVT::i64)
12986     return SDValue();
12987
12988   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12989   if (!C)
12990     return SDValue();
12991   uint64_t MulAmt = C->getZExtValue();
12992   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12993     return SDValue();
12994
12995   uint64_t MulAmt1 = 0;
12996   uint64_t MulAmt2 = 0;
12997   if ((MulAmt % 9) == 0) {
12998     MulAmt1 = 9;
12999     MulAmt2 = MulAmt / 9;
13000   } else if ((MulAmt % 5) == 0) {
13001     MulAmt1 = 5;
13002     MulAmt2 = MulAmt / 5;
13003   } else if ((MulAmt % 3) == 0) {
13004     MulAmt1 = 3;
13005     MulAmt2 = MulAmt / 3;
13006   }
13007   if (MulAmt2 &&
13008       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13009     DebugLoc DL = N->getDebugLoc();
13010
13011     if (isPowerOf2_64(MulAmt2) &&
13012         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13013       // If second multiplifer is pow2, issue it first. We want the multiply by
13014       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13015       // is an add.
13016       std::swap(MulAmt1, MulAmt2);
13017
13018     SDValue NewMul;
13019     if (isPowerOf2_64(MulAmt1))
13020       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13021                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13022     else
13023       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13024                            DAG.getConstant(MulAmt1, VT));
13025
13026     if (isPowerOf2_64(MulAmt2))
13027       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13028                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13029     else
13030       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13031                            DAG.getConstant(MulAmt2, VT));
13032
13033     // Do not add new nodes to DAG combiner worklist.
13034     DCI.CombineTo(N, NewMul, false);
13035   }
13036   return SDValue();
13037 }
13038
13039 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13040   SDValue N0 = N->getOperand(0);
13041   SDValue N1 = N->getOperand(1);
13042   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13043   EVT VT = N0.getValueType();
13044
13045   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13046   // since the result of setcc_c is all zero's or all ones.
13047   if (N1C && N0.getOpcode() == ISD::AND &&
13048       N0.getOperand(1).getOpcode() == ISD::Constant) {
13049     SDValue N00 = N0.getOperand(0);
13050     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13051         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13052           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13053          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13054       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13055       APInt ShAmt = N1C->getAPIntValue();
13056       Mask = Mask.shl(ShAmt);
13057       if (Mask != 0)
13058         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13059                            N00, DAG.getConstant(Mask, VT));
13060     }
13061   }
13062
13063   return SDValue();
13064 }
13065
13066 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13067 ///                       when possible.
13068 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13069                                    const X86Subtarget *Subtarget) {
13070   EVT VT = N->getValueType(0);
13071   if (!VT.isVector() && VT.isInteger() &&
13072       N->getOpcode() == ISD::SHL)
13073     return PerformSHLCombine(N, DAG);
13074
13075   // On X86 with SSE2 support, we can transform this to a vector shift if
13076   // all elements are shifted by the same amount.  We can't do this in legalize
13077   // because the a constant vector is typically transformed to a constant pool
13078   // so we have no knowledge of the shift amount.
13079   if (!Subtarget->hasXMMInt())
13080     return SDValue();
13081
13082   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13083     return SDValue();
13084
13085   SDValue ShAmtOp = N->getOperand(1);
13086   EVT EltVT = VT.getVectorElementType();
13087   DebugLoc DL = N->getDebugLoc();
13088   SDValue BaseShAmt = SDValue();
13089   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13090     unsigned NumElts = VT.getVectorNumElements();
13091     unsigned i = 0;
13092     for (; i != NumElts; ++i) {
13093       SDValue Arg = ShAmtOp.getOperand(i);
13094       if (Arg.getOpcode() == ISD::UNDEF) continue;
13095       BaseShAmt = Arg;
13096       break;
13097     }
13098     for (; i != NumElts; ++i) {
13099       SDValue Arg = ShAmtOp.getOperand(i);
13100       if (Arg.getOpcode() == ISD::UNDEF) continue;
13101       if (Arg != BaseShAmt) {
13102         return SDValue();
13103       }
13104     }
13105   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13106              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13107     SDValue InVec = ShAmtOp.getOperand(0);
13108     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13109       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13110       unsigned i = 0;
13111       for (; i != NumElts; ++i) {
13112         SDValue Arg = InVec.getOperand(i);
13113         if (Arg.getOpcode() == ISD::UNDEF) continue;
13114         BaseShAmt = Arg;
13115         break;
13116       }
13117     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13118        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13119          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13120          if (C->getZExtValue() == SplatIdx)
13121            BaseShAmt = InVec.getOperand(1);
13122        }
13123     }
13124     if (BaseShAmt.getNode() == 0)
13125       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13126                               DAG.getIntPtrConstant(0));
13127   } else
13128     return SDValue();
13129
13130   // The shift amount is an i32.
13131   if (EltVT.bitsGT(MVT::i32))
13132     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13133   else if (EltVT.bitsLT(MVT::i32))
13134     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13135
13136   // The shift amount is identical so we can do a vector shift.
13137   SDValue  ValOp = N->getOperand(0);
13138   switch (N->getOpcode()) {
13139   default:
13140     llvm_unreachable("Unknown shift opcode!");
13141     break;
13142   case ISD::SHL:
13143     if (VT == MVT::v2i64)
13144       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13145                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13146                          ValOp, BaseShAmt);
13147     if (VT == MVT::v4i32)
13148       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13149                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13150                          ValOp, BaseShAmt);
13151     if (VT == MVT::v8i16)
13152       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13153                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13154                          ValOp, BaseShAmt);
13155     break;
13156   case ISD::SRA:
13157     if (VT == MVT::v4i32)
13158       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13159                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13160                          ValOp, BaseShAmt);
13161     if (VT == MVT::v8i16)
13162       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13163                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13164                          ValOp, BaseShAmt);
13165     break;
13166   case ISD::SRL:
13167     if (VT == MVT::v2i64)
13168       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13169                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13170                          ValOp, BaseShAmt);
13171     if (VT == MVT::v4i32)
13172       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13173                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13174                          ValOp, BaseShAmt);
13175     if (VT ==  MVT::v8i16)
13176       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13177                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13178                          ValOp, BaseShAmt);
13179     break;
13180   }
13181   return SDValue();
13182 }
13183
13184
13185 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13186 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13187 // and friends.  Likewise for OR -> CMPNEQSS.
13188 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13189                             TargetLowering::DAGCombinerInfo &DCI,
13190                             const X86Subtarget *Subtarget) {
13191   unsigned opcode;
13192
13193   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13194   // we're requiring SSE2 for both.
13195   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13196     SDValue N0 = N->getOperand(0);
13197     SDValue N1 = N->getOperand(1);
13198     SDValue CMP0 = N0->getOperand(1);
13199     SDValue CMP1 = N1->getOperand(1);
13200     DebugLoc DL = N->getDebugLoc();
13201
13202     // The SETCCs should both refer to the same CMP.
13203     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13204       return SDValue();
13205
13206     SDValue CMP00 = CMP0->getOperand(0);
13207     SDValue CMP01 = CMP0->getOperand(1);
13208     EVT     VT    = CMP00.getValueType();
13209
13210     if (VT == MVT::f32 || VT == MVT::f64) {
13211       bool ExpectingFlags = false;
13212       // Check for any users that want flags:
13213       for (SDNode::use_iterator UI = N->use_begin(),
13214              UE = N->use_end();
13215            !ExpectingFlags && UI != UE; ++UI)
13216         switch (UI->getOpcode()) {
13217         default:
13218         case ISD::BR_CC:
13219         case ISD::BRCOND:
13220         case ISD::SELECT:
13221           ExpectingFlags = true;
13222           break;
13223         case ISD::CopyToReg:
13224         case ISD::SIGN_EXTEND:
13225         case ISD::ZERO_EXTEND:
13226         case ISD::ANY_EXTEND:
13227           break;
13228         }
13229
13230       if (!ExpectingFlags) {
13231         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13232         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13233
13234         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13235           X86::CondCode tmp = cc0;
13236           cc0 = cc1;
13237           cc1 = tmp;
13238         }
13239
13240         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13241             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13242           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13243           X86ISD::NodeType NTOperator = is64BitFP ?
13244             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13245           // FIXME: need symbolic constants for these magic numbers.
13246           // See X86ATTInstPrinter.cpp:printSSECC().
13247           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13248           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13249                                               DAG.getConstant(x86cc, MVT::i8));
13250           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13251                                               OnesOrZeroesF);
13252           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13253                                       DAG.getConstant(1, MVT::i32));
13254           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13255           return OneBitOfTruth;
13256         }
13257       }
13258     }
13259   }
13260   return SDValue();
13261 }
13262
13263 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13264 /// so it can be folded inside ANDNP.
13265 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13266   EVT VT = N->getValueType(0);
13267
13268   // Match direct AllOnes for 128 and 256-bit vectors
13269   if (ISD::isBuildVectorAllOnes(N))
13270     return true;
13271
13272   // Look through a bit convert.
13273   if (N->getOpcode() == ISD::BITCAST)
13274     N = N->getOperand(0).getNode();
13275
13276   // Sometimes the operand may come from a insert_subvector building a 256-bit
13277   // allones vector
13278   if (VT.getSizeInBits() == 256 &&
13279       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13280     SDValue V1 = N->getOperand(0);
13281     SDValue V2 = N->getOperand(1);
13282
13283     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13284         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13285         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13286         ISD::isBuildVectorAllOnes(V2.getNode()))
13287       return true;
13288   }
13289
13290   return false;
13291 }
13292
13293 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13294                                  TargetLowering::DAGCombinerInfo &DCI,
13295                                  const X86Subtarget *Subtarget) {
13296   if (DCI.isBeforeLegalizeOps())
13297     return SDValue();
13298
13299   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13300   if (R.getNode())
13301     return R;
13302
13303   EVT VT = N->getValueType(0);
13304
13305   // Create ANDN, BLSI, and BLSR instructions
13306   // BLSI is X & (-X)
13307   // BLSR is X & (X-1)
13308   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13309     SDValue N0 = N->getOperand(0);
13310     SDValue N1 = N->getOperand(1);
13311     DebugLoc DL = N->getDebugLoc();
13312
13313     // Check LHS for not
13314     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13315       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13316     // Check RHS for not
13317     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13318       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13319
13320     // Check LHS for neg
13321     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13322         isZero(N0.getOperand(0)))
13323       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13324
13325     // Check RHS for neg
13326     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13327         isZero(N1.getOperand(0)))
13328       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13329
13330     // Check LHS for X-1
13331     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13332         isAllOnes(N0.getOperand(1)))
13333       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13334
13335     // Check RHS for X-1
13336     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13337         isAllOnes(N1.getOperand(1)))
13338       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13339
13340     return SDValue();
13341   }
13342
13343   // Want to form ANDNP nodes:
13344   // 1) In the hopes of then easily combining them with OR and AND nodes
13345   //    to form PBLEND/PSIGN.
13346   // 2) To match ANDN packed intrinsics
13347   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13348     return SDValue();
13349
13350   SDValue N0 = N->getOperand(0);
13351   SDValue N1 = N->getOperand(1);
13352   DebugLoc DL = N->getDebugLoc();
13353
13354   // Check LHS for vnot
13355   if (N0.getOpcode() == ISD::XOR &&
13356       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13357       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13358     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13359
13360   // Check RHS for vnot
13361   if (N1.getOpcode() == ISD::XOR &&
13362       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13363       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13364     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13365
13366   return SDValue();
13367 }
13368
13369 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13370                                 TargetLowering::DAGCombinerInfo &DCI,
13371                                 const X86Subtarget *Subtarget) {
13372   if (DCI.isBeforeLegalizeOps())
13373     return SDValue();
13374
13375   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13376   if (R.getNode())
13377     return R;
13378
13379   EVT VT = N->getValueType(0);
13380   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13381     return SDValue();
13382
13383   SDValue N0 = N->getOperand(0);
13384   SDValue N1 = N->getOperand(1);
13385
13386   // look for psign/blend
13387   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13388     if (VT == MVT::v2i64) {
13389       // Canonicalize pandn to RHS
13390       if (N0.getOpcode() == X86ISD::ANDNP)
13391         std::swap(N0, N1);
13392       // or (and (m, x), (pandn m, y))
13393       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13394         SDValue Mask = N1.getOperand(0);
13395         SDValue X    = N1.getOperand(1);
13396         SDValue Y;
13397         if (N0.getOperand(0) == Mask)
13398           Y = N0.getOperand(1);
13399         if (N0.getOperand(1) == Mask)
13400           Y = N0.getOperand(0);
13401
13402         // Check to see if the mask appeared in both the AND and ANDNP and
13403         if (!Y.getNode())
13404           return SDValue();
13405
13406         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13407         if (Mask.getOpcode() != ISD::BITCAST ||
13408             X.getOpcode() != ISD::BITCAST ||
13409             Y.getOpcode() != ISD::BITCAST)
13410           return SDValue();
13411
13412         // Look through mask bitcast.
13413         Mask = Mask.getOperand(0);
13414         EVT MaskVT = Mask.getValueType();
13415
13416         // Validate that the Mask operand is a vector sra node.  The sra node
13417         // will be an intrinsic.
13418         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13419           return SDValue();
13420
13421         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13422         // there is no psrai.b
13423         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13424         case Intrinsic::x86_sse2_psrai_w:
13425         case Intrinsic::x86_sse2_psrai_d:
13426           break;
13427         default: return SDValue();
13428         }
13429
13430         // Check that the SRA is all signbits.
13431         SDValue SraC = Mask.getOperand(2);
13432         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13433         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13434         if ((SraAmt + 1) != EltBits)
13435           return SDValue();
13436
13437         DebugLoc DL = N->getDebugLoc();
13438
13439         // Now we know we at least have a plendvb with the mask val.  See if
13440         // we can form a psignb/w/d.
13441         // psign = x.type == y.type == mask.type && y = sub(0, x);
13442         X = X.getOperand(0);
13443         Y = Y.getOperand(0);
13444         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13445             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13446             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13447           unsigned Opc = 0;
13448           switch (EltBits) {
13449           case 8: Opc = X86ISD::PSIGNB; break;
13450           case 16: Opc = X86ISD::PSIGNW; break;
13451           case 32: Opc = X86ISD::PSIGND; break;
13452           default: break;
13453           }
13454           if (Opc) {
13455             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13456             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13457           }
13458         }
13459         // PBLENDVB only available on SSE 4.1
13460         if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13461           return SDValue();
13462
13463         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13464         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13465         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13466         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13467         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13468       }
13469     }
13470   }
13471
13472   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13473   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13474     std::swap(N0, N1);
13475   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13476     return SDValue();
13477   if (!N0.hasOneUse() || !N1.hasOneUse())
13478     return SDValue();
13479
13480   SDValue ShAmt0 = N0.getOperand(1);
13481   if (ShAmt0.getValueType() != MVT::i8)
13482     return SDValue();
13483   SDValue ShAmt1 = N1.getOperand(1);
13484   if (ShAmt1.getValueType() != MVT::i8)
13485     return SDValue();
13486   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13487     ShAmt0 = ShAmt0.getOperand(0);
13488   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13489     ShAmt1 = ShAmt1.getOperand(0);
13490
13491   DebugLoc DL = N->getDebugLoc();
13492   unsigned Opc = X86ISD::SHLD;
13493   SDValue Op0 = N0.getOperand(0);
13494   SDValue Op1 = N1.getOperand(0);
13495   if (ShAmt0.getOpcode() == ISD::SUB) {
13496     Opc = X86ISD::SHRD;
13497     std::swap(Op0, Op1);
13498     std::swap(ShAmt0, ShAmt1);
13499   }
13500
13501   unsigned Bits = VT.getSizeInBits();
13502   if (ShAmt1.getOpcode() == ISD::SUB) {
13503     SDValue Sum = ShAmt1.getOperand(0);
13504     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13505       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13506       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13507         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13508       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13509         return DAG.getNode(Opc, DL, VT,
13510                            Op0, Op1,
13511                            DAG.getNode(ISD::TRUNCATE, DL,
13512                                        MVT::i8, ShAmt0));
13513     }
13514   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13515     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13516     if (ShAmt0C &&
13517         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13518       return DAG.getNode(Opc, DL, VT,
13519                          N0.getOperand(0), N1.getOperand(0),
13520                          DAG.getNode(ISD::TRUNCATE, DL,
13521                                        MVT::i8, ShAmt0));
13522   }
13523
13524   return SDValue();
13525 }
13526
13527 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13528                                  TargetLowering::DAGCombinerInfo &DCI,
13529                                  const X86Subtarget *Subtarget) {
13530   if (DCI.isBeforeLegalizeOps())
13531     return SDValue();
13532
13533   EVT VT = N->getValueType(0);
13534
13535   if (VT != MVT::i32 && VT != MVT::i64)
13536     return SDValue();
13537
13538   // Create BLSMSK instructions by finding X ^ (X-1)
13539   SDValue N0 = N->getOperand(0);
13540   SDValue N1 = N->getOperand(1);
13541   DebugLoc DL = N->getDebugLoc();
13542
13543   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13544       isAllOnes(N0.getOperand(1)))
13545     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13546
13547   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13548       isAllOnes(N1.getOperand(1)))
13549     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13550
13551   return SDValue();
13552 }
13553
13554 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13555 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13556                                    const X86Subtarget *Subtarget) {
13557   LoadSDNode *Ld = cast<LoadSDNode>(N);
13558   EVT RegVT = Ld->getValueType(0);
13559   EVT MemVT = Ld->getMemoryVT();
13560   DebugLoc dl = Ld->getDebugLoc();
13561   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13562
13563   ISD::LoadExtType Ext = Ld->getExtensionType();
13564
13565   // If this is a vector EXT Load then attempt to optimize it using a
13566   // shuffle. We need SSE4 for the shuffles.
13567   // TODO: It is possible to support ZExt by zeroing the undef values
13568   // during the shuffle phase or after the shuffle.
13569   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13570     assert(MemVT != RegVT && "Cannot extend to the same type");
13571     assert(MemVT.isVector() && "Must load a vector from memory");
13572
13573     unsigned NumElems = RegVT.getVectorNumElements();
13574     unsigned RegSz = RegVT.getSizeInBits();
13575     unsigned MemSz = MemVT.getSizeInBits();
13576     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13577     // All sizes must be a power of two
13578     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13579
13580     // Attempt to load the original value using a single load op.
13581     // Find a scalar type which is equal to the loaded word size.
13582     MVT SclrLoadTy = MVT::i8;
13583     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13584          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13585       MVT Tp = (MVT::SimpleValueType)tp;
13586       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13587         SclrLoadTy = Tp;
13588         break;
13589       }
13590     }
13591
13592     // Proceed if a load word is found.
13593     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13594
13595     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13596       RegSz/SclrLoadTy.getSizeInBits());
13597
13598     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13599                                   RegSz/MemVT.getScalarType().getSizeInBits());
13600     // Can't shuffle using an illegal type.
13601     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13602
13603     // Perform a single load.
13604     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13605                                   Ld->getBasePtr(),
13606                                   Ld->getPointerInfo(), Ld->isVolatile(),
13607                                   Ld->isNonTemporal(), Ld->getAlignment());
13608
13609     // Insert the word loaded into a vector.
13610     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13611       LoadUnitVecVT, ScalarLoad);
13612
13613     // Bitcast the loaded value to a vector of the original element type, in
13614     // the size of the target vector type.
13615     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13616     unsigned SizeRatio = RegSz/MemSz;
13617
13618     // Redistribute the loaded elements into the different locations.
13619     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13620     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13621
13622     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13623                                 DAG.getUNDEF(SlicedVec.getValueType()),
13624                                 ShuffleVec.data());
13625
13626     // Bitcast to the requested type.
13627     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13628     // Replace the original load with the new sequence
13629     // and return the new chain.
13630     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13631     return SDValue(ScalarLoad.getNode(), 1);
13632   }
13633
13634   return SDValue();
13635 }
13636
13637 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13638 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13639                                    const X86Subtarget *Subtarget) {
13640   StoreSDNode *St = cast<StoreSDNode>(N);
13641   EVT VT = St->getValue().getValueType();
13642   EVT StVT = St->getMemoryVT();
13643   DebugLoc dl = St->getDebugLoc();
13644   SDValue StoredVal = St->getOperand(1);
13645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13646
13647   // If we are saving a concatination of two XMM registers, perform two stores.
13648   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13649   // 128-bit ones. If in the future the cost becomes only one memory access the
13650   // first version would be better.
13651   if (VT.getSizeInBits() == 256 &&
13652     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13653     StoredVal.getNumOperands() == 2) {
13654
13655     SDValue Value0 = StoredVal.getOperand(0);
13656     SDValue Value1 = StoredVal.getOperand(1);
13657
13658     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13659     SDValue Ptr0 = St->getBasePtr();
13660     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13661
13662     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13663                                 St->getPointerInfo(), St->isVolatile(),
13664                                 St->isNonTemporal(), St->getAlignment());
13665     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13666                                 St->getPointerInfo(), St->isVolatile(),
13667                                 St->isNonTemporal(), St->getAlignment());
13668     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13669   }
13670
13671   // Optimize trunc store (of multiple scalars) to shuffle and store.
13672   // First, pack all of the elements in one place. Next, store to memory
13673   // in fewer chunks.
13674   if (St->isTruncatingStore() && VT.isVector()) {
13675     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13676     unsigned NumElems = VT.getVectorNumElements();
13677     assert(StVT != VT && "Cannot truncate to the same type");
13678     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13679     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13680
13681     // From, To sizes and ElemCount must be pow of two
13682     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13683     // We are going to use the original vector elt for storing.
13684     // Accumulated smaller vector elements must be a multiple of the store size.
13685     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13686
13687     unsigned SizeRatio  = FromSz / ToSz;
13688
13689     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13690
13691     // Create a type on which we perform the shuffle
13692     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13693             StVT.getScalarType(), NumElems*SizeRatio);
13694
13695     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13696
13697     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13698     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13699     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13700
13701     // Can't shuffle using an illegal type
13702     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13703
13704     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13705                                 DAG.getUNDEF(WideVec.getValueType()),
13706                                 ShuffleVec.data());
13707     // At this point all of the data is stored at the bottom of the
13708     // register. We now need to save it to mem.
13709
13710     // Find the largest store unit
13711     MVT StoreType = MVT::i8;
13712     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13713          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13714       MVT Tp = (MVT::SimpleValueType)tp;
13715       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13716         StoreType = Tp;
13717     }
13718
13719     // Bitcast the original vector into a vector of store-size units
13720     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13721             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13722     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13723     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13724     SmallVector<SDValue, 8> Chains;
13725     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13726                                         TLI.getPointerTy());
13727     SDValue Ptr = St->getBasePtr();
13728
13729     // Perform one or more big stores into memory.
13730     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13731       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13732                                    StoreType, ShuffWide,
13733                                    DAG.getIntPtrConstant(i));
13734       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13735                                 St->getPointerInfo(), St->isVolatile(),
13736                                 St->isNonTemporal(), St->getAlignment());
13737       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13738       Chains.push_back(Ch);
13739     }
13740
13741     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13742                                Chains.size());
13743   }
13744
13745
13746   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13747   // the FP state in cases where an emms may be missing.
13748   // A preferable solution to the general problem is to figure out the right
13749   // places to insert EMMS.  This qualifies as a quick hack.
13750
13751   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13752   if (VT.getSizeInBits() != 64)
13753     return SDValue();
13754
13755   const Function *F = DAG.getMachineFunction().getFunction();
13756   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13757   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13758                      && Subtarget->hasXMMInt();
13759   if ((VT.isVector() ||
13760        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13761       isa<LoadSDNode>(St->getValue()) &&
13762       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13763       St->getChain().hasOneUse() && !St->isVolatile()) {
13764     SDNode* LdVal = St->getValue().getNode();
13765     LoadSDNode *Ld = 0;
13766     int TokenFactorIndex = -1;
13767     SmallVector<SDValue, 8> Ops;
13768     SDNode* ChainVal = St->getChain().getNode();
13769     // Must be a store of a load.  We currently handle two cases:  the load
13770     // is a direct child, and it's under an intervening TokenFactor.  It is
13771     // possible to dig deeper under nested TokenFactors.
13772     if (ChainVal == LdVal)
13773       Ld = cast<LoadSDNode>(St->getChain());
13774     else if (St->getValue().hasOneUse() &&
13775              ChainVal->getOpcode() == ISD::TokenFactor) {
13776       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13777         if (ChainVal->getOperand(i).getNode() == LdVal) {
13778           TokenFactorIndex = i;
13779           Ld = cast<LoadSDNode>(St->getValue());
13780         } else
13781           Ops.push_back(ChainVal->getOperand(i));
13782       }
13783     }
13784
13785     if (!Ld || !ISD::isNormalLoad(Ld))
13786       return SDValue();
13787
13788     // If this is not the MMX case, i.e. we are just turning i64 load/store
13789     // into f64 load/store, avoid the transformation if there are multiple
13790     // uses of the loaded value.
13791     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13792       return SDValue();
13793
13794     DebugLoc LdDL = Ld->getDebugLoc();
13795     DebugLoc StDL = N->getDebugLoc();
13796     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13797     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13798     // pair instead.
13799     if (Subtarget->is64Bit() || F64IsLegal) {
13800       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13801       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13802                                   Ld->getPointerInfo(), Ld->isVolatile(),
13803                                   Ld->isNonTemporal(), Ld->getAlignment());
13804       SDValue NewChain = NewLd.getValue(1);
13805       if (TokenFactorIndex != -1) {
13806         Ops.push_back(NewChain);
13807         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13808                                Ops.size());
13809       }
13810       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13811                           St->getPointerInfo(),
13812                           St->isVolatile(), St->isNonTemporal(),
13813                           St->getAlignment());
13814     }
13815
13816     // Otherwise, lower to two pairs of 32-bit loads / stores.
13817     SDValue LoAddr = Ld->getBasePtr();
13818     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13819                                  DAG.getConstant(4, MVT::i32));
13820
13821     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13822                                Ld->getPointerInfo(),
13823                                Ld->isVolatile(), Ld->isNonTemporal(),
13824                                Ld->getAlignment());
13825     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13826                                Ld->getPointerInfo().getWithOffset(4),
13827                                Ld->isVolatile(), Ld->isNonTemporal(),
13828                                MinAlign(Ld->getAlignment(), 4));
13829
13830     SDValue NewChain = LoLd.getValue(1);
13831     if (TokenFactorIndex != -1) {
13832       Ops.push_back(LoLd);
13833       Ops.push_back(HiLd);
13834       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13835                              Ops.size());
13836     }
13837
13838     LoAddr = St->getBasePtr();
13839     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13840                          DAG.getConstant(4, MVT::i32));
13841
13842     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13843                                 St->getPointerInfo(),
13844                                 St->isVolatile(), St->isNonTemporal(),
13845                                 St->getAlignment());
13846     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13847                                 St->getPointerInfo().getWithOffset(4),
13848                                 St->isVolatile(),
13849                                 St->isNonTemporal(),
13850                                 MinAlign(St->getAlignment(), 4));
13851     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13852   }
13853   return SDValue();
13854 }
13855
13856 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
13857 /// and return the operands for the horizontal operation in LHS and RHS.  A
13858 /// horizontal operation performs the binary operation on successive elements
13859 /// of its first operand, then on successive elements of its second operand,
13860 /// returning the resulting values in a vector.  For example, if
13861 ///   A = < float a0, float a1, float a2, float a3 >
13862 /// and
13863 ///   B = < float b0, float b1, float b2, float b3 >
13864 /// then the result of doing a horizontal operation on A and B is
13865 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
13866 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
13867 /// A horizontal-op B, for some already available A and B, and if so then LHS is
13868 /// set to A, RHS to B, and the routine returns 'true'.
13869 /// Note that the binary operation should have the property that if one of the
13870 /// operands is UNDEF then the result is UNDEF.
13871 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
13872   // Look for the following pattern: if
13873   //   A = < float a0, float a1, float a2, float a3 >
13874   //   B = < float b0, float b1, float b2, float b3 >
13875   // and
13876   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
13877   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
13878   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
13879   // which is A horizontal-op B.
13880
13881   // At least one of the operands should be a vector shuffle.
13882   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13883       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
13884     return false;
13885
13886   EVT VT = LHS.getValueType();
13887   unsigned N = VT.getVectorNumElements();
13888
13889   // View LHS in the form
13890   //   LHS = VECTOR_SHUFFLE A, B, LMask
13891   // If LHS is not a shuffle then pretend it is the shuffle
13892   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
13893   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
13894   // type VT.
13895   SDValue A, B;
13896   SmallVector<int, 8> LMask(N);
13897   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13898     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
13899       A = LHS.getOperand(0);
13900     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
13901       B = LHS.getOperand(1);
13902     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
13903   } else {
13904     if (LHS.getOpcode() != ISD::UNDEF)
13905       A = LHS;
13906     for (unsigned i = 0; i != N; ++i)
13907       LMask[i] = i;
13908   }
13909
13910   // Likewise, view RHS in the form
13911   //   RHS = VECTOR_SHUFFLE C, D, RMask
13912   SDValue C, D;
13913   SmallVector<int, 8> RMask(N);
13914   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13915     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
13916       C = RHS.getOperand(0);
13917     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
13918       D = RHS.getOperand(1);
13919     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
13920   } else {
13921     if (RHS.getOpcode() != ISD::UNDEF)
13922       C = RHS;
13923     for (unsigned i = 0; i != N; ++i)
13924       RMask[i] = i;
13925   }
13926
13927   // Check that the shuffles are both shuffling the same vectors.
13928   if (!(A == C && B == D) && !(A == D && B == C))
13929     return false;
13930
13931   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
13932   if (!A.getNode() && !B.getNode())
13933     return false;
13934
13935   // If A and B occur in reverse order in RHS, then "swap" them (which means
13936   // rewriting the mask).
13937   if (A != C)
13938     for (unsigned i = 0; i != N; ++i) {
13939       unsigned Idx = RMask[i];
13940       if (Idx < N)
13941         RMask[i] += N;
13942       else if (Idx < 2*N)
13943         RMask[i] -= N;
13944     }
13945
13946   // At this point LHS and RHS are equivalent to
13947   //   LHS = VECTOR_SHUFFLE A, B, LMask
13948   //   RHS = VECTOR_SHUFFLE A, B, RMask
13949   // Check that the masks correspond to performing a horizontal operation.
13950   for (unsigned i = 0; i != N; ++i) {
13951     unsigned LIdx = LMask[i], RIdx = RMask[i];
13952
13953     // Ignore any UNDEF components.
13954     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
13955         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
13956       continue;
13957
13958     // Check that successive elements are being operated on.  If not, this is
13959     // not a horizontal operation.
13960     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
13961         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
13962       return false;
13963   }
13964
13965   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
13966   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
13967   return true;
13968 }
13969
13970 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
13971 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
13972                                   const X86Subtarget *Subtarget) {
13973   EVT VT = N->getValueType(0);
13974   SDValue LHS = N->getOperand(0);
13975   SDValue RHS = N->getOperand(1);
13976
13977   // Try to synthesize horizontal adds from adds of shuffles.
13978   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13979       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13980       isHorizontalBinOp(LHS, RHS, true))
13981     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
13982   return SDValue();
13983 }
13984
13985 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
13986 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
13987                                   const X86Subtarget *Subtarget) {
13988   EVT VT = N->getValueType(0);
13989   SDValue LHS = N->getOperand(0);
13990   SDValue RHS = N->getOperand(1);
13991
13992   // Try to synthesize horizontal subs from subs of shuffles.
13993   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13994       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13995       isHorizontalBinOp(LHS, RHS, false))
13996     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
13997   return SDValue();
13998 }
13999
14000 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14001 /// X86ISD::FXOR nodes.
14002 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14003   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14004   // F[X]OR(0.0, x) -> x
14005   // F[X]OR(x, 0.0) -> x
14006   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14007     if (C->getValueAPF().isPosZero())
14008       return N->getOperand(1);
14009   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14010     if (C->getValueAPF().isPosZero())
14011       return N->getOperand(0);
14012   return SDValue();
14013 }
14014
14015 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14016 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14017   // FAND(0.0, x) -> 0.0
14018   // FAND(x, 0.0) -> 0.0
14019   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14020     if (C->getValueAPF().isPosZero())
14021       return N->getOperand(0);
14022   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14023     if (C->getValueAPF().isPosZero())
14024       return N->getOperand(1);
14025   return SDValue();
14026 }
14027
14028 static SDValue PerformBTCombine(SDNode *N,
14029                                 SelectionDAG &DAG,
14030                                 TargetLowering::DAGCombinerInfo &DCI) {
14031   // BT ignores high bits in the bit index operand.
14032   SDValue Op1 = N->getOperand(1);
14033   if (Op1.hasOneUse()) {
14034     unsigned BitWidth = Op1.getValueSizeInBits();
14035     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14036     APInt KnownZero, KnownOne;
14037     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14038                                           !DCI.isBeforeLegalizeOps());
14039     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14040     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14041         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14042       DCI.CommitTargetLoweringOpt(TLO);
14043   }
14044   return SDValue();
14045 }
14046
14047 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14048   SDValue Op = N->getOperand(0);
14049   if (Op.getOpcode() == ISD::BITCAST)
14050     Op = Op.getOperand(0);
14051   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14052   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14053       VT.getVectorElementType().getSizeInBits() ==
14054       OpVT.getVectorElementType().getSizeInBits()) {
14055     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14056   }
14057   return SDValue();
14058 }
14059
14060 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14061   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14062   //           (and (i32 x86isd::setcc_carry), 1)
14063   // This eliminates the zext. This transformation is necessary because
14064   // ISD::SETCC is always legalized to i8.
14065   DebugLoc dl = N->getDebugLoc();
14066   SDValue N0 = N->getOperand(0);
14067   EVT VT = N->getValueType(0);
14068   if (N0.getOpcode() == ISD::AND &&
14069       N0.hasOneUse() &&
14070       N0.getOperand(0).hasOneUse()) {
14071     SDValue N00 = N0.getOperand(0);
14072     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14073       return SDValue();
14074     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14075     if (!C || C->getZExtValue() != 1)
14076       return SDValue();
14077     return DAG.getNode(ISD::AND, dl, VT,
14078                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14079                                    N00.getOperand(0), N00.getOperand(1)),
14080                        DAG.getConstant(1, VT));
14081   }
14082
14083   return SDValue();
14084 }
14085
14086 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14087 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14088   unsigned X86CC = N->getConstantOperandVal(0);
14089   SDValue EFLAG = N->getOperand(1);
14090   DebugLoc DL = N->getDebugLoc();
14091
14092   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14093   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14094   // cases.
14095   if (X86CC == X86::COND_B)
14096     return DAG.getNode(ISD::AND, DL, MVT::i8,
14097                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14098                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14099                        DAG.getConstant(1, MVT::i8));
14100
14101   return SDValue();
14102 }
14103
14104 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14105                                         const X86TargetLowering *XTLI) {
14106   SDValue Op0 = N->getOperand(0);
14107   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14108   // a 32-bit target where SSE doesn't support i64->FP operations.
14109   if (Op0.getOpcode() == ISD::LOAD) {
14110     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14111     EVT VT = Ld->getValueType(0);
14112     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14113         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14114         !XTLI->getSubtarget()->is64Bit() &&
14115         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14116       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14117                                           Ld->getChain(), Op0, DAG);
14118       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14119       return FILDChain;
14120     }
14121   }
14122   return SDValue();
14123 }
14124
14125 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14126 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14127                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14128   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14129   // the result is either zero or one (depending on the input carry bit).
14130   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14131   if (X86::isZeroNode(N->getOperand(0)) &&
14132       X86::isZeroNode(N->getOperand(1)) &&
14133       // We don't have a good way to replace an EFLAGS use, so only do this when
14134       // dead right now.
14135       SDValue(N, 1).use_empty()) {
14136     DebugLoc DL = N->getDebugLoc();
14137     EVT VT = N->getValueType(0);
14138     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14139     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14140                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14141                                            DAG.getConstant(X86::COND_B,MVT::i8),
14142                                            N->getOperand(2)),
14143                                DAG.getConstant(1, VT));
14144     return DCI.CombineTo(N, Res1, CarryOut);
14145   }
14146
14147   return SDValue();
14148 }
14149
14150 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14151 //      (add Y, (setne X, 0)) -> sbb -1, Y
14152 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14153 //      (sub (setne X, 0), Y) -> adc -1, Y
14154 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14155   DebugLoc DL = N->getDebugLoc();
14156
14157   // Look through ZExts.
14158   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14159   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14160     return SDValue();
14161
14162   SDValue SetCC = Ext.getOperand(0);
14163   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14164     return SDValue();
14165
14166   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14167   if (CC != X86::COND_E && CC != X86::COND_NE)
14168     return SDValue();
14169
14170   SDValue Cmp = SetCC.getOperand(1);
14171   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14172       !X86::isZeroNode(Cmp.getOperand(1)) ||
14173       !Cmp.getOperand(0).getValueType().isInteger())
14174     return SDValue();
14175
14176   SDValue CmpOp0 = Cmp.getOperand(0);
14177   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14178                                DAG.getConstant(1, CmpOp0.getValueType()));
14179
14180   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14181   if (CC == X86::COND_NE)
14182     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14183                        DL, OtherVal.getValueType(), OtherVal,
14184                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14185   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14186                      DL, OtherVal.getValueType(), OtherVal,
14187                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14188 }
14189
14190 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14191   SDValue Op0 = N->getOperand(0);
14192   SDValue Op1 = N->getOperand(1);
14193
14194   // X86 can't encode an immediate LHS of a sub. See if we can push the
14195   // negation into a preceding instruction.
14196   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14197     // If the RHS of the sub is a XOR with one use and a constant, invert the
14198     // immediate. Then add one to the LHS of the sub so we can turn
14199     // X-Y -> X+~Y+1, saving one register.
14200     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14201         isa<ConstantSDNode>(Op1.getOperand(1))) {
14202       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14203       EVT VT = Op0.getValueType();
14204       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14205                                    Op1.getOperand(0),
14206                                    DAG.getConstant(~XorC, VT));
14207       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14208                          DAG.getConstant(C->getAPIntValue()+1, VT));
14209     }
14210   }
14211
14212   return OptimizeConditionalInDecrement(N, DAG);
14213 }
14214
14215 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14216                                              DAGCombinerInfo &DCI) const {
14217   SelectionDAG &DAG = DCI.DAG;
14218   switch (N->getOpcode()) {
14219   default: break;
14220   case ISD::EXTRACT_VECTOR_ELT:
14221     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14222   case ISD::VSELECT:
14223   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14224   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14225   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14226   case ISD::SUB:            return PerformSubCombine(N, DAG);
14227   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14228   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14229   case ISD::SHL:
14230   case ISD::SRA:
14231   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14232   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14233   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14234   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14235   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14236   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14237   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14238   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14239   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14240   case X86ISD::FXOR:
14241   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14242   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14243   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14244   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14245   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14246   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14247   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14248   case X86ISD::SHUFPD:
14249   case X86ISD::PALIGN:
14250   case X86ISD::PUNPCKHBW:
14251   case X86ISD::PUNPCKHWD:
14252   case X86ISD::PUNPCKHDQ:
14253   case X86ISD::PUNPCKHQDQ:
14254   case X86ISD::UNPCKHPS:
14255   case X86ISD::UNPCKHPD:
14256   case X86ISD::VUNPCKHPSY:
14257   case X86ISD::VUNPCKHPDY:
14258   case X86ISD::PUNPCKLBW:
14259   case X86ISD::PUNPCKLWD:
14260   case X86ISD::PUNPCKLDQ:
14261   case X86ISD::PUNPCKLQDQ:
14262   case X86ISD::UNPCKLPS:
14263   case X86ISD::UNPCKLPD:
14264   case X86ISD::VUNPCKLPSY:
14265   case X86ISD::VUNPCKLPDY:
14266   case X86ISD::MOVHLPS:
14267   case X86ISD::MOVLHPS:
14268   case X86ISD::PSHUFD:
14269   case X86ISD::PSHUFHW:
14270   case X86ISD::PSHUFLW:
14271   case X86ISD::MOVSS:
14272   case X86ISD::MOVSD:
14273   case X86ISD::VPERMILPS:
14274   case X86ISD::VPERMILPSY:
14275   case X86ISD::VPERMILPD:
14276   case X86ISD::VPERMILPDY:
14277   case X86ISD::VPERM2F128:
14278   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14279   }
14280
14281   return SDValue();
14282 }
14283
14284 /// isTypeDesirableForOp - Return true if the target has native support for
14285 /// the specified value type and it is 'desirable' to use the type for the
14286 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14287 /// instruction encodings are longer and some i16 instructions are slow.
14288 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14289   if (!isTypeLegal(VT))
14290     return false;
14291   if (VT != MVT::i16)
14292     return true;
14293
14294   switch (Opc) {
14295   default:
14296     return true;
14297   case ISD::LOAD:
14298   case ISD::SIGN_EXTEND:
14299   case ISD::ZERO_EXTEND:
14300   case ISD::ANY_EXTEND:
14301   case ISD::SHL:
14302   case ISD::SRL:
14303   case ISD::SUB:
14304   case ISD::ADD:
14305   case ISD::MUL:
14306   case ISD::AND:
14307   case ISD::OR:
14308   case ISD::XOR:
14309     return false;
14310   }
14311 }
14312
14313 /// IsDesirableToPromoteOp - This method query the target whether it is
14314 /// beneficial for dag combiner to promote the specified node. If true, it
14315 /// should return the desired promotion type by reference.
14316 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14317   EVT VT = Op.getValueType();
14318   if (VT != MVT::i16)
14319     return false;
14320
14321   bool Promote = false;
14322   bool Commute = false;
14323   switch (Op.getOpcode()) {
14324   default: break;
14325   case ISD::LOAD: {
14326     LoadSDNode *LD = cast<LoadSDNode>(Op);
14327     // If the non-extending load has a single use and it's not live out, then it
14328     // might be folded.
14329     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14330                                                      Op.hasOneUse()*/) {
14331       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14332              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14333         // The only case where we'd want to promote LOAD (rather then it being
14334         // promoted as an operand is when it's only use is liveout.
14335         if (UI->getOpcode() != ISD::CopyToReg)
14336           return false;
14337       }
14338     }
14339     Promote = true;
14340     break;
14341   }
14342   case ISD::SIGN_EXTEND:
14343   case ISD::ZERO_EXTEND:
14344   case ISD::ANY_EXTEND:
14345     Promote = true;
14346     break;
14347   case ISD::SHL:
14348   case ISD::SRL: {
14349     SDValue N0 = Op.getOperand(0);
14350     // Look out for (store (shl (load), x)).
14351     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14352       return false;
14353     Promote = true;
14354     break;
14355   }
14356   case ISD::ADD:
14357   case ISD::MUL:
14358   case ISD::AND:
14359   case ISD::OR:
14360   case ISD::XOR:
14361     Commute = true;
14362     // fallthrough
14363   case ISD::SUB: {
14364     SDValue N0 = Op.getOperand(0);
14365     SDValue N1 = Op.getOperand(1);
14366     if (!Commute && MayFoldLoad(N1))
14367       return false;
14368     // Avoid disabling potential load folding opportunities.
14369     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14370       return false;
14371     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14372       return false;
14373     Promote = true;
14374   }
14375   }
14376
14377   PVT = MVT::i32;
14378   return Promote;
14379 }
14380
14381 //===----------------------------------------------------------------------===//
14382 //                           X86 Inline Assembly Support
14383 //===----------------------------------------------------------------------===//
14384
14385 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14386   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14387
14388   std::string AsmStr = IA->getAsmString();
14389
14390   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14391   SmallVector<StringRef, 4> AsmPieces;
14392   SplitString(AsmStr, AsmPieces, ";\n");
14393
14394   switch (AsmPieces.size()) {
14395   default: return false;
14396   case 1:
14397     AsmStr = AsmPieces[0];
14398     AsmPieces.clear();
14399     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14400
14401     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14402     // we will turn this bswap into something that will be lowered to logical ops
14403     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14404     // so don't worry about this.
14405     // bswap $0
14406     if (AsmPieces.size() == 2 &&
14407         (AsmPieces[0] == "bswap" ||
14408          AsmPieces[0] == "bswapq" ||
14409          AsmPieces[0] == "bswapl") &&
14410         (AsmPieces[1] == "$0" ||
14411          AsmPieces[1] == "${0:q}")) {
14412       // No need to check constraints, nothing other than the equivalent of
14413       // "=r,0" would be valid here.
14414       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14415       if (!Ty || Ty->getBitWidth() % 16 != 0)
14416         return false;
14417       return IntrinsicLowering::LowerToByteSwap(CI);
14418     }
14419     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14420     if (CI->getType()->isIntegerTy(16) &&
14421         AsmPieces.size() == 3 &&
14422         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14423         AsmPieces[1] == "$$8," &&
14424         AsmPieces[2] == "${0:w}" &&
14425         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14426       AsmPieces.clear();
14427       const std::string &ConstraintsStr = IA->getConstraintString();
14428       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14429       std::sort(AsmPieces.begin(), AsmPieces.end());
14430       if (AsmPieces.size() == 4 &&
14431           AsmPieces[0] == "~{cc}" &&
14432           AsmPieces[1] == "~{dirflag}" &&
14433           AsmPieces[2] == "~{flags}" &&
14434           AsmPieces[3] == "~{fpsr}") {
14435         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14436         if (!Ty || Ty->getBitWidth() % 16 != 0)
14437           return false;
14438         return IntrinsicLowering::LowerToByteSwap(CI);
14439       }
14440     }
14441     break;
14442   case 3:
14443     if (CI->getType()->isIntegerTy(32) &&
14444         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14445       SmallVector<StringRef, 4> Words;
14446       SplitString(AsmPieces[0], Words, " \t,");
14447       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14448           Words[2] == "${0:w}") {
14449         Words.clear();
14450         SplitString(AsmPieces[1], Words, " \t,");
14451         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14452             Words[2] == "$0") {
14453           Words.clear();
14454           SplitString(AsmPieces[2], Words, " \t,");
14455           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14456               Words[2] == "${0:w}") {
14457             AsmPieces.clear();
14458             const std::string &ConstraintsStr = IA->getConstraintString();
14459             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14460             std::sort(AsmPieces.begin(), AsmPieces.end());
14461             if (AsmPieces.size() == 4 &&
14462                 AsmPieces[0] == "~{cc}" &&
14463                 AsmPieces[1] == "~{dirflag}" &&
14464                 AsmPieces[2] == "~{flags}" &&
14465                 AsmPieces[3] == "~{fpsr}") {
14466               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14467               if (!Ty || Ty->getBitWidth() % 16 != 0)
14468                 return false;
14469               return IntrinsicLowering::LowerToByteSwap(CI);
14470             }
14471           }
14472         }
14473       }
14474     }
14475
14476     if (CI->getType()->isIntegerTy(64)) {
14477       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14478       if (Constraints.size() >= 2 &&
14479           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14480           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14481         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14482         SmallVector<StringRef, 4> Words;
14483         SplitString(AsmPieces[0], Words, " \t");
14484         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14485           Words.clear();
14486           SplitString(AsmPieces[1], Words, " \t");
14487           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14488             Words.clear();
14489             SplitString(AsmPieces[2], Words, " \t,");
14490             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14491                 Words[2] == "%edx") {
14492               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14493               if (!Ty || Ty->getBitWidth() % 16 != 0)
14494                 return false;
14495               return IntrinsicLowering::LowerToByteSwap(CI);
14496             }
14497           }
14498         }
14499       }
14500     }
14501     break;
14502   }
14503   return false;
14504 }
14505
14506
14507
14508 /// getConstraintType - Given a constraint letter, return the type of
14509 /// constraint it is for this target.
14510 X86TargetLowering::ConstraintType
14511 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14512   if (Constraint.size() == 1) {
14513     switch (Constraint[0]) {
14514     case 'R':
14515     case 'q':
14516     case 'Q':
14517     case 'f':
14518     case 't':
14519     case 'u':
14520     case 'y':
14521     case 'x':
14522     case 'Y':
14523     case 'l':
14524       return C_RegisterClass;
14525     case 'a':
14526     case 'b':
14527     case 'c':
14528     case 'd':
14529     case 'S':
14530     case 'D':
14531     case 'A':
14532       return C_Register;
14533     case 'I':
14534     case 'J':
14535     case 'K':
14536     case 'L':
14537     case 'M':
14538     case 'N':
14539     case 'G':
14540     case 'C':
14541     case 'e':
14542     case 'Z':
14543       return C_Other;
14544     default:
14545       break;
14546     }
14547   }
14548   return TargetLowering::getConstraintType(Constraint);
14549 }
14550
14551 /// Examine constraint type and operand type and determine a weight value.
14552 /// This object must already have been set up with the operand type
14553 /// and the current alternative constraint selected.
14554 TargetLowering::ConstraintWeight
14555   X86TargetLowering::getSingleConstraintMatchWeight(
14556     AsmOperandInfo &info, const char *constraint) const {
14557   ConstraintWeight weight = CW_Invalid;
14558   Value *CallOperandVal = info.CallOperandVal;
14559     // If we don't have a value, we can't do a match,
14560     // but allow it at the lowest weight.
14561   if (CallOperandVal == NULL)
14562     return CW_Default;
14563   Type *type = CallOperandVal->getType();
14564   // Look at the constraint type.
14565   switch (*constraint) {
14566   default:
14567     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14568   case 'R':
14569   case 'q':
14570   case 'Q':
14571   case 'a':
14572   case 'b':
14573   case 'c':
14574   case 'd':
14575   case 'S':
14576   case 'D':
14577   case 'A':
14578     if (CallOperandVal->getType()->isIntegerTy())
14579       weight = CW_SpecificReg;
14580     break;
14581   case 'f':
14582   case 't':
14583   case 'u':
14584       if (type->isFloatingPointTy())
14585         weight = CW_SpecificReg;
14586       break;
14587   case 'y':
14588       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14589         weight = CW_SpecificReg;
14590       break;
14591   case 'x':
14592   case 'Y':
14593     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14594       weight = CW_Register;
14595     break;
14596   case 'I':
14597     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14598       if (C->getZExtValue() <= 31)
14599         weight = CW_Constant;
14600     }
14601     break;
14602   case 'J':
14603     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14604       if (C->getZExtValue() <= 63)
14605         weight = CW_Constant;
14606     }
14607     break;
14608   case 'K':
14609     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14610       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14611         weight = CW_Constant;
14612     }
14613     break;
14614   case 'L':
14615     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14616       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14617         weight = CW_Constant;
14618     }
14619     break;
14620   case 'M':
14621     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14622       if (C->getZExtValue() <= 3)
14623         weight = CW_Constant;
14624     }
14625     break;
14626   case 'N':
14627     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14628       if (C->getZExtValue() <= 0xff)
14629         weight = CW_Constant;
14630     }
14631     break;
14632   case 'G':
14633   case 'C':
14634     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14635       weight = CW_Constant;
14636     }
14637     break;
14638   case 'e':
14639     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14640       if ((C->getSExtValue() >= -0x80000000LL) &&
14641           (C->getSExtValue() <= 0x7fffffffLL))
14642         weight = CW_Constant;
14643     }
14644     break;
14645   case 'Z':
14646     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14647       if (C->getZExtValue() <= 0xffffffff)
14648         weight = CW_Constant;
14649     }
14650     break;
14651   }
14652   return weight;
14653 }
14654
14655 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14656 /// with another that has more specific requirements based on the type of the
14657 /// corresponding operand.
14658 const char *X86TargetLowering::
14659 LowerXConstraint(EVT ConstraintVT) const {
14660   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14661   // 'f' like normal targets.
14662   if (ConstraintVT.isFloatingPoint()) {
14663     if (Subtarget->hasXMMInt())
14664       return "Y";
14665     if (Subtarget->hasXMM())
14666       return "x";
14667   }
14668
14669   return TargetLowering::LowerXConstraint(ConstraintVT);
14670 }
14671
14672 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14673 /// vector.  If it is invalid, don't add anything to Ops.
14674 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14675                                                      std::string &Constraint,
14676                                                      std::vector<SDValue>&Ops,
14677                                                      SelectionDAG &DAG) const {
14678   SDValue Result(0, 0);
14679
14680   // Only support length 1 constraints for now.
14681   if (Constraint.length() > 1) return;
14682
14683   char ConstraintLetter = Constraint[0];
14684   switch (ConstraintLetter) {
14685   default: break;
14686   case 'I':
14687     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14688       if (C->getZExtValue() <= 31) {
14689         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14690         break;
14691       }
14692     }
14693     return;
14694   case 'J':
14695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14696       if (C->getZExtValue() <= 63) {
14697         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14698         break;
14699       }
14700     }
14701     return;
14702   case 'K':
14703     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14704       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14705         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14706         break;
14707       }
14708     }
14709     return;
14710   case 'N':
14711     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14712       if (C->getZExtValue() <= 255) {
14713         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14714         break;
14715       }
14716     }
14717     return;
14718   case 'e': {
14719     // 32-bit signed value
14720     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14721       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14722                                            C->getSExtValue())) {
14723         // Widen to 64 bits here to get it sign extended.
14724         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14725         break;
14726       }
14727     // FIXME gcc accepts some relocatable values here too, but only in certain
14728     // memory models; it's complicated.
14729     }
14730     return;
14731   }
14732   case 'Z': {
14733     // 32-bit unsigned value
14734     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14735       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14736                                            C->getZExtValue())) {
14737         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14738         break;
14739       }
14740     }
14741     // FIXME gcc accepts some relocatable values here too, but only in certain
14742     // memory models; it's complicated.
14743     return;
14744   }
14745   case 'i': {
14746     // Literal immediates are always ok.
14747     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14748       // Widen to 64 bits here to get it sign extended.
14749       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14750       break;
14751     }
14752
14753     // In any sort of PIC mode addresses need to be computed at runtime by
14754     // adding in a register or some sort of table lookup.  These can't
14755     // be used as immediates.
14756     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14757       return;
14758
14759     // If we are in non-pic codegen mode, we allow the address of a global (with
14760     // an optional displacement) to be used with 'i'.
14761     GlobalAddressSDNode *GA = 0;
14762     int64_t Offset = 0;
14763
14764     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14765     while (1) {
14766       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14767         Offset += GA->getOffset();
14768         break;
14769       } else if (Op.getOpcode() == ISD::ADD) {
14770         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14771           Offset += C->getZExtValue();
14772           Op = Op.getOperand(0);
14773           continue;
14774         }
14775       } else if (Op.getOpcode() == ISD::SUB) {
14776         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14777           Offset += -C->getZExtValue();
14778           Op = Op.getOperand(0);
14779           continue;
14780         }
14781       }
14782
14783       // Otherwise, this isn't something we can handle, reject it.
14784       return;
14785     }
14786
14787     const GlobalValue *GV = GA->getGlobal();
14788     // If we require an extra load to get this address, as in PIC mode, we
14789     // can't accept it.
14790     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14791                                                         getTargetMachine())))
14792       return;
14793
14794     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14795                                         GA->getValueType(0), Offset);
14796     break;
14797   }
14798   }
14799
14800   if (Result.getNode()) {
14801     Ops.push_back(Result);
14802     return;
14803   }
14804   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14805 }
14806
14807 std::pair<unsigned, const TargetRegisterClass*>
14808 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14809                                                 EVT VT) const {
14810   // First, see if this is a constraint that directly corresponds to an LLVM
14811   // register class.
14812   if (Constraint.size() == 1) {
14813     // GCC Constraint Letters
14814     switch (Constraint[0]) {
14815     default: break;
14816       // TODO: Slight differences here in allocation order and leaving
14817       // RIP in the class. Do they matter any more here than they do
14818       // in the normal allocation?
14819     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14820       if (Subtarget->is64Bit()) {
14821         if (VT == MVT::i32 || VT == MVT::f32)
14822           return std::make_pair(0U, X86::GR32RegisterClass);
14823         else if (VT == MVT::i16)
14824           return std::make_pair(0U, X86::GR16RegisterClass);
14825         else if (VT == MVT::i8 || VT == MVT::i1)
14826           return std::make_pair(0U, X86::GR8RegisterClass);
14827         else if (VT == MVT::i64 || VT == MVT::f64)
14828           return std::make_pair(0U, X86::GR64RegisterClass);
14829         break;
14830       }
14831       // 32-bit fallthrough
14832     case 'Q':   // Q_REGS
14833       if (VT == MVT::i32 || VT == MVT::f32)
14834         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14835       else if (VT == MVT::i16)
14836         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14837       else if (VT == MVT::i8 || VT == MVT::i1)
14838         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14839       else if (VT == MVT::i64)
14840         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14841       break;
14842     case 'r':   // GENERAL_REGS
14843     case 'l':   // INDEX_REGS
14844       if (VT == MVT::i8 || VT == MVT::i1)
14845         return std::make_pair(0U, X86::GR8RegisterClass);
14846       if (VT == MVT::i16)
14847         return std::make_pair(0U, X86::GR16RegisterClass);
14848       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14849         return std::make_pair(0U, X86::GR32RegisterClass);
14850       return std::make_pair(0U, X86::GR64RegisterClass);
14851     case 'R':   // LEGACY_REGS
14852       if (VT == MVT::i8 || VT == MVT::i1)
14853         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14854       if (VT == MVT::i16)
14855         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14856       if (VT == MVT::i32 || !Subtarget->is64Bit())
14857         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14858       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14859     case 'f':  // FP Stack registers.
14860       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14861       // value to the correct fpstack register class.
14862       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14863         return std::make_pair(0U, X86::RFP32RegisterClass);
14864       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14865         return std::make_pair(0U, X86::RFP64RegisterClass);
14866       return std::make_pair(0U, X86::RFP80RegisterClass);
14867     case 'y':   // MMX_REGS if MMX allowed.
14868       if (!Subtarget->hasMMX()) break;
14869       return std::make_pair(0U, X86::VR64RegisterClass);
14870     case 'Y':   // SSE_REGS if SSE2 allowed
14871       if (!Subtarget->hasXMMInt()) break;
14872       // FALL THROUGH.
14873     case 'x':   // SSE_REGS if SSE1 allowed
14874       if (!Subtarget->hasXMM()) break;
14875
14876       switch (VT.getSimpleVT().SimpleTy) {
14877       default: break;
14878       // Scalar SSE types.
14879       case MVT::f32:
14880       case MVT::i32:
14881         return std::make_pair(0U, X86::FR32RegisterClass);
14882       case MVT::f64:
14883       case MVT::i64:
14884         return std::make_pair(0U, X86::FR64RegisterClass);
14885       // Vector types.
14886       case MVT::v16i8:
14887       case MVT::v8i16:
14888       case MVT::v4i32:
14889       case MVT::v2i64:
14890       case MVT::v4f32:
14891       case MVT::v2f64:
14892         return std::make_pair(0U, X86::VR128RegisterClass);
14893       }
14894       break;
14895     }
14896   }
14897
14898   // Use the default implementation in TargetLowering to convert the register
14899   // constraint into a member of a register class.
14900   std::pair<unsigned, const TargetRegisterClass*> Res;
14901   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14902
14903   // Not found as a standard register?
14904   if (Res.second == 0) {
14905     // Map st(0) -> st(7) -> ST0
14906     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14907         tolower(Constraint[1]) == 's' &&
14908         tolower(Constraint[2]) == 't' &&
14909         Constraint[3] == '(' &&
14910         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14911         Constraint[5] == ')' &&
14912         Constraint[6] == '}') {
14913
14914       Res.first = X86::ST0+Constraint[4]-'0';
14915       Res.second = X86::RFP80RegisterClass;
14916       return Res;
14917     }
14918
14919     // GCC allows "st(0)" to be called just plain "st".
14920     if (StringRef("{st}").equals_lower(Constraint)) {
14921       Res.first = X86::ST0;
14922       Res.second = X86::RFP80RegisterClass;
14923       return Res;
14924     }
14925
14926     // flags -> EFLAGS
14927     if (StringRef("{flags}").equals_lower(Constraint)) {
14928       Res.first = X86::EFLAGS;
14929       Res.second = X86::CCRRegisterClass;
14930       return Res;
14931     }
14932
14933     // 'A' means EAX + EDX.
14934     if (Constraint == "A") {
14935       Res.first = X86::EAX;
14936       Res.second = X86::GR32_ADRegisterClass;
14937       return Res;
14938     }
14939     return Res;
14940   }
14941
14942   // Otherwise, check to see if this is a register class of the wrong value
14943   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14944   // turn into {ax},{dx}.
14945   if (Res.second->hasType(VT))
14946     return Res;   // Correct type already, nothing to do.
14947
14948   // All of the single-register GCC register classes map their values onto
14949   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14950   // really want an 8-bit or 32-bit register, map to the appropriate register
14951   // class and return the appropriate register.
14952   if (Res.second == X86::GR16RegisterClass) {
14953     if (VT == MVT::i8) {
14954       unsigned DestReg = 0;
14955       switch (Res.first) {
14956       default: break;
14957       case X86::AX: DestReg = X86::AL; break;
14958       case X86::DX: DestReg = X86::DL; break;
14959       case X86::CX: DestReg = X86::CL; break;
14960       case X86::BX: DestReg = X86::BL; break;
14961       }
14962       if (DestReg) {
14963         Res.first = DestReg;
14964         Res.second = X86::GR8RegisterClass;
14965       }
14966     } else if (VT == MVT::i32) {
14967       unsigned DestReg = 0;
14968       switch (Res.first) {
14969       default: break;
14970       case X86::AX: DestReg = X86::EAX; break;
14971       case X86::DX: DestReg = X86::EDX; break;
14972       case X86::CX: DestReg = X86::ECX; break;
14973       case X86::BX: DestReg = X86::EBX; break;
14974       case X86::SI: DestReg = X86::ESI; break;
14975       case X86::DI: DestReg = X86::EDI; break;
14976       case X86::BP: DestReg = X86::EBP; break;
14977       case X86::SP: DestReg = X86::ESP; break;
14978       }
14979       if (DestReg) {
14980         Res.first = DestReg;
14981         Res.second = X86::GR32RegisterClass;
14982       }
14983     } else if (VT == MVT::i64) {
14984       unsigned DestReg = 0;
14985       switch (Res.first) {
14986       default: break;
14987       case X86::AX: DestReg = X86::RAX; break;
14988       case X86::DX: DestReg = X86::RDX; break;
14989       case X86::CX: DestReg = X86::RCX; break;
14990       case X86::BX: DestReg = X86::RBX; break;
14991       case X86::SI: DestReg = X86::RSI; break;
14992       case X86::DI: DestReg = X86::RDI; break;
14993       case X86::BP: DestReg = X86::RBP; break;
14994       case X86::SP: DestReg = X86::RSP; break;
14995       }
14996       if (DestReg) {
14997         Res.first = DestReg;
14998         Res.second = X86::GR64RegisterClass;
14999       }
15000     }
15001   } else if (Res.second == X86::FR32RegisterClass ||
15002              Res.second == X86::FR64RegisterClass ||
15003              Res.second == X86::VR128RegisterClass) {
15004     // Handle references to XMM physical registers that got mapped into the
15005     // wrong class.  This can happen with constraints like {xmm0} where the
15006     // target independent register mapper will just pick the first match it can
15007     // find, ignoring the required type.
15008     if (VT == MVT::f32)
15009       Res.second = X86::FR32RegisterClass;
15010     else if (VT == MVT::f64)
15011       Res.second = X86::FR64RegisterClass;
15012     else if (X86::VR128RegisterClass->hasType(VT))
15013       Res.second = X86::VR128RegisterClass;
15014   }
15015
15016   return Res;
15017 }