Enable tail call optimization in the presence of a byval (x86-32 and x86-64).
[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 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference.  Idx is an index in the 128 bits we
80 /// want.  It need not be aligned to a 128-bit bounday.  That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
83                                    SDValue Idx,
84                                    SelectionDAG &DAG,
85                                    DebugLoc dl) {
86   EVT VT = Vec.getValueType();
87   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88
89   EVT ElVT = VT.getVectorElementType();
90
91   int Factor = VT.getSizeInBits() / 128;
92
93   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94                                   ElVT,
95                                   VT.getVectorNumElements() / Factor);
96
97   // Extract from UNDEF is UNDEF.
98   if (Vec.getOpcode() == ISD::UNDEF)
99     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100
101   if (isa<ConstantSDNode>(Idx)) {
102     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103
104     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
105     // we can match to VEXTRACTF128.
106     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107
108     // This is the index of the first element of the 128-bit chunk
109     // we want.
110     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
111                                  * ElemsPerChunk);
112
113     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114
115     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116                                  VecIdx);
117
118     return Result;
119   }
120
121   return SDValue();
122 }
123
124 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference.  Idx is an index in the 128 bits
127 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
130                                   SDValue Vec,
131                                   SDValue Idx,
132                                   SelectionDAG &DAG,
133                                   DebugLoc dl) {
134   if (isa<ConstantSDNode>(Idx)) {
135     EVT VT = Vec.getValueType();
136     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138     EVT ElVT = VT.getVectorElementType();
139
140     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142     EVT ResultVT = Result.getValueType();
143
144     // Insert the relevant 128 bits.
145     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147     // This is the index of the first element of the 128-bit chunk
148     // we want.
149     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                  * ElemsPerChunk);
151
152     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                          VecIdx);
156     return Result;
157   }
158
159   return SDValue();
160 }
161
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164   DebugLoc dl = Lower.getDebugLoc();
165
166   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168   EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                             Lower.getValueType().getVectorElementType(),
170                             Lower.getValueType().getVectorNumElements() * 2);
171
172   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175   // Insert the upper subvector.
176   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                    DAG.getConstant(
178                                      // This is half the length of the result
179                                      // vector.  Start inserting the upper 128
180                                      // bits here.
181                                      Lower.getValueType().getVectorNumElements(),
182                                      MVT::i32),
183                                    DAG, dl);
184
185   // Insert the lower subvector.
186   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187   return Vec;
188 }
189
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192   bool is64Bit = Subtarget->is64Bit();
193
194   if (Subtarget->isTargetEnvMacho()) {
195     if (is64Bit)
196       return new X8664_MachoTargetObjectFile();
197     return new TargetLoweringObjectFileMachO();
198   }
199
200   if (Subtarget->isTargetELF()) {
201     if (is64Bit)
202       return new X8664_ELFTargetObjectFile(TM);
203     return new X8632_ELFTargetObjectFile(TM);
204   }
205   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206     return new TargetLoweringObjectFileCOFF();
207   llvm_unreachable("unknown subtarget type");
208 }
209
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211   : TargetLowering(TM, createTLOF(TM)) {
212   Subtarget = &TM.getSubtarget<X86Subtarget>();
213   X86ScalarSSEf64 = Subtarget->hasXMMInt();
214   X86ScalarSSEf32 = Subtarget->hasXMM();
215   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217   RegInfo = TM.getRegisterInfo();
218   TD = getTargetData();
219
220   // Set up the TargetLowering object.
221   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223   // X86 is weird, it always uses i8 for shift amounts and setcc results.
224   setBooleanContents(ZeroOrOneBooleanContent);
225
226   // For 64-bit since we have so many registers use the ILP scheduler, for
227   // 32-bit code use the register pressure specific scheduling.
228   if (Subtarget->is64Bit())
229     setSchedulingPreference(Sched::ILP);
230   else
231     setSchedulingPreference(Sched::RegPressure);
232   setStackPointerRegisterToSaveRestore(X86StackPtr);
233
234   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235     // Setup Windows compiler runtime calls.
236     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
244   }
245
246   if (Subtarget->isTargetDarwin()) {
247     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248     setUseUnderscoreSetJmp(false);
249     setUseUnderscoreLongJmp(false);
250   } else if (Subtarget->isTargetMingw()) {
251     // MS runtime is weird: it exports _setjmp, but longjmp!
252     setUseUnderscoreSetJmp(true);
253     setUseUnderscoreLongJmp(false);
254   } else {
255     setUseUnderscoreSetJmp(true);
256     setUseUnderscoreLongJmp(true);
257   }
258
259   // Set up the register classes.
260   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263   if (Subtarget->is64Bit())
264     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265
266   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267
268   // We don't accept any truncstore of integer registers.
269   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
275
276   // SETOEQ and SETUNE require checking two conditions.
277   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283
284   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285   // operation.
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
288   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
289
290   if (Subtarget->is64Bit()) {
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
292     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
293   } else if (!UseSoftFloat) {
294     // We have an algorithm for SSE2->double, and we turn this into a
295     // 64-bit FILD followed by conditional FADD for other targets.
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
297     // We have an algorithm for SSE2, and we turn this into a 64-bit
298     // FILD for other targets.
299     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
300   }
301
302   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303   // this operation.
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
305   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
306
307   if (!UseSoftFloat) {
308     // SSE has no i16 to fp conversion, only i32
309     if (X86ScalarSSEf32) {
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
311       // f32 and f64 cases are Legal, f80 case is not
312       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
313     } else {
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
316     }
317   } else {
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
319     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
320   }
321
322   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
323   // are Legal, f80 is custom lowered.
324   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
325   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
326
327   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328   // this operation.
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
330   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
331
332   if (X86ScalarSSEf32) {
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
334     // f32 and f64 cases are Legal, f80 case is not
335     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
336   } else {
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
339   }
340
341   // Handle FP_TO_UINT by promoting the destination to a larger signed
342   // conversion.
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
345   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
346
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
349     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
350   } else if (!UseSoftFloat) {
351     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352       // Expand FP_TO_UINT into a select.
353       // FIXME: We would like to use a Custom expander here eventually to do
354       // the optimal thing for SSE vs. the default expansion in the legalizer.
355       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
356     else
357       // With SSE3 we can use fisttpll to convert to a signed i64; without
358       // SSE, we're stuck with a fistpll.
359       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
360   }
361
362   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363   if (!X86ScalarSSEf64) {
364     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
365     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
366     if (Subtarget->is64Bit()) {
367       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
368       // Without SSE, i64->f64 goes through memory.
369       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
370     }
371   }
372
373   // Scalar integer divide and remainder are lowered to use operations that
374   // produce two results, to match the available instructions. This exposes
375   // the two-result form to trivial CSE, which is able to combine x/y and x%y
376   // into a single instruction.
377   //
378   // Scalar integer multiply-high is also lowered to use two-result
379   // operations, to match the available instructions. However, plain multiply
380   // (low) operations are left as Legal, as there are single-result
381   // instructions for this in x86. Using the two-result multiply instructions
382   // when both high and low results are needed must be arranged by dagcombine.
383   for (unsigned i = 0, e = 4; i != e; ++i) {
384     MVT VT = IntVTs[i];
385     setOperationAction(ISD::MULHS, VT, Expand);
386     setOperationAction(ISD::MULHU, VT, Expand);
387     setOperationAction(ISD::SDIV, VT, Expand);
388     setOperationAction(ISD::UDIV, VT, Expand);
389     setOperationAction(ISD::SREM, VT, Expand);
390     setOperationAction(ISD::UREM, VT, Expand);
391
392     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393     setOperationAction(ISD::ADDC, VT, Custom);
394     setOperationAction(ISD::ADDE, VT, Custom);
395     setOperationAction(ISD::SUBC, VT, Custom);
396     setOperationAction(ISD::SUBE, VT, Custom);
397   }
398
399   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
400   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
401   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
408   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
412   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
413
414   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
416   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
418   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
419   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
420   if (Subtarget->is64Bit()) {
421     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
422     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
423   }
424
425   if (Subtarget->hasPOPCNT()) {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
427   } else {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
433   }
434
435   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
436   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
437
438   // These should be promoted to a larger select which is supported.
439   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
440   // X86 wants to expand cmov itself.
441   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
455     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
456   }
457   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
458
459   // Darwin ABI issue.
460   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
461   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
463   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
464   if (Subtarget->is64Bit())
465     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
467   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
470     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
471     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
472     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
473     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
474   }
475   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
478   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
479   if (Subtarget->is64Bit()) {
480     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
482     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
483   }
484
485   if (Subtarget->hasXMM())
486     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
487
488   // We may not have a libcall for MEMBARRIER so we should lower this.
489   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
490
491   // On X86 and X86-64, atomic operations are lowered to locked instructions.
492   // Locked instructions, in turn, have implicit fence semantics (all memory
493   // operations are flushed before issuing the locked instruction, and they
494   // are not buffered), so we can fold away the common pattern of
495   // fence-atomic-fence.
496   setShouldFoldAtomicFences(true);
497
498   // Expand certain atomics
499   for (unsigned i = 0, e = 4; i != e; ++i) {
500     MVT VT = IntVTs[i];
501     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
503   }
504
505   if (!Subtarget->is64Bit()) {
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   // FIXME - use subtarget debug flags
516   if (!Subtarget->isTargetDarwin() &&
517       !Subtarget->isTargetELF() &&
518       !Subtarget->isTargetCygMing()) {
519     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526   if (Subtarget->is64Bit()) {
527     setExceptionPointerRegister(X86::RAX);
528     setExceptionSelectorRegister(X86::RDX);
529   } else {
530     setExceptionPointerRegister(X86::EAX);
531     setExceptionSelectorRegister(X86::EDX);
532   }
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539
540   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   if (Subtarget->is64Bit()) {
544     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
545     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
546   } else {
547     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
548     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
549   }
550
551   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
552   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
553   setOperationAction(ISD::DYNAMIC_STACKALLOC,
554                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555                      (Subtarget->isTargetCOFF()
556                       && !Subtarget->isTargetEnvMacho()
557                       ? Custom : Expand));
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // Lower this to FGETSIGNx86 plus an AND.
578     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
579     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
580
581     // We don't support sin/cos/fmod
582     setOperationAction(ISD::FSIN , MVT::f64, Expand);
583     setOperationAction(ISD::FCOS , MVT::f64, Expand);
584     setOperationAction(ISD::FSIN , MVT::f32, Expand);
585     setOperationAction(ISD::FCOS , MVT::f32, Expand);
586
587     // Expand FP immediates into loads from the stack, except for the special
588     // cases we handle.
589     addLegalFPImmediate(APFloat(+0.0)); // xorpd
590     addLegalFPImmediate(APFloat(+0.0f)); // xorps
591   } else if (!UseSoftFloat && X86ScalarSSEf32) {
592     // Use SSE for f32, x87 for f64.
593     // Set up the FP register classes.
594     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
595     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
596
597     // Use ANDPS to simulate FABS.
598     setOperationAction(ISD::FABS , MVT::f32, Custom);
599
600     // Use XORP to simulate FNEG.
601     setOperationAction(ISD::FNEG , MVT::f32, Custom);
602
603     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
604
605     // Use ANDPS and ORPS to simulate FCOPYSIGN.
606     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
607     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
608
609     // We don't support sin/cos/fmod
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Special cases we handle for FP constants.
614     addLegalFPImmediate(APFloat(+0.0f)); // xorps
615     addLegalFPImmediate(APFloat(+0.0)); // FLD0
616     addLegalFPImmediate(APFloat(+1.0)); // FLD1
617     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619
620     if (!UnsafeFPMath) {
621       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
622       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
623     }
624   } else if (!UseSoftFloat) {
625     // f32 and f64 in x87.
626     // Set up the FP register classes.
627     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
628     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
634
635     if (!UnsafeFPMath) {
636       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
637       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
638     }
639     addLegalFPImmediate(APFloat(+0.0)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
643     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
647   }
648
649   // Long double always uses X87.
650   if (!UseSoftFloat) {
651     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
652     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
653     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
654     {
655       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
656       addLegalFPImmediate(TmpFlt);  // FLD0
657       TmpFlt.changeSign();
658       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
659
660       bool ignored;
661       APFloat TmpFlt2(+1.0);
662       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
663                       &ignored);
664       addLegalFPImmediate(TmpFlt2);  // FLD1
665       TmpFlt2.changeSign();
666       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
667     }
668
669     if (!UnsafeFPMath) {
670       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
671       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
672     }
673   }
674
675   // Always use a library call for pow.
676   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
677   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
679
680   setOperationAction(ISD::FLOG, MVT::f80, Expand);
681   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
683   setOperationAction(ISD::FEXP, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
685
686   // First set operation action for all vector types to either promote
687   // (for widening) or expand (for scalarization). Then we will selectively
688   // turn on ones that can be effectively codegen'd.
689   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
690        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
691     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
706     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
708     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
741     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
746          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
747       setTruncStoreAction((MVT::SimpleValueType)VT,
748                           (MVT::SimpleValueType)InnerVT, Expand);
749     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
750     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
752   }
753
754   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
755   // with -msoft-float, disable use of MMX as well.
756   if (!UseSoftFloat && Subtarget->hasMMX()) {
757     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
758     // No operations on x86mmx supported, everything uses intrinsics.
759   }
760
761   // MMX-sized vectors (other than x86mmx) are expected to be expanded
762   // into smaller operations.
763   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
764   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
765   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
767   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
768   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
769   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
770   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
771   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
772   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
773   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
774   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
775   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
776   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
777   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
778   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
779   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
783   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
784   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
785   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
786   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
788   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
792
793   if (!UseSoftFloat && Subtarget->hasXMM()) {
794     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
795
796     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
801     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
802     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
803     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
804     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
805     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
807     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
808   }
809
810   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
811     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
812
813     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
814     // registers cannot be used even for integer operations.
815     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
816     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
819
820     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
821     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
822     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
823     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
825     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
826     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
827     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
828     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
829     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
830     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
831     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
835     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
836
837     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
838     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
841
842     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
847
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
853
854     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
856       EVT VT = (MVT::SimpleValueType)i;
857       // Do not attempt to custom lower non-power-of-2 vectors
858       if (!isPowerOf2_32(VT.getVectorNumElements()))
859         continue;
860       // Do not attempt to custom lower non-128-bit vectors
861       if (!VT.is128BitVector())
862         continue;
863       setOperationAction(ISD::BUILD_VECTOR,
864                          VT.getSimpleVT().SimpleTy, Custom);
865       setOperationAction(ISD::VECTOR_SHUFFLE,
866                          VT.getSimpleVT().SimpleTy, Custom);
867       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
868                          VT.getSimpleVT().SimpleTy, Custom);
869     }
870
871     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
873     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
876     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
877
878     if (Subtarget->is64Bit()) {
879       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
880       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
881     }
882
883     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
884     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
885       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
886       EVT VT = SVT;
887
888       // Do not attempt to promote non-128-bit vectors
889       if (!VT.is128BitVector())
890         continue;
891
892       setOperationAction(ISD::AND,    SVT, Promote);
893       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
894       setOperationAction(ISD::OR,     SVT, Promote);
895       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
896       setOperationAction(ISD::XOR,    SVT, Promote);
897       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
898       setOperationAction(ISD::LOAD,   SVT, Promote);
899       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
900       setOperationAction(ISD::SELECT, SVT, Promote);
901       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
902     }
903
904     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914   }
915
916   if (Subtarget->hasSSE41()) {
917     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
922     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
923     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
924     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
925     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
926     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
927
928     // FIXME: Do we need to handle scalar-to-vector here?
929     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
930
931     // Can turn SHL into an integer multiply.
932     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
933     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
934
935     // i8 and i16 vectors are custom , because the source register and source
936     // source memory operand types are not the same width.  f32 vectors are
937     // custom since the immediate controlling the insert encodes additional
938     // information.
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
943
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
948
949     if (Subtarget->is64Bit()) {
950       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
951       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
952     }
953   }
954
955   if (Subtarget->hasSSE2()) {
956     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
957     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
959
960     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
961     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
962     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
963
964     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
966   }
967
968   if (Subtarget->hasSSE42())
969     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
970
971   if (!UseSoftFloat && Subtarget->hasAVX()) {
972     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
973     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
974     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
976     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
977
978     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
979     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
982
983     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
989
990     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
995     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
996
997     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
998     // insert_vector_elt extract_subvector and extract_vector_elt for
999     // 256-bit types.
1000     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1002          ++i) {
1003       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1004       // Do not attempt to custom lower non-256-bit vectors
1005       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1006           || (MVT(VT).getSizeInBits() < 256))
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1013     }
1014     // Custom-lower insert_subvector and extract_subvector based on
1015     // the result type.
1016     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1017          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1018          ++i) {
1019       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1020       // Do not attempt to custom lower non-256-bit vectors
1021       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1022         continue;
1023
1024       if (MVT(VT).getSizeInBits() == 128) {
1025         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1026       }
1027       else if (MVT(VT).getSizeInBits() == 256) {
1028         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1029       }
1030     }
1031
1032     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1033     // Don't promote loads because we need them for VPERM vector index versions.
1034
1035     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1036          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1037          VT++) {
1038       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1039           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1040         continue;
1041       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1042       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1043       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1044       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1045       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1046       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1047       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1048       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1049       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1050       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1051     }
1052   }
1053
1054   // We want to custom lower some of our intrinsics.
1055   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1056
1057
1058   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1059   // handle type legalization for these operations here.
1060   //
1061   // FIXME: We really should do custom legalization for addition and
1062   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1063   // than generic legalization for 64-bit multiplication-with-overflow, though.
1064   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1065     // Add/Sub/Mul with overflow operations are custom lowered.
1066     MVT VT = IntVTs[i];
1067     setOperationAction(ISD::SADDO, VT, Custom);
1068     setOperationAction(ISD::UADDO, VT, Custom);
1069     setOperationAction(ISD::SSUBO, VT, Custom);
1070     setOperationAction(ISD::USUBO, VT, Custom);
1071     setOperationAction(ISD::SMULO, VT, Custom);
1072     setOperationAction(ISD::UMULO, VT, Custom);
1073   }
1074
1075   // There are no 8-bit 3-address imul/mul instructions
1076   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1077   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1078
1079   if (!Subtarget->is64Bit()) {
1080     // These libcalls are not available in 32-bit.
1081     setLibcallName(RTLIB::SHL_I128, 0);
1082     setLibcallName(RTLIB::SRL_I128, 0);
1083     setLibcallName(RTLIB::SRA_I128, 0);
1084   }
1085
1086   // We have target-specific dag combine patterns for the following nodes:
1087   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1088   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1089   setTargetDAGCombine(ISD::BUILD_VECTOR);
1090   setTargetDAGCombine(ISD::SELECT);
1091   setTargetDAGCombine(ISD::SHL);
1092   setTargetDAGCombine(ISD::SRA);
1093   setTargetDAGCombine(ISD::SRL);
1094   setTargetDAGCombine(ISD::OR);
1095   setTargetDAGCombine(ISD::AND);
1096   setTargetDAGCombine(ISD::ADD);
1097   setTargetDAGCombine(ISD::SUB);
1098   setTargetDAGCombine(ISD::STORE);
1099   setTargetDAGCombine(ISD::ZERO_EXTEND);
1100   setTargetDAGCombine(ISD::SINT_TO_FP);
1101   if (Subtarget->is64Bit())
1102     setTargetDAGCombine(ISD::MUL);
1103
1104   computeRegisterProperties();
1105
1106   // On Darwin, -Os means optimize for size without hurting performance,
1107   // do not reduce the limit.
1108   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1109   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1110   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1111   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1112   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1113   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1114   setPrefLoopAlignment(16);
1115   benefitFromCodePlacementOpt = true;
1116
1117   setPrefFunctionAlignment(4);
1118 }
1119
1120
1121 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1122   return MVT::i8;
1123 }
1124
1125
1126 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1127 /// the desired ByVal argument alignment.
1128 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1129   if (MaxAlign == 16)
1130     return;
1131   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1132     if (VTy->getBitWidth() == 128)
1133       MaxAlign = 16;
1134   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1135     unsigned EltAlign = 0;
1136     getMaxByValAlign(ATy->getElementType(), EltAlign);
1137     if (EltAlign > MaxAlign)
1138       MaxAlign = EltAlign;
1139   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1140     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1141       unsigned EltAlign = 0;
1142       getMaxByValAlign(STy->getElementType(i), EltAlign);
1143       if (EltAlign > MaxAlign)
1144         MaxAlign = EltAlign;
1145       if (MaxAlign == 16)
1146         break;
1147     }
1148   }
1149   return;
1150 }
1151
1152 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1153 /// function arguments in the caller parameter area. For X86, aggregates
1154 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1155 /// are at 4-byte boundaries.
1156 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1157   if (Subtarget->is64Bit()) {
1158     // Max of 8 and alignment of type.
1159     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1160     if (TyAlign > 8)
1161       return TyAlign;
1162     return 8;
1163   }
1164
1165   unsigned Align = 4;
1166   if (Subtarget->hasXMM())
1167     getMaxByValAlign(Ty, Align);
1168   return Align;
1169 }
1170
1171 /// getOptimalMemOpType - Returns the target specific optimal type for load
1172 /// and store operations as a result of memset, memcpy, and memmove
1173 /// lowering. If DstAlign is zero that means it's safe to destination
1174 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1175 /// means there isn't a need to check it against alignment requirement,
1176 /// probably because the source does not need to be loaded. If
1177 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1178 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1179 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1180 /// constant so it does not need to be loaded.
1181 /// It returns EVT::Other if the type should be determined using generic
1182 /// target-independent logic.
1183 EVT
1184 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1185                                        unsigned DstAlign, unsigned SrcAlign,
1186                                        bool NonScalarIntSafe,
1187                                        bool MemcpyStrSrc,
1188                                        MachineFunction &MF) const {
1189   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1190   // linux.  This is because the stack realignment code can't handle certain
1191   // cases like PR2962.  This should be removed when PR2962 is fixed.
1192   const Function *F = MF.getFunction();
1193   if (NonScalarIntSafe &&
1194       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1195     if (Size >= 16 &&
1196         (Subtarget->isUnalignedMemAccessFast() ||
1197          ((DstAlign == 0 || DstAlign >= 16) &&
1198           (SrcAlign == 0 || SrcAlign >= 16))) &&
1199         Subtarget->getStackAlignment() >= 16) {
1200       if (Subtarget->hasSSE2())
1201         return MVT::v4i32;
1202       if (Subtarget->hasSSE1())
1203         return MVT::v4f32;
1204     } else if (!MemcpyStrSrc && Size >= 8 &&
1205                !Subtarget->is64Bit() &&
1206                Subtarget->getStackAlignment() >= 8 &&
1207                Subtarget->hasXMMInt()) {
1208       // Do not use f64 to lower memcpy if source is string constant. It's
1209       // better to use i32 to avoid the loads.
1210       return MVT::f64;
1211     }
1212   }
1213   if (Subtarget->is64Bit() && Size >= 8)
1214     return MVT::i64;
1215   return MVT::i32;
1216 }
1217
1218 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1219 /// current function.  The returned value is a member of the
1220 /// MachineJumpTableInfo::JTEntryKind enum.
1221 unsigned X86TargetLowering::getJumpTableEncoding() const {
1222   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1223   // symbol.
1224   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1225       Subtarget->isPICStyleGOT())
1226     return MachineJumpTableInfo::EK_Custom32;
1227
1228   // Otherwise, use the normal jump table encoding heuristics.
1229   return TargetLowering::getJumpTableEncoding();
1230 }
1231
1232 const MCExpr *
1233 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1234                                              const MachineBasicBlock *MBB,
1235                                              unsigned uid,MCContext &Ctx) const{
1236   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1237          Subtarget->isPICStyleGOT());
1238   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1239   // entries.
1240   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1241                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1242 }
1243
1244 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1245 /// jumptable.
1246 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1247                                                     SelectionDAG &DAG) const {
1248   if (!Subtarget->is64Bit())
1249     // This doesn't have DebugLoc associated with it, but is not really the
1250     // same as a Register.
1251     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1252   return Table;
1253 }
1254
1255 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1256 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1257 /// MCExpr.
1258 const MCExpr *X86TargetLowering::
1259 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1260                              MCContext &Ctx) const {
1261   // X86-64 uses RIP relative addressing based on the jump table label.
1262   if (Subtarget->isPICStyleRIPRel())
1263     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1264
1265   // Otherwise, the reference is relative to the PIC base.
1266   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1267 }
1268
1269 // FIXME: Why this routine is here? Move to RegInfo!
1270 std::pair<const TargetRegisterClass*, uint8_t>
1271 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1272   const TargetRegisterClass *RRC = 0;
1273   uint8_t Cost = 1;
1274   switch (VT.getSimpleVT().SimpleTy) {
1275   default:
1276     return TargetLowering::findRepresentativeClass(VT);
1277   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1278     RRC = (Subtarget->is64Bit()
1279            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1280     break;
1281   case MVT::x86mmx:
1282     RRC = X86::VR64RegisterClass;
1283     break;
1284   case MVT::f32: case MVT::f64:
1285   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1286   case MVT::v4f32: case MVT::v2f64:
1287   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1288   case MVT::v4f64:
1289     RRC = X86::VR128RegisterClass;
1290     break;
1291   }
1292   return std::make_pair(RRC, Cost);
1293 }
1294
1295 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1296                                                unsigned &Offset) const {
1297   if (!Subtarget->isTargetLinux())
1298     return false;
1299
1300   if (Subtarget->is64Bit()) {
1301     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1302     Offset = 0x28;
1303     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1304       AddressSpace = 256;
1305     else
1306       AddressSpace = 257;
1307   } else {
1308     // %gs:0x14 on i386
1309     Offset = 0x14;
1310     AddressSpace = 256;
1311   }
1312   return true;
1313 }
1314
1315
1316 //===----------------------------------------------------------------------===//
1317 //               Return Value Calling Convention Implementation
1318 //===----------------------------------------------------------------------===//
1319
1320 #include "X86GenCallingConv.inc"
1321
1322 bool
1323 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1324                                   MachineFunction &MF, bool isVarArg,
1325                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1326                         LLVMContext &Context) const {
1327   SmallVector<CCValAssign, 16> RVLocs;
1328   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1329                  RVLocs, Context);
1330   return CCInfo.CheckReturn(Outs, RetCC_X86);
1331 }
1332
1333 SDValue
1334 X86TargetLowering::LowerReturn(SDValue Chain,
1335                                CallingConv::ID CallConv, bool isVarArg,
1336                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1337                                const SmallVectorImpl<SDValue> &OutVals,
1338                                DebugLoc dl, SelectionDAG &DAG) const {
1339   MachineFunction &MF = DAG.getMachineFunction();
1340   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1341
1342   SmallVector<CCValAssign, 16> RVLocs;
1343   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1344                  RVLocs, *DAG.getContext());
1345   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1346
1347   // Add the regs to the liveout set for the function.
1348   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1349   for (unsigned i = 0; i != RVLocs.size(); ++i)
1350     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1351       MRI.addLiveOut(RVLocs[i].getLocReg());
1352
1353   SDValue Flag;
1354
1355   SmallVector<SDValue, 6> RetOps;
1356   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1357   // Operand #1 = Bytes To Pop
1358   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1359                    MVT::i16));
1360
1361   // Copy the result values into the output registers.
1362   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1363     CCValAssign &VA = RVLocs[i];
1364     assert(VA.isRegLoc() && "Can only return in registers!");
1365     SDValue ValToCopy = OutVals[i];
1366     EVT ValVT = ValToCopy.getValueType();
1367
1368     // If this is x86-64, and we disabled SSE, we can't return FP values,
1369     // or SSE or MMX vectors.
1370     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1371          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1372           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1373       report_fatal_error("SSE register return with SSE disabled");
1374     }
1375     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1376     // llvm-gcc has never done it right and no one has noticed, so this
1377     // should be OK for now.
1378     if (ValVT == MVT::f64 &&
1379         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1380       report_fatal_error("SSE2 register return with SSE2 disabled");
1381
1382     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1383     // the RET instruction and handled by the FP Stackifier.
1384     if (VA.getLocReg() == X86::ST0 ||
1385         VA.getLocReg() == X86::ST1) {
1386       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1387       // change the value to the FP stack register class.
1388       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1389         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1390       RetOps.push_back(ValToCopy);
1391       // Don't emit a copytoreg.
1392       continue;
1393     }
1394
1395     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1396     // which is returned in RAX / RDX.
1397     if (Subtarget->is64Bit()) {
1398       if (ValVT == MVT::x86mmx) {
1399         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1400           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1401           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1402                                   ValToCopy);
1403           // If we don't have SSE2 available, convert to v4f32 so the generated
1404           // register is legal.
1405           if (!Subtarget->hasSSE2())
1406             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1407         }
1408       }
1409     }
1410
1411     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1412     Flag = Chain.getValue(1);
1413   }
1414
1415   // The x86-64 ABI for returning structs by value requires that we copy
1416   // the sret argument into %rax for the return. We saved the argument into
1417   // a virtual register in the entry block, so now we copy the value out
1418   // and into %rax.
1419   if (Subtarget->is64Bit() &&
1420       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1421     MachineFunction &MF = DAG.getMachineFunction();
1422     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1423     unsigned Reg = FuncInfo->getSRetReturnReg();
1424     assert(Reg &&
1425            "SRetReturnReg should have been set in LowerFormalArguments().");
1426     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1427
1428     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1429     Flag = Chain.getValue(1);
1430
1431     // RAX now acts like a return value.
1432     MRI.addLiveOut(X86::RAX);
1433   }
1434
1435   RetOps[0] = Chain;  // Update chain.
1436
1437   // Add the flag if we have it.
1438   if (Flag.getNode())
1439     RetOps.push_back(Flag);
1440
1441   return DAG.getNode(X86ISD::RET_FLAG, dl,
1442                      MVT::Other, &RetOps[0], RetOps.size());
1443 }
1444
1445 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1446   if (N->getNumValues() != 1)
1447     return false;
1448   if (!N->hasNUsesOfValue(1, 0))
1449     return false;
1450
1451   SDNode *Copy = *N->use_begin();
1452   if (Copy->getOpcode() != ISD::CopyToReg &&
1453       Copy->getOpcode() != ISD::FP_EXTEND)
1454     return false;
1455
1456   bool HasRet = false;
1457   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1458        UI != UE; ++UI) {
1459     if (UI->getOpcode() != X86ISD::RET_FLAG)
1460       return false;
1461     HasRet = true;
1462   }
1463
1464   return HasRet;
1465 }
1466
1467 EVT
1468 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1469                                             ISD::NodeType ExtendKind) const {
1470   MVT ReturnMVT;
1471   // TODO: Is this also valid on 32-bit?
1472   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1473     ReturnMVT = MVT::i8;
1474   else
1475     ReturnMVT = MVT::i32;
1476
1477   EVT MinVT = getRegisterType(Context, ReturnMVT);
1478   return VT.bitsLT(MinVT) ? MinVT : VT;
1479 }
1480
1481 /// LowerCallResult - Lower the result values of a call into the
1482 /// appropriate copies out of appropriate physical registers.
1483 ///
1484 SDValue
1485 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1486                                    CallingConv::ID CallConv, bool isVarArg,
1487                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1488                                    DebugLoc dl, SelectionDAG &DAG,
1489                                    SmallVectorImpl<SDValue> &InVals) const {
1490
1491   // Assign locations to each value returned by this call.
1492   SmallVector<CCValAssign, 16> RVLocs;
1493   bool Is64Bit = Subtarget->is64Bit();
1494   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1495                  getTargetMachine(), RVLocs, *DAG.getContext());
1496   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1497
1498   // Copy all of the result registers out of their specified physreg.
1499   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1500     CCValAssign &VA = RVLocs[i];
1501     EVT CopyVT = VA.getValVT();
1502
1503     // If this is x86-64, and we disabled SSE, we can't return FP values
1504     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1505         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1506       report_fatal_error("SSE register return with SSE disabled");
1507     }
1508
1509     SDValue Val;
1510
1511     // If this is a call to a function that returns an fp value on the floating
1512     // point stack, we must guarantee the the value is popped from the stack, so
1513     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1514     // if the return value is not used. We use the FpGET_ST0 instructions
1515     // instead.
1516     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1517       // If we prefer to use the value in xmm registers, copy it out as f80 and
1518       // use a truncate to move it from fp stack reg to xmm reg.
1519       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1520       bool isST0 = VA.getLocReg() == X86::ST0;
1521       unsigned Opc = 0;
1522       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1523       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1524       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1525       SDValue Ops[] = { Chain, InFlag };
1526       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1527                                          Ops, 2), 1);
1528       Val = Chain.getValue(0);
1529
1530       // Round the f80 to the right size, which also moves it to the appropriate
1531       // xmm register.
1532       if (CopyVT != VA.getValVT())
1533         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1534                           // This truncation won't change the value.
1535                           DAG.getIntPtrConstant(1));
1536     } else {
1537       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1538                                  CopyVT, InFlag).getValue(1);
1539       Val = Chain.getValue(0);
1540     }
1541     InFlag = Chain.getValue(2);
1542     InVals.push_back(Val);
1543   }
1544
1545   return Chain;
1546 }
1547
1548
1549 //===----------------------------------------------------------------------===//
1550 //                C & StdCall & Fast Calling Convention implementation
1551 //===----------------------------------------------------------------------===//
1552 //  StdCall calling convention seems to be standard for many Windows' API
1553 //  routines and around. It differs from C calling convention just a little:
1554 //  callee should clean up the stack, not caller. Symbols should be also
1555 //  decorated in some fancy way :) It doesn't support any vector arguments.
1556 //  For info on fast calling convention see Fast Calling Convention (tail call)
1557 //  implementation LowerX86_32FastCCCallTo.
1558
1559 /// CallIsStructReturn - Determines whether a call uses struct return
1560 /// semantics.
1561 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1562   if (Outs.empty())
1563     return false;
1564
1565   return Outs[0].Flags.isSRet();
1566 }
1567
1568 /// ArgsAreStructReturn - Determines whether a function uses struct
1569 /// return semantics.
1570 static bool
1571 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1572   if (Ins.empty())
1573     return false;
1574
1575   return Ins[0].Flags.isSRet();
1576 }
1577
1578 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1579 /// by "Src" to address "Dst" with size and alignment information specified by
1580 /// the specific parameter attribute. The copy will be passed as a byval
1581 /// function parameter.
1582 static SDValue
1583 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1584                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1585                           DebugLoc dl) {
1586   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1587
1588   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1589                        /*isVolatile*/false, /*AlwaysInline=*/true,
1590                        MachinePointerInfo(), MachinePointerInfo());
1591 }
1592
1593 /// IsTailCallConvention - Return true if the calling convention is one that
1594 /// supports tail call optimization.
1595 static bool IsTailCallConvention(CallingConv::ID CC) {
1596   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1597 }
1598
1599 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1600   if (!CI->isTailCall())
1601     return false;
1602
1603   CallSite CS(CI);
1604   CallingConv::ID CalleeCC = CS.getCallingConv();
1605   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1606     return false;
1607
1608   return true;
1609 }
1610
1611 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1612 /// a tailcall target by changing its ABI.
1613 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1614   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1615 }
1616
1617 SDValue
1618 X86TargetLowering::LowerMemArgument(SDValue Chain,
1619                                     CallingConv::ID CallConv,
1620                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1621                                     DebugLoc dl, SelectionDAG &DAG,
1622                                     const CCValAssign &VA,
1623                                     MachineFrameInfo *MFI,
1624                                     unsigned i) const {
1625   // Create the nodes corresponding to a load from this parameter slot.
1626   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1627   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1628   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1629   EVT ValVT;
1630
1631   // If value is passed by pointer we have address passed instead of the value
1632   // itself.
1633   if (VA.getLocInfo() == CCValAssign::Indirect)
1634     ValVT = VA.getLocVT();
1635   else
1636     ValVT = VA.getValVT();
1637
1638   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1639   // changed with more analysis.
1640   // In case of tail call optimization mark all arguments mutable. Since they
1641   // could be overwritten by lowering of arguments in case of a tail call.
1642   if (Flags.isByVal()) {
1643     unsigned Bytes = Flags.getByValSize();
1644     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1645     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1646     return DAG.getFrameIndex(FI, getPointerTy());
1647   } else {
1648     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1649                                     VA.getLocMemOffset(), isImmutable);
1650     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1651     return DAG.getLoad(ValVT, dl, Chain, FIN,
1652                        MachinePointerInfo::getFixedStack(FI),
1653                        false, false, 0);
1654   }
1655 }
1656
1657 SDValue
1658 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1659                                         CallingConv::ID CallConv,
1660                                         bool isVarArg,
1661                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1662                                         DebugLoc dl,
1663                                         SelectionDAG &DAG,
1664                                         SmallVectorImpl<SDValue> &InVals)
1665                                           const {
1666   MachineFunction &MF = DAG.getMachineFunction();
1667   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1668
1669   const Function* Fn = MF.getFunction();
1670   if (Fn->hasExternalLinkage() &&
1671       Subtarget->isTargetCygMing() &&
1672       Fn->getName() == "main")
1673     FuncInfo->setForceFramePointer(true);
1674
1675   MachineFrameInfo *MFI = MF.getFrameInfo();
1676   bool Is64Bit = Subtarget->is64Bit();
1677   bool IsWin64 = Subtarget->isTargetWin64();
1678
1679   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1680          "Var args not supported with calling convention fastcc or ghc");
1681
1682   // Assign locations to all of the incoming arguments.
1683   SmallVector<CCValAssign, 16> ArgLocs;
1684   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1685                  ArgLocs, *DAG.getContext());
1686
1687   // Allocate shadow area for Win64
1688   if (IsWin64) {
1689     CCInfo.AllocateStack(32, 8);
1690   }
1691
1692   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1693
1694   unsigned LastVal = ~0U;
1695   SDValue ArgValue;
1696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1697     CCValAssign &VA = ArgLocs[i];
1698     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1699     // places.
1700     assert(VA.getValNo() != LastVal &&
1701            "Don't support value assigned to multiple locs yet");
1702     LastVal = VA.getValNo();
1703
1704     if (VA.isRegLoc()) {
1705       EVT RegVT = VA.getLocVT();
1706       TargetRegisterClass *RC = NULL;
1707       if (RegVT == MVT::i32)
1708         RC = X86::GR32RegisterClass;
1709       else if (Is64Bit && RegVT == MVT::i64)
1710         RC = X86::GR64RegisterClass;
1711       else if (RegVT == MVT::f32)
1712         RC = X86::FR32RegisterClass;
1713       else if (RegVT == MVT::f64)
1714         RC = X86::FR64RegisterClass;
1715       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1716         RC = X86::VR256RegisterClass;
1717       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1718         RC = X86::VR128RegisterClass;
1719       else if (RegVT == MVT::x86mmx)
1720         RC = X86::VR64RegisterClass;
1721       else
1722         llvm_unreachable("Unknown argument type!");
1723
1724       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1725       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1726
1727       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1728       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1729       // right size.
1730       if (VA.getLocInfo() == CCValAssign::SExt)
1731         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1732                                DAG.getValueType(VA.getValVT()));
1733       else if (VA.getLocInfo() == CCValAssign::ZExt)
1734         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1735                                DAG.getValueType(VA.getValVT()));
1736       else if (VA.getLocInfo() == CCValAssign::BCvt)
1737         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1738
1739       if (VA.isExtInLoc()) {
1740         // Handle MMX values passed in XMM regs.
1741         if (RegVT.isVector()) {
1742           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1743                                  ArgValue);
1744         } else
1745           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1746       }
1747     } else {
1748       assert(VA.isMemLoc());
1749       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1750     }
1751
1752     // If value is passed via pointer - do a load.
1753     if (VA.getLocInfo() == CCValAssign::Indirect)
1754       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1755                              MachinePointerInfo(), false, false, 0);
1756
1757     InVals.push_back(ArgValue);
1758   }
1759
1760   // The x86-64 ABI for returning structs by value requires that we copy
1761   // the sret argument into %rax for the return. Save the argument into
1762   // a virtual register so that we can access it from the return points.
1763   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1764     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1765     unsigned Reg = FuncInfo->getSRetReturnReg();
1766     if (!Reg) {
1767       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1768       FuncInfo->setSRetReturnReg(Reg);
1769     }
1770     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1771     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1772   }
1773
1774   unsigned StackSize = CCInfo.getNextStackOffset();
1775   // Align stack specially for tail calls.
1776   if (FuncIsMadeTailCallSafe(CallConv))
1777     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1778
1779   // If the function takes variable number of arguments, make a frame index for
1780   // the start of the first vararg value... for expansion of llvm.va_start.
1781   if (isVarArg) {
1782     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1783                     CallConv != CallingConv::X86_ThisCall)) {
1784       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1785     }
1786     if (Is64Bit) {
1787       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1788
1789       // FIXME: We should really autogenerate these arrays
1790       static const unsigned GPR64ArgRegsWin64[] = {
1791         X86::RCX, X86::RDX, X86::R8,  X86::R9
1792       };
1793       static const unsigned GPR64ArgRegs64Bit[] = {
1794         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1795       };
1796       static const unsigned XMMArgRegs64Bit[] = {
1797         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1798         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1799       };
1800       const unsigned *GPR64ArgRegs;
1801       unsigned NumXMMRegs = 0;
1802
1803       if (IsWin64) {
1804         // The XMM registers which might contain var arg parameters are shadowed
1805         // in their paired GPR.  So we only need to save the GPR to their home
1806         // slots.
1807         TotalNumIntRegs = 4;
1808         GPR64ArgRegs = GPR64ArgRegsWin64;
1809       } else {
1810         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1811         GPR64ArgRegs = GPR64ArgRegs64Bit;
1812
1813         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1814       }
1815       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1816                                                        TotalNumIntRegs);
1817
1818       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1819       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1820              "SSE register cannot be used when SSE is disabled!");
1821       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1822              "SSE register cannot be used when SSE is disabled!");
1823       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1824         // Kernel mode asks for SSE to be disabled, so don't push them
1825         // on the stack.
1826         TotalNumXMMRegs = 0;
1827
1828       if (IsWin64) {
1829         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1830         // Get to the caller-allocated home save location.  Add 8 to account
1831         // for the return address.
1832         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1833         FuncInfo->setRegSaveFrameIndex(
1834           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1835         // Fixup to set vararg frame on shadow area (4 x i64).
1836         if (NumIntRegs < 4)
1837           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1838       } else {
1839         // For X86-64, if there are vararg parameters that are passed via
1840         // registers, then we must store them to their spots on the stack so they
1841         // may be loaded by deferencing the result of va_next.
1842         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1843         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1844         FuncInfo->setRegSaveFrameIndex(
1845           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1846                                false));
1847       }
1848
1849       // Store the integer parameter registers.
1850       SmallVector<SDValue, 8> MemOps;
1851       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1852                                         getPointerTy());
1853       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1854       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1855         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1856                                   DAG.getIntPtrConstant(Offset));
1857         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1858                                      X86::GR64RegisterClass);
1859         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1860         SDValue Store =
1861           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1862                        MachinePointerInfo::getFixedStack(
1863                          FuncInfo->getRegSaveFrameIndex(), Offset),
1864                        false, false, 0);
1865         MemOps.push_back(Store);
1866         Offset += 8;
1867       }
1868
1869       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1870         // Now store the XMM (fp + vector) parameter registers.
1871         SmallVector<SDValue, 11> SaveXMMOps;
1872         SaveXMMOps.push_back(Chain);
1873
1874         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1875         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1876         SaveXMMOps.push_back(ALVal);
1877
1878         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1879                                FuncInfo->getRegSaveFrameIndex()));
1880         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1881                                FuncInfo->getVarArgsFPOffset()));
1882
1883         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1884           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1885                                        X86::VR128RegisterClass);
1886           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1887           SaveXMMOps.push_back(Val);
1888         }
1889         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1890                                      MVT::Other,
1891                                      &SaveXMMOps[0], SaveXMMOps.size()));
1892       }
1893
1894       if (!MemOps.empty())
1895         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1896                             &MemOps[0], MemOps.size());
1897     }
1898   }
1899
1900   // Some CCs need callee pop.
1901   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1902     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1903   } else {
1904     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1905     // If this is an sret function, the return should pop the hidden pointer.
1906     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1907       FuncInfo->setBytesToPopOnReturn(4);
1908   }
1909
1910   if (!Is64Bit) {
1911     // RegSaveFrameIndex is X86-64 only.
1912     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1913     if (CallConv == CallingConv::X86_FastCall ||
1914         CallConv == CallingConv::X86_ThisCall)
1915       // fastcc functions can't have varargs.
1916       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1917   }
1918
1919   return Chain;
1920 }
1921
1922 SDValue
1923 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1924                                     SDValue StackPtr, SDValue Arg,
1925                                     DebugLoc dl, SelectionDAG &DAG,
1926                                     const CCValAssign &VA,
1927                                     ISD::ArgFlagsTy Flags) const {
1928   unsigned LocMemOffset = VA.getLocMemOffset();
1929   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1930   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1931   if (Flags.isByVal())
1932     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1933
1934   return DAG.getStore(Chain, dl, Arg, PtrOff,
1935                       MachinePointerInfo::getStack(LocMemOffset),
1936                       false, false, 0);
1937 }
1938
1939 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1940 /// optimization is performed and it is required.
1941 SDValue
1942 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1943                                            SDValue &OutRetAddr, SDValue Chain,
1944                                            bool IsTailCall, bool Is64Bit,
1945                                            int FPDiff, DebugLoc dl) const {
1946   // Adjust the Return address stack slot.
1947   EVT VT = getPointerTy();
1948   OutRetAddr = getReturnAddressFrameIndex(DAG);
1949
1950   // Load the "old" Return address.
1951   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1952                            false, false, 0);
1953   return SDValue(OutRetAddr.getNode(), 1);
1954 }
1955
1956 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1957 /// optimization is performed and it is required (FPDiff!=0).
1958 static SDValue
1959 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1960                          SDValue Chain, SDValue RetAddrFrIdx,
1961                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1962   // Store the return address to the appropriate stack slot.
1963   if (!FPDiff) return Chain;
1964   // Calculate the new stack slot for the return address.
1965   int SlotSize = Is64Bit ? 8 : 4;
1966   int NewReturnAddrFI =
1967     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1968   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1969   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1970   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1971                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1972                        false, false, 0);
1973   return Chain;
1974 }
1975
1976 SDValue
1977 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1978                              CallingConv::ID CallConv, bool isVarArg,
1979                              bool &isTailCall,
1980                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1981                              const SmallVectorImpl<SDValue> &OutVals,
1982                              const SmallVectorImpl<ISD::InputArg> &Ins,
1983                              DebugLoc dl, SelectionDAG &DAG,
1984                              SmallVectorImpl<SDValue> &InVals) const {
1985   MachineFunction &MF = DAG.getMachineFunction();
1986   bool Is64Bit        = Subtarget->is64Bit();
1987   bool IsWin64        = Subtarget->isTargetWin64();
1988   bool IsStructRet    = CallIsStructReturn(Outs);
1989   bool IsSibcall      = false;
1990
1991   if (isTailCall) {
1992     // Check if it's really possible to do a tail call.
1993     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1994                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1995                                                    Outs, OutVals, Ins, DAG);
1996
1997     // Sibcalls are automatically detected tailcalls which do not require
1998     // ABI changes.
1999     if (!GuaranteedTailCallOpt && isTailCall)
2000       IsSibcall = true;
2001
2002     if (isTailCall)
2003       ++NumTailCalls;
2004   }
2005
2006   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2007          "Var args not supported with calling convention fastcc or ghc");
2008
2009   // Analyze operands of the call, assigning locations to each operand.
2010   SmallVector<CCValAssign, 16> ArgLocs;
2011   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2012                  ArgLocs, *DAG.getContext());
2013
2014   // Allocate shadow area for Win64
2015   if (IsWin64) {
2016     CCInfo.AllocateStack(32, 8);
2017   }
2018
2019   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2020
2021   // Get a count of how many bytes are to be pushed on the stack.
2022   unsigned NumBytes = CCInfo.getNextStackOffset();
2023   if (IsSibcall)
2024     // This is a sibcall. The memory operands are available in caller's
2025     // own caller's stack.
2026     NumBytes = 0;
2027   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2028     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2029
2030   int FPDiff = 0;
2031   if (isTailCall && !IsSibcall) {
2032     // Lower arguments at fp - stackoffset + fpdiff.
2033     unsigned NumBytesCallerPushed =
2034       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2035     FPDiff = NumBytesCallerPushed - NumBytes;
2036
2037     // Set the delta of movement of the returnaddr stackslot.
2038     // But only set if delta is greater than previous delta.
2039     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2040       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2041   }
2042
2043   if (!IsSibcall)
2044     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2045
2046   SDValue RetAddrFrIdx;
2047   // Load return address for tail calls.
2048   if (isTailCall && FPDiff)
2049     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2050                                     Is64Bit, FPDiff, dl);
2051
2052   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2053   SmallVector<SDValue, 8> MemOpChains;
2054   SDValue StackPtr;
2055
2056   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2057   // of tail call optimization arguments are handle later.
2058   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2059     CCValAssign &VA = ArgLocs[i];
2060     EVT RegVT = VA.getLocVT();
2061     SDValue Arg = OutVals[i];
2062     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2063     bool isByVal = Flags.isByVal();
2064
2065     // Promote the value if needed.
2066     switch (VA.getLocInfo()) {
2067     default: llvm_unreachable("Unknown loc info!");
2068     case CCValAssign::Full: break;
2069     case CCValAssign::SExt:
2070       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2071       break;
2072     case CCValAssign::ZExt:
2073       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2074       break;
2075     case CCValAssign::AExt:
2076       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2077         // Special case: passing MMX values in XMM registers.
2078         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2079         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2080         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2081       } else
2082         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2083       break;
2084     case CCValAssign::BCvt:
2085       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2086       break;
2087     case CCValAssign::Indirect: {
2088       // Store the argument.
2089       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2090       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2091       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2092                            MachinePointerInfo::getFixedStack(FI),
2093                            false, false, 0);
2094       Arg = SpillSlot;
2095       break;
2096     }
2097     }
2098
2099     if (VA.isRegLoc()) {
2100       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2101       if (isVarArg && IsWin64) {
2102         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2103         // shadow reg if callee is a varargs function.
2104         unsigned ShadowReg = 0;
2105         switch (VA.getLocReg()) {
2106         case X86::XMM0: ShadowReg = X86::RCX; break;
2107         case X86::XMM1: ShadowReg = X86::RDX; break;
2108         case X86::XMM2: ShadowReg = X86::R8; break;
2109         case X86::XMM3: ShadowReg = X86::R9; break;
2110         }
2111         if (ShadowReg)
2112           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2113       }
2114     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2115       assert(VA.isMemLoc());
2116       if (StackPtr.getNode() == 0)
2117         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2118       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2119                                              dl, DAG, VA, Flags));
2120     }
2121   }
2122
2123   if (!MemOpChains.empty())
2124     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2125                         &MemOpChains[0], MemOpChains.size());
2126
2127   // Build a sequence of copy-to-reg nodes chained together with token chain
2128   // and flag operands which copy the outgoing args into registers.
2129   SDValue InFlag;
2130   // Tail call byval lowering might overwrite argument registers so in case of
2131   // tail call optimization the copies to registers are lowered later.
2132   if (!isTailCall)
2133     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2134       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2135                                RegsToPass[i].second, InFlag);
2136       InFlag = Chain.getValue(1);
2137     }
2138
2139   if (Subtarget->isPICStyleGOT()) {
2140     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2141     // GOT pointer.
2142     if (!isTailCall) {
2143       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2144                                DAG.getNode(X86ISD::GlobalBaseReg,
2145                                            DebugLoc(), getPointerTy()),
2146                                InFlag);
2147       InFlag = Chain.getValue(1);
2148     } else {
2149       // If we are tail calling and generating PIC/GOT style code load the
2150       // address of the callee into ECX. The value in ecx is used as target of
2151       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2152       // for tail calls on PIC/GOT architectures. Normally we would just put the
2153       // address of GOT into ebx and then call target@PLT. But for tail calls
2154       // ebx would be restored (since ebx is callee saved) before jumping to the
2155       // target@PLT.
2156
2157       // Note: The actual moving to ECX is done further down.
2158       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2159       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2160           !G->getGlobal()->hasProtectedVisibility())
2161         Callee = LowerGlobalAddress(Callee, DAG);
2162       else if (isa<ExternalSymbolSDNode>(Callee))
2163         Callee = LowerExternalSymbol(Callee, DAG);
2164     }
2165   }
2166
2167   if (Is64Bit && isVarArg && !IsWin64) {
2168     // From AMD64 ABI document:
2169     // For calls that may call functions that use varargs or stdargs
2170     // (prototype-less calls or calls to functions containing ellipsis (...) in
2171     // the declaration) %al is used as hidden argument to specify the number
2172     // of SSE registers used. The contents of %al do not need to match exactly
2173     // the number of registers, but must be an ubound on the number of SSE
2174     // registers used and is in the range 0 - 8 inclusive.
2175
2176     // Count the number of XMM registers allocated.
2177     static const unsigned XMMArgRegs[] = {
2178       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2179       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2180     };
2181     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2182     assert((Subtarget->hasXMM() || !NumXMMRegs)
2183            && "SSE registers cannot be used when SSE is disabled");
2184
2185     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2186                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2187     InFlag = Chain.getValue(1);
2188   }
2189
2190
2191   // For tail calls lower the arguments to the 'real' stack slot.
2192   if (isTailCall) {
2193     // Force all the incoming stack arguments to be loaded from the stack
2194     // before any new outgoing arguments are stored to the stack, because the
2195     // outgoing stack slots may alias the incoming argument stack slots, and
2196     // the alias isn't otherwise explicit. This is slightly more conservative
2197     // than necessary, because it means that each store effectively depends
2198     // on every argument instead of just those arguments it would clobber.
2199     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2200
2201     SmallVector<SDValue, 8> MemOpChains2;
2202     SDValue FIN;
2203     int FI = 0;
2204     // Do not flag preceding copytoreg stuff together with the following stuff.
2205     InFlag = SDValue();
2206     if (GuaranteedTailCallOpt) {
2207       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2208         CCValAssign &VA = ArgLocs[i];
2209         if (VA.isRegLoc())
2210           continue;
2211         assert(VA.isMemLoc());
2212         SDValue Arg = OutVals[i];
2213         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2214         // Create frame index.
2215         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2216         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2217         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2218         FIN = DAG.getFrameIndex(FI, getPointerTy());
2219
2220         if (Flags.isByVal()) {
2221           // Copy relative to framepointer.
2222           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2223           if (StackPtr.getNode() == 0)
2224             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2225                                           getPointerTy());
2226           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2227
2228           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2229                                                            ArgChain,
2230                                                            Flags, DAG, dl));
2231         } else {
2232           // Store relative to framepointer.
2233           MemOpChains2.push_back(
2234             DAG.getStore(ArgChain, dl, Arg, FIN,
2235                          MachinePointerInfo::getFixedStack(FI),
2236                          false, false, 0));
2237         }
2238       }
2239     }
2240
2241     if (!MemOpChains2.empty())
2242       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2243                           &MemOpChains2[0], MemOpChains2.size());
2244
2245     // Copy arguments to their registers.
2246     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2247       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2248                                RegsToPass[i].second, InFlag);
2249       InFlag = Chain.getValue(1);
2250     }
2251     InFlag =SDValue();
2252
2253     // Store the return address to the appropriate stack slot.
2254     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2255                                      FPDiff, dl);
2256   }
2257
2258   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2259     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2260     // In the 64-bit large code model, we have to make all calls
2261     // through a register, since the call instruction's 32-bit
2262     // pc-relative offset may not be large enough to hold the whole
2263     // address.
2264   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2265     // If the callee is a GlobalAddress node (quite common, every direct call
2266     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2267     // it.
2268
2269     // We should use extra load for direct calls to dllimported functions in
2270     // non-JIT mode.
2271     const GlobalValue *GV = G->getGlobal();
2272     if (!GV->hasDLLImportLinkage()) {
2273       unsigned char OpFlags = 0;
2274       bool ExtraLoad = false;
2275       unsigned WrapperKind = ISD::DELETED_NODE;
2276
2277       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2278       // external symbols most go through the PLT in PIC mode.  If the symbol
2279       // has hidden or protected visibility, or if it is static or local, then
2280       // we don't need to use the PLT - we can directly call it.
2281       if (Subtarget->isTargetELF() &&
2282           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2283           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2284         OpFlags = X86II::MO_PLT;
2285       } else if (Subtarget->isPICStyleStubAny() &&
2286                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2287                  (!Subtarget->getTargetTriple().isMacOSX() ||
2288                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2289         // PC-relative references to external symbols should go through $stub,
2290         // unless we're building with the leopard linker or later, which
2291         // automatically synthesizes these stubs.
2292         OpFlags = X86II::MO_DARWIN_STUB;
2293       } else if (Subtarget->isPICStyleRIPRel() &&
2294                  isa<Function>(GV) &&
2295                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2296         // If the function is marked as non-lazy, generate an indirect call
2297         // which loads from the GOT directly. This avoids runtime overhead
2298         // at the cost of eager binding (and one extra byte of encoding).
2299         OpFlags = X86II::MO_GOTPCREL;
2300         WrapperKind = X86ISD::WrapperRIP;
2301         ExtraLoad = true;
2302       }
2303
2304       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2305                                           G->getOffset(), OpFlags);
2306
2307       // Add a wrapper if needed.
2308       if (WrapperKind != ISD::DELETED_NODE)
2309         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2310       // Add extra indirection if needed.
2311       if (ExtraLoad)
2312         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2313                              MachinePointerInfo::getGOT(),
2314                              false, false, 0);
2315     }
2316   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2317     unsigned char OpFlags = 0;
2318
2319     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2320     // external symbols should go through the PLT.
2321     if (Subtarget->isTargetELF() &&
2322         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2323       OpFlags = X86II::MO_PLT;
2324     } else if (Subtarget->isPICStyleStubAny() &&
2325                (!Subtarget->getTargetTriple().isMacOSX() ||
2326                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2327       // PC-relative references to external symbols should go through $stub,
2328       // unless we're building with the leopard linker or later, which
2329       // automatically synthesizes these stubs.
2330       OpFlags = X86II::MO_DARWIN_STUB;
2331     }
2332
2333     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2334                                          OpFlags);
2335   }
2336
2337   // Returns a chain & a flag for retval copy to use.
2338   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2339   SmallVector<SDValue, 8> Ops;
2340
2341   if (!IsSibcall && isTailCall) {
2342     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2343                            DAG.getIntPtrConstant(0, true), InFlag);
2344     InFlag = Chain.getValue(1);
2345   }
2346
2347   Ops.push_back(Chain);
2348   Ops.push_back(Callee);
2349
2350   if (isTailCall)
2351     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2352
2353   // Add argument registers to the end of the list so that they are known live
2354   // into the call.
2355   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2356     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2357                                   RegsToPass[i].second.getValueType()));
2358
2359   // Add an implicit use GOT pointer in EBX.
2360   if (!isTailCall && Subtarget->isPICStyleGOT())
2361     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2362
2363   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2364   if (Is64Bit && isVarArg && !IsWin64)
2365     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2366
2367   if (InFlag.getNode())
2368     Ops.push_back(InFlag);
2369
2370   if (isTailCall) {
2371     // We used to do:
2372     //// If this is the first return lowered for this function, add the regs
2373     //// to the liveout set for the function.
2374     // This isn't right, although it's probably harmless on x86; liveouts
2375     // should be computed from returns not tail calls.  Consider a void
2376     // function making a tail call to a function returning int.
2377     return DAG.getNode(X86ISD::TC_RETURN, dl,
2378                        NodeTys, &Ops[0], Ops.size());
2379   }
2380
2381   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2382   InFlag = Chain.getValue(1);
2383
2384   // Create the CALLSEQ_END node.
2385   unsigned NumBytesForCalleeToPush;
2386   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2387     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2388   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2389     // If this is a call to a struct-return function, the callee
2390     // pops the hidden struct pointer, so we have to push it back.
2391     // This is common for Darwin/X86, Linux & Mingw32 targets.
2392     NumBytesForCalleeToPush = 4;
2393   else
2394     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2395
2396   // Returns a flag for retval copy to use.
2397   if (!IsSibcall) {
2398     Chain = DAG.getCALLSEQ_END(Chain,
2399                                DAG.getIntPtrConstant(NumBytes, true),
2400                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2401                                                      true),
2402                                InFlag);
2403     InFlag = Chain.getValue(1);
2404   }
2405
2406   // Handle result values, copying them out of physregs into vregs that we
2407   // return.
2408   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2409                          Ins, dl, DAG, InVals);
2410 }
2411
2412
2413 //===----------------------------------------------------------------------===//
2414 //                Fast Calling Convention (tail call) implementation
2415 //===----------------------------------------------------------------------===//
2416
2417 //  Like std call, callee cleans arguments, convention except that ECX is
2418 //  reserved for storing the tail called function address. Only 2 registers are
2419 //  free for argument passing (inreg). Tail call optimization is performed
2420 //  provided:
2421 //                * tailcallopt is enabled
2422 //                * caller/callee are fastcc
2423 //  On X86_64 architecture with GOT-style position independent code only local
2424 //  (within module) calls are supported at the moment.
2425 //  To keep the stack aligned according to platform abi the function
2426 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2427 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2428 //  If a tail called function callee has more arguments than the caller the
2429 //  caller needs to make sure that there is room to move the RETADDR to. This is
2430 //  achieved by reserving an area the size of the argument delta right after the
2431 //  original REtADDR, but before the saved framepointer or the spilled registers
2432 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2433 //  stack layout:
2434 //    arg1
2435 //    arg2
2436 //    RETADDR
2437 //    [ new RETADDR
2438 //      move area ]
2439 //    (possible EBP)
2440 //    ESI
2441 //    EDI
2442 //    local1 ..
2443
2444 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2445 /// for a 16 byte align requirement.
2446 unsigned
2447 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2448                                                SelectionDAG& DAG) const {
2449   MachineFunction &MF = DAG.getMachineFunction();
2450   const TargetMachine &TM = MF.getTarget();
2451   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2452   unsigned StackAlignment = TFI.getStackAlignment();
2453   uint64_t AlignMask = StackAlignment - 1;
2454   int64_t Offset = StackSize;
2455   uint64_t SlotSize = TD->getPointerSize();
2456   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2457     // Number smaller than 12 so just add the difference.
2458     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2459   } else {
2460     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2461     Offset = ((~AlignMask) & Offset) + StackAlignment +
2462       (StackAlignment-SlotSize);
2463   }
2464   return Offset;
2465 }
2466
2467 /// MatchingStackOffset - Return true if the given stack call argument is
2468 /// already available in the same position (relatively) of the caller's
2469 /// incoming argument stack.
2470 static
2471 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2472                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2473                          const X86InstrInfo *TII) {
2474   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2475   int FI = INT_MAX;
2476   if (Arg.getOpcode() == ISD::CopyFromReg) {
2477     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2478     if (!TargetRegisterInfo::isVirtualRegister(VR))
2479       return false;
2480     MachineInstr *Def = MRI->getVRegDef(VR);
2481     if (!Def)
2482       return false;
2483     if (!Flags.isByVal()) {
2484       if (!TII->isLoadFromStackSlot(Def, FI))
2485         return false;
2486     } else {
2487       unsigned Opcode = Def->getOpcode();
2488       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2489           Def->getOperand(1).isFI()) {
2490         FI = Def->getOperand(1).getIndex();
2491         Bytes = Flags.getByValSize();
2492       } else
2493         return false;
2494     }
2495   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2496     if (Flags.isByVal())
2497       // ByVal argument is passed in as a pointer but it's now being
2498       // dereferenced. e.g.
2499       // define @foo(%struct.X* %A) {
2500       //   tail call @bar(%struct.X* byval %A)
2501       // }
2502       return false;
2503     SDValue Ptr = Ld->getBasePtr();
2504     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2505     if (!FINode)
2506       return false;
2507     FI = FINode->getIndex();
2508   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2509     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Arg);
2510     FI = FINode->getIndex();
2511     Bytes = Flags.getByValSize();
2512   } else
2513     return false;
2514
2515   assert(FI != INT_MAX);
2516   if (!MFI->isFixedObjectIndex(FI))
2517     return false;
2518   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2519 }
2520
2521 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2522 /// for tail call optimization. Targets which want to do tail call
2523 /// optimization should implement this function.
2524 bool
2525 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2526                                                      CallingConv::ID CalleeCC,
2527                                                      bool isVarArg,
2528                                                      bool isCalleeStructRet,
2529                                                      bool isCallerStructRet,
2530                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2531                                     const SmallVectorImpl<SDValue> &OutVals,
2532                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2533                                                      SelectionDAG& DAG) const {
2534   if (!IsTailCallConvention(CalleeCC) &&
2535       CalleeCC != CallingConv::C)
2536     return false;
2537
2538   // If -tailcallopt is specified, make fastcc functions tail-callable.
2539   const MachineFunction &MF = DAG.getMachineFunction();
2540   const Function *CallerF = DAG.getMachineFunction().getFunction();
2541   CallingConv::ID CallerCC = CallerF->getCallingConv();
2542   bool CCMatch = CallerCC == CalleeCC;
2543
2544   if (GuaranteedTailCallOpt) {
2545     if (IsTailCallConvention(CalleeCC) && CCMatch)
2546       return true;
2547     return false;
2548   }
2549
2550   // Look for obvious safe cases to perform tail call optimization that do not
2551   // require ABI changes. This is what gcc calls sibcall.
2552
2553   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2554   // emit a special epilogue.
2555   if (RegInfo->needsStackRealignment(MF))
2556     return false;
2557
2558   // Also avoid sibcall optimization if either caller or callee uses struct
2559   // return semantics.
2560   if (isCalleeStructRet || isCallerStructRet)
2561     return false;
2562
2563   // An stdcall caller is expected to clean up its arguments; the callee
2564   // isn't going to do that.
2565   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2566     return false;
2567
2568   // Do not sibcall optimize vararg calls unless all arguments are passed via
2569   // registers.
2570   if (isVarArg && !Outs.empty()) {
2571
2572     // Optimizing for varargs on Win64 is unlikely to be safe without
2573     // additional testing.
2574     if (Subtarget->isTargetWin64())
2575       return false;
2576
2577     SmallVector<CCValAssign, 16> ArgLocs;
2578     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2579                    getTargetMachine(), ArgLocs, *DAG.getContext());
2580
2581     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2582     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2583       if (!ArgLocs[i].isRegLoc())
2584         return false;
2585   }
2586
2587   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2588   // Therefore if it's not used by the call it is not safe to optimize this into
2589   // a sibcall.
2590   bool Unused = false;
2591   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2592     if (!Ins[i].Used) {
2593       Unused = true;
2594       break;
2595     }
2596   }
2597   if (Unused) {
2598     SmallVector<CCValAssign, 16> RVLocs;
2599     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2600                    getTargetMachine(), RVLocs, *DAG.getContext());
2601     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2602     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2603       CCValAssign &VA = RVLocs[i];
2604       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2605         return false;
2606     }
2607   }
2608
2609   // If the calling conventions do not match, then we'd better make sure the
2610   // results are returned in the same way as what the caller expects.
2611   if (!CCMatch) {
2612     SmallVector<CCValAssign, 16> RVLocs1;
2613     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2614                     getTargetMachine(), RVLocs1, *DAG.getContext());
2615     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2616
2617     SmallVector<CCValAssign, 16> RVLocs2;
2618     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2619                     getTargetMachine(), RVLocs2, *DAG.getContext());
2620     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2621
2622     if (RVLocs1.size() != RVLocs2.size())
2623       return false;
2624     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2625       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2626         return false;
2627       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2628         return false;
2629       if (RVLocs1[i].isRegLoc()) {
2630         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2631           return false;
2632       } else {
2633         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2634           return false;
2635       }
2636     }
2637   }
2638
2639   // If the callee takes no arguments then go on to check the results of the
2640   // call.
2641   if (!Outs.empty()) {
2642     // Check if stack adjustment is needed. For now, do not do this if any
2643     // argument is passed on the stack.
2644     SmallVector<CCValAssign, 16> ArgLocs;
2645     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2646                    getTargetMachine(), ArgLocs, *DAG.getContext());
2647
2648     // Allocate shadow area for Win64
2649     if (Subtarget->isTargetWin64()) {
2650       CCInfo.AllocateStack(32, 8);
2651     }
2652
2653     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2654     if (CCInfo.getNextStackOffset()) {
2655       MachineFunction &MF = DAG.getMachineFunction();
2656       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2657         return false;
2658
2659       // Check if the arguments are already laid out in the right way as
2660       // the caller's fixed stack objects.
2661       MachineFrameInfo *MFI = MF.getFrameInfo();
2662       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2663       const X86InstrInfo *TII =
2664         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2665       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2666         CCValAssign &VA = ArgLocs[i];
2667         SDValue Arg = OutVals[i];
2668         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2669         if (VA.getLocInfo() == CCValAssign::Indirect)
2670           return false;
2671         if (!VA.isRegLoc()) {
2672           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2673                                    MFI, MRI, TII))
2674             return false;
2675         }
2676       }
2677     }
2678
2679     // If the tailcall address may be in a register, then make sure it's
2680     // possible to register allocate for it. In 32-bit, the call address can
2681     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2682     // callee-saved registers are restored. These happen to be the same
2683     // registers used to pass 'inreg' arguments so watch out for those.
2684     if (!Subtarget->is64Bit() &&
2685         !isa<GlobalAddressSDNode>(Callee) &&
2686         !isa<ExternalSymbolSDNode>(Callee)) {
2687       unsigned NumInRegs = 0;
2688       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2689         CCValAssign &VA = ArgLocs[i];
2690         if (!VA.isRegLoc())
2691           continue;
2692         unsigned Reg = VA.getLocReg();
2693         switch (Reg) {
2694         default: break;
2695         case X86::EAX: case X86::EDX: case X86::ECX:
2696           if (++NumInRegs == 3)
2697             return false;
2698           break;
2699         }
2700       }
2701     }
2702   }
2703
2704   return true;
2705 }
2706
2707 FastISel *
2708 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2709   return X86::createFastISel(funcInfo);
2710 }
2711
2712
2713 //===----------------------------------------------------------------------===//
2714 //                           Other Lowering Hooks
2715 //===----------------------------------------------------------------------===//
2716
2717 static bool MayFoldLoad(SDValue Op) {
2718   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2719 }
2720
2721 static bool MayFoldIntoStore(SDValue Op) {
2722   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2723 }
2724
2725 static bool isTargetShuffle(unsigned Opcode) {
2726   switch(Opcode) {
2727   default: return false;
2728   case X86ISD::PSHUFD:
2729   case X86ISD::PSHUFHW:
2730   case X86ISD::PSHUFLW:
2731   case X86ISD::SHUFPD:
2732   case X86ISD::PALIGN:
2733   case X86ISD::SHUFPS:
2734   case X86ISD::MOVLHPS:
2735   case X86ISD::MOVLHPD:
2736   case X86ISD::MOVHLPS:
2737   case X86ISD::MOVLPS:
2738   case X86ISD::MOVLPD:
2739   case X86ISD::MOVSHDUP:
2740   case X86ISD::MOVSLDUP:
2741   case X86ISD::MOVDDUP:
2742   case X86ISD::MOVSS:
2743   case X86ISD::MOVSD:
2744   case X86ISD::UNPCKLPS:
2745   case X86ISD::UNPCKLPD:
2746   case X86ISD::VUNPCKLPS:
2747   case X86ISD::VUNPCKLPD:
2748   case X86ISD::VUNPCKLPSY:
2749   case X86ISD::VUNPCKLPDY:
2750   case X86ISD::PUNPCKLWD:
2751   case X86ISD::PUNPCKLBW:
2752   case X86ISD::PUNPCKLDQ:
2753   case X86ISD::PUNPCKLQDQ:
2754   case X86ISD::UNPCKHPS:
2755   case X86ISD::UNPCKHPD:
2756   case X86ISD::PUNPCKHWD:
2757   case X86ISD::PUNPCKHBW:
2758   case X86ISD::PUNPCKHDQ:
2759   case X86ISD::PUNPCKHQDQ:
2760     return true;
2761   }
2762   return false;
2763 }
2764
2765 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2766                                                SDValue V1, SelectionDAG &DAG) {
2767   switch(Opc) {
2768   default: llvm_unreachable("Unknown x86 shuffle node");
2769   case X86ISD::MOVSHDUP:
2770   case X86ISD::MOVSLDUP:
2771   case X86ISD::MOVDDUP:
2772     return DAG.getNode(Opc, dl, VT, V1);
2773   }
2774
2775   return SDValue();
2776 }
2777
2778 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2779                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2780   switch(Opc) {
2781   default: llvm_unreachable("Unknown x86 shuffle node");
2782   case X86ISD::PSHUFD:
2783   case X86ISD::PSHUFHW:
2784   case X86ISD::PSHUFLW:
2785     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2786   }
2787
2788   return SDValue();
2789 }
2790
2791 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2792                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2793   switch(Opc) {
2794   default: llvm_unreachable("Unknown x86 shuffle node");
2795   case X86ISD::PALIGN:
2796   case X86ISD::SHUFPD:
2797   case X86ISD::SHUFPS:
2798     return DAG.getNode(Opc, dl, VT, V1, V2,
2799                        DAG.getConstant(TargetMask, MVT::i8));
2800   }
2801   return SDValue();
2802 }
2803
2804 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2805                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2806   switch(Opc) {
2807   default: llvm_unreachable("Unknown x86 shuffle node");
2808   case X86ISD::MOVLHPS:
2809   case X86ISD::MOVLHPD:
2810   case X86ISD::MOVHLPS:
2811   case X86ISD::MOVLPS:
2812   case X86ISD::MOVLPD:
2813   case X86ISD::MOVSS:
2814   case X86ISD::MOVSD:
2815   case X86ISD::UNPCKLPS:
2816   case X86ISD::UNPCKLPD:
2817   case X86ISD::VUNPCKLPS:
2818   case X86ISD::VUNPCKLPD:
2819   case X86ISD::VUNPCKLPSY:
2820   case X86ISD::VUNPCKLPDY:
2821   case X86ISD::PUNPCKLWD:
2822   case X86ISD::PUNPCKLBW:
2823   case X86ISD::PUNPCKLDQ:
2824   case X86ISD::PUNPCKLQDQ:
2825   case X86ISD::UNPCKHPS:
2826   case X86ISD::UNPCKHPD:
2827   case X86ISD::PUNPCKHWD:
2828   case X86ISD::PUNPCKHBW:
2829   case X86ISD::PUNPCKHDQ:
2830   case X86ISD::PUNPCKHQDQ:
2831     return DAG.getNode(Opc, dl, VT, V1, V2);
2832   }
2833   return SDValue();
2834 }
2835
2836 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2837   MachineFunction &MF = DAG.getMachineFunction();
2838   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2839   int ReturnAddrIndex = FuncInfo->getRAIndex();
2840
2841   if (ReturnAddrIndex == 0) {
2842     // Set up a frame object for the return address.
2843     uint64_t SlotSize = TD->getPointerSize();
2844     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2845                                                            false);
2846     FuncInfo->setRAIndex(ReturnAddrIndex);
2847   }
2848
2849   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2850 }
2851
2852
2853 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2854                                        bool hasSymbolicDisplacement) {
2855   // Offset should fit into 32 bit immediate field.
2856   if (!isInt<32>(Offset))
2857     return false;
2858
2859   // If we don't have a symbolic displacement - we don't have any extra
2860   // restrictions.
2861   if (!hasSymbolicDisplacement)
2862     return true;
2863
2864   // FIXME: Some tweaks might be needed for medium code model.
2865   if (M != CodeModel::Small && M != CodeModel::Kernel)
2866     return false;
2867
2868   // For small code model we assume that latest object is 16MB before end of 31
2869   // bits boundary. We may also accept pretty large negative constants knowing
2870   // that all objects are in the positive half of address space.
2871   if (M == CodeModel::Small && Offset < 16*1024*1024)
2872     return true;
2873
2874   // For kernel code model we know that all object resist in the negative half
2875   // of 32bits address space. We may not accept negative offsets, since they may
2876   // be just off and we may accept pretty large positive ones.
2877   if (M == CodeModel::Kernel && Offset > 0)
2878     return true;
2879
2880   return false;
2881 }
2882
2883 /// isCalleePop - Determines whether the callee is required to pop its
2884 /// own arguments. Callee pop is necessary to support tail calls.
2885 bool X86::isCalleePop(CallingConv::ID CallingConv,
2886                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2887   if (IsVarArg)
2888     return false;
2889
2890   switch (CallingConv) {
2891   default:
2892     return false;
2893   case CallingConv::X86_StdCall:
2894     return !is64Bit;
2895   case CallingConv::X86_FastCall:
2896     return !is64Bit;
2897   case CallingConv::X86_ThisCall:
2898     return !is64Bit;
2899   case CallingConv::Fast:
2900     return TailCallOpt;
2901   case CallingConv::GHC:
2902     return TailCallOpt;
2903   }
2904 }
2905
2906 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2907 /// specific condition code, returning the condition code and the LHS/RHS of the
2908 /// comparison to make.
2909 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2910                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2911   if (!isFP) {
2912     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2913       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2914         // X > -1   -> X == 0, jump !sign.
2915         RHS = DAG.getConstant(0, RHS.getValueType());
2916         return X86::COND_NS;
2917       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2918         // X < 0   -> X == 0, jump on sign.
2919         return X86::COND_S;
2920       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2921         // X < 1   -> X <= 0
2922         RHS = DAG.getConstant(0, RHS.getValueType());
2923         return X86::COND_LE;
2924       }
2925     }
2926
2927     switch (SetCCOpcode) {
2928     default: llvm_unreachable("Invalid integer condition!");
2929     case ISD::SETEQ:  return X86::COND_E;
2930     case ISD::SETGT:  return X86::COND_G;
2931     case ISD::SETGE:  return X86::COND_GE;
2932     case ISD::SETLT:  return X86::COND_L;
2933     case ISD::SETLE:  return X86::COND_LE;
2934     case ISD::SETNE:  return X86::COND_NE;
2935     case ISD::SETULT: return X86::COND_B;
2936     case ISD::SETUGT: return X86::COND_A;
2937     case ISD::SETULE: return X86::COND_BE;
2938     case ISD::SETUGE: return X86::COND_AE;
2939     }
2940   }
2941
2942   // First determine if it is required or is profitable to flip the operands.
2943
2944   // If LHS is a foldable load, but RHS is not, flip the condition.
2945   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2946       !ISD::isNON_EXTLoad(RHS.getNode())) {
2947     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2948     std::swap(LHS, RHS);
2949   }
2950
2951   switch (SetCCOpcode) {
2952   default: break;
2953   case ISD::SETOLT:
2954   case ISD::SETOLE:
2955   case ISD::SETUGT:
2956   case ISD::SETUGE:
2957     std::swap(LHS, RHS);
2958     break;
2959   }
2960
2961   // On a floating point condition, the flags are set as follows:
2962   // ZF  PF  CF   op
2963   //  0 | 0 | 0 | X > Y
2964   //  0 | 0 | 1 | X < Y
2965   //  1 | 0 | 0 | X == Y
2966   //  1 | 1 | 1 | unordered
2967   switch (SetCCOpcode) {
2968   default: llvm_unreachable("Condcode should be pre-legalized away");
2969   case ISD::SETUEQ:
2970   case ISD::SETEQ:   return X86::COND_E;
2971   case ISD::SETOLT:              // flipped
2972   case ISD::SETOGT:
2973   case ISD::SETGT:   return X86::COND_A;
2974   case ISD::SETOLE:              // flipped
2975   case ISD::SETOGE:
2976   case ISD::SETGE:   return X86::COND_AE;
2977   case ISD::SETUGT:              // flipped
2978   case ISD::SETULT:
2979   case ISD::SETLT:   return X86::COND_B;
2980   case ISD::SETUGE:              // flipped
2981   case ISD::SETULE:
2982   case ISD::SETLE:   return X86::COND_BE;
2983   case ISD::SETONE:
2984   case ISD::SETNE:   return X86::COND_NE;
2985   case ISD::SETUO:   return X86::COND_P;
2986   case ISD::SETO:    return X86::COND_NP;
2987   case ISD::SETOEQ:
2988   case ISD::SETUNE:  return X86::COND_INVALID;
2989   }
2990 }
2991
2992 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2993 /// code. Current x86 isa includes the following FP cmov instructions:
2994 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2995 static bool hasFPCMov(unsigned X86CC) {
2996   switch (X86CC) {
2997   default:
2998     return false;
2999   case X86::COND_B:
3000   case X86::COND_BE:
3001   case X86::COND_E:
3002   case X86::COND_P:
3003   case X86::COND_A:
3004   case X86::COND_AE:
3005   case X86::COND_NE:
3006   case X86::COND_NP:
3007     return true;
3008   }
3009 }
3010
3011 /// isFPImmLegal - Returns true if the target can instruction select the
3012 /// specified FP immediate natively. If false, the legalizer will
3013 /// materialize the FP immediate as a load from a constant pool.
3014 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3015   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3016     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3017       return true;
3018   }
3019   return false;
3020 }
3021
3022 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3023 /// the specified range (L, H].
3024 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3025   return (Val < 0) || (Val >= Low && Val < Hi);
3026 }
3027
3028 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3029 /// specified value.
3030 static bool isUndefOrEqual(int Val, int CmpVal) {
3031   if (Val < 0 || Val == CmpVal)
3032     return true;
3033   return false;
3034 }
3035
3036 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3037 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3038 /// the second operand.
3039 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3040   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3041     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3042   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3043     return (Mask[0] < 2 && Mask[1] < 2);
3044   return false;
3045 }
3046
3047 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3048   SmallVector<int, 8> M;
3049   N->getMask(M);
3050   return ::isPSHUFDMask(M, N->getValueType(0));
3051 }
3052
3053 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3054 /// is suitable for input to PSHUFHW.
3055 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3056   if (VT != MVT::v8i16)
3057     return false;
3058
3059   // Lower quadword copied in order or undef.
3060   for (int i = 0; i != 4; ++i)
3061     if (Mask[i] >= 0 && Mask[i] != i)
3062       return false;
3063
3064   // Upper quadword shuffled.
3065   for (int i = 4; i != 8; ++i)
3066     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3067       return false;
3068
3069   return true;
3070 }
3071
3072 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3073   SmallVector<int, 8> M;
3074   N->getMask(M);
3075   return ::isPSHUFHWMask(M, N->getValueType(0));
3076 }
3077
3078 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3079 /// is suitable for input to PSHUFLW.
3080 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3081   if (VT != MVT::v8i16)
3082     return false;
3083
3084   // Upper quadword copied in order.
3085   for (int i = 4; i != 8; ++i)
3086     if (Mask[i] >= 0 && Mask[i] != i)
3087       return false;
3088
3089   // Lower quadword shuffled.
3090   for (int i = 0; i != 4; ++i)
3091     if (Mask[i] >= 4)
3092       return false;
3093
3094   return true;
3095 }
3096
3097 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3098   SmallVector<int, 8> M;
3099   N->getMask(M);
3100   return ::isPSHUFLWMask(M, N->getValueType(0));
3101 }
3102
3103 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3104 /// is suitable for input to PALIGNR.
3105 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3106                           bool hasSSSE3) {
3107   int i, e = VT.getVectorNumElements();
3108
3109   // Do not handle v2i64 / v2f64 shuffles with palignr.
3110   if (e < 4 || !hasSSSE3)
3111     return false;
3112
3113   for (i = 0; i != e; ++i)
3114     if (Mask[i] >= 0)
3115       break;
3116
3117   // All undef, not a palignr.
3118   if (i == e)
3119     return false;
3120
3121   // Determine if it's ok to perform a palignr with only the LHS, since we
3122   // don't have access to the actual shuffle elements to see if RHS is undef.
3123   bool Unary = Mask[i] < (int)e;
3124   bool NeedsUnary = false;
3125
3126   int s = Mask[i] - i;
3127
3128   // Check the rest of the elements to see if they are consecutive.
3129   for (++i; i != e; ++i) {
3130     int m = Mask[i];
3131     if (m < 0)
3132       continue;
3133
3134     Unary = Unary && (m < (int)e);
3135     NeedsUnary = NeedsUnary || (m < s);
3136
3137     if (NeedsUnary && !Unary)
3138       return false;
3139     if (Unary && m != ((s+i) & (e-1)))
3140       return false;
3141     if (!Unary && m != (s+i))
3142       return false;
3143   }
3144   return true;
3145 }
3146
3147 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3148   SmallVector<int, 8> M;
3149   N->getMask(M);
3150   return ::isPALIGNRMask(M, N->getValueType(0), true);
3151 }
3152
3153 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3154 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3155 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3156   int NumElems = VT.getVectorNumElements();
3157   if (NumElems != 2 && NumElems != 4)
3158     return false;
3159
3160   int Half = NumElems / 2;
3161   for (int i = 0; i < Half; ++i)
3162     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3163       return false;
3164   for (int i = Half; i < NumElems; ++i)
3165     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3166       return false;
3167
3168   return true;
3169 }
3170
3171 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3172   SmallVector<int, 8> M;
3173   N->getMask(M);
3174   return ::isSHUFPMask(M, N->getValueType(0));
3175 }
3176
3177 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3178 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3179 /// half elements to come from vector 1 (which would equal the dest.) and
3180 /// the upper half to come from vector 2.
3181 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3182   int NumElems = VT.getVectorNumElements();
3183
3184   if (NumElems != 2 && NumElems != 4)
3185     return false;
3186
3187   int Half = NumElems / 2;
3188   for (int i = 0; i < Half; ++i)
3189     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3190       return false;
3191   for (int i = Half; i < NumElems; ++i)
3192     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3193       return false;
3194   return true;
3195 }
3196
3197 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3198   SmallVector<int, 8> M;
3199   N->getMask(M);
3200   return isCommutedSHUFPMask(M, N->getValueType(0));
3201 }
3202
3203 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3204 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3205 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3206   if (N->getValueType(0).getVectorNumElements() != 4)
3207     return false;
3208
3209   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3210   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3211          isUndefOrEqual(N->getMaskElt(1), 7) &&
3212          isUndefOrEqual(N->getMaskElt(2), 2) &&
3213          isUndefOrEqual(N->getMaskElt(3), 3);
3214 }
3215
3216 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3217 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3218 /// <2, 3, 2, 3>
3219 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3220   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3221
3222   if (NumElems != 4)
3223     return false;
3224
3225   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3226   isUndefOrEqual(N->getMaskElt(1), 3) &&
3227   isUndefOrEqual(N->getMaskElt(2), 2) &&
3228   isUndefOrEqual(N->getMaskElt(3), 3);
3229 }
3230
3231 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3232 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3233 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3234   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3235
3236   if (NumElems != 2 && NumElems != 4)
3237     return false;
3238
3239   for (unsigned i = 0; i < NumElems/2; ++i)
3240     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3241       return false;
3242
3243   for (unsigned i = NumElems/2; i < NumElems; ++i)
3244     if (!isUndefOrEqual(N->getMaskElt(i), i))
3245       return false;
3246
3247   return true;
3248 }
3249
3250 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3251 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3252 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3253   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3254
3255   if ((NumElems != 2 && NumElems != 4)
3256       || N->getValueType(0).getSizeInBits() > 128)
3257     return false;
3258
3259   for (unsigned i = 0; i < NumElems/2; ++i)
3260     if (!isUndefOrEqual(N->getMaskElt(i), i))
3261       return false;
3262
3263   for (unsigned i = 0; i < NumElems/2; ++i)
3264     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3265       return false;
3266
3267   return true;
3268 }
3269
3270 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3271 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3272 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3273                          bool V2IsSplat = false) {
3274   int NumElts = VT.getVectorNumElements();
3275   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3276     return false;
3277
3278   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3279   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3280   // sections.
3281   unsigned NumSections = VT.getSizeInBits() / 128;
3282   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3283   unsigned NumSectionElts = NumElts / NumSections;
3284
3285   unsigned Start = 0;
3286   unsigned End = NumSectionElts;
3287   for (unsigned s = 0; s < NumSections; ++s) {
3288     for (unsigned i = Start, j = s * NumSectionElts;
3289          i != End;
3290          i += 2, ++j) {
3291       int BitI  = Mask[i];
3292       int BitI1 = Mask[i+1];
3293       if (!isUndefOrEqual(BitI, j))
3294         return false;
3295       if (V2IsSplat) {
3296         if (!isUndefOrEqual(BitI1, NumElts))
3297           return false;
3298       } else {
3299         if (!isUndefOrEqual(BitI1, j + NumElts))
3300           return false;
3301       }
3302     }
3303     // Process the next 128 bits.
3304     Start += NumSectionElts;
3305     End += NumSectionElts;
3306   }
3307
3308   return true;
3309 }
3310
3311 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3312   SmallVector<int, 8> M;
3313   N->getMask(M);
3314   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3315 }
3316
3317 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3318 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3319 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3320                          bool V2IsSplat = false) {
3321   int NumElts = VT.getVectorNumElements();
3322   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3323     return false;
3324
3325   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3326     int BitI  = Mask[i];
3327     int BitI1 = Mask[i+1];
3328     if (!isUndefOrEqual(BitI, j + NumElts/2))
3329       return false;
3330     if (V2IsSplat) {
3331       if (isUndefOrEqual(BitI1, NumElts))
3332         return false;
3333     } else {
3334       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3335         return false;
3336     }
3337   }
3338   return true;
3339 }
3340
3341 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3342   SmallVector<int, 8> M;
3343   N->getMask(M);
3344   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3345 }
3346
3347 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3348 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3349 /// <0, 0, 1, 1>
3350 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3351   int NumElems = VT.getVectorNumElements();
3352   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3353     return false;
3354
3355   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3356   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3357   // sections.
3358   unsigned NumSections = VT.getSizeInBits() / 128;
3359   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3360   unsigned NumSectionElts = NumElems / NumSections;
3361
3362   for (unsigned s = 0; s < NumSections; ++s) {
3363     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3364          i != NumSectionElts * (s + 1);
3365          i += 2, ++j) {
3366       int BitI  = Mask[i];
3367       int BitI1 = Mask[i+1];
3368
3369       if (!isUndefOrEqual(BitI, j))
3370         return false;
3371       if (!isUndefOrEqual(BitI1, j))
3372         return false;
3373     }
3374   }
3375
3376   return true;
3377 }
3378
3379 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3380   SmallVector<int, 8> M;
3381   N->getMask(M);
3382   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3383 }
3384
3385 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3386 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3387 /// <2, 2, 3, 3>
3388 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3389   int NumElems = VT.getVectorNumElements();
3390   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3391     return false;
3392
3393   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3394     int BitI  = Mask[i];
3395     int BitI1 = Mask[i+1];
3396     if (!isUndefOrEqual(BitI, j))
3397       return false;
3398     if (!isUndefOrEqual(BitI1, j))
3399       return false;
3400   }
3401   return true;
3402 }
3403
3404 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3405   SmallVector<int, 8> M;
3406   N->getMask(M);
3407   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3408 }
3409
3410 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3411 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3412 /// MOVSD, and MOVD, i.e. setting the lowest element.
3413 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3414   if (VT.getVectorElementType().getSizeInBits() < 32)
3415     return false;
3416
3417   int NumElts = VT.getVectorNumElements();
3418
3419   if (!isUndefOrEqual(Mask[0], NumElts))
3420     return false;
3421
3422   for (int i = 1; i < NumElts; ++i)
3423     if (!isUndefOrEqual(Mask[i], i))
3424       return false;
3425
3426   return true;
3427 }
3428
3429 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3430   SmallVector<int, 8> M;
3431   N->getMask(M);
3432   return ::isMOVLMask(M, N->getValueType(0));
3433 }
3434
3435 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3436 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3437 /// element of vector 2 and the other elements to come from vector 1 in order.
3438 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3439                                bool V2IsSplat = false, bool V2IsUndef = false) {
3440   int NumOps = VT.getVectorNumElements();
3441   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3442     return false;
3443
3444   if (!isUndefOrEqual(Mask[0], 0))
3445     return false;
3446
3447   for (int i = 1; i < NumOps; ++i)
3448     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3449           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3450           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3451       return false;
3452
3453   return true;
3454 }
3455
3456 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3457                            bool V2IsUndef = false) {
3458   SmallVector<int, 8> M;
3459   N->getMask(M);
3460   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3461 }
3462
3463 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3464 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3465 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3466   if (N->getValueType(0).getVectorNumElements() != 4)
3467     return false;
3468
3469   // Expect 1, 1, 3, 3
3470   for (unsigned i = 0; i < 2; ++i) {
3471     int Elt = N->getMaskElt(i);
3472     if (Elt >= 0 && Elt != 1)
3473       return false;
3474   }
3475
3476   bool HasHi = false;
3477   for (unsigned i = 2; i < 4; ++i) {
3478     int Elt = N->getMaskElt(i);
3479     if (Elt >= 0 && Elt != 3)
3480       return false;
3481     if (Elt == 3)
3482       HasHi = true;
3483   }
3484   // Don't use movshdup if it can be done with a shufps.
3485   // FIXME: verify that matching u, u, 3, 3 is what we want.
3486   return HasHi;
3487 }
3488
3489 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3491 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3492   if (N->getValueType(0).getVectorNumElements() != 4)
3493     return false;
3494
3495   // Expect 0, 0, 2, 2
3496   for (unsigned i = 0; i < 2; ++i)
3497     if (N->getMaskElt(i) > 0)
3498       return false;
3499
3500   bool HasHi = false;
3501   for (unsigned i = 2; i < 4; ++i) {
3502     int Elt = N->getMaskElt(i);
3503     if (Elt >= 0 && Elt != 2)
3504       return false;
3505     if (Elt == 2)
3506       HasHi = true;
3507   }
3508   // Don't use movsldup if it can be done with a shufps.
3509   return HasHi;
3510 }
3511
3512 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3513 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3514 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3515   int e = N->getValueType(0).getVectorNumElements() / 2;
3516
3517   for (int i = 0; i < e; ++i)
3518     if (!isUndefOrEqual(N->getMaskElt(i), i))
3519       return false;
3520   for (int i = 0; i < e; ++i)
3521     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3522       return false;
3523   return true;
3524 }
3525
3526 /// isVEXTRACTF128Index - Return true if the specified
3527 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3528 /// suitable for input to VEXTRACTF128.
3529 bool X86::isVEXTRACTF128Index(SDNode *N) {
3530   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3531     return false;
3532
3533   // The index should be aligned on a 128-bit boundary.
3534   uint64_t Index =
3535     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3536
3537   unsigned VL = N->getValueType(0).getVectorNumElements();
3538   unsigned VBits = N->getValueType(0).getSizeInBits();
3539   unsigned ElSize = VBits / VL;
3540   bool Result = (Index * ElSize) % 128 == 0;
3541
3542   return Result;
3543 }
3544
3545 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3546 /// operand specifies a subvector insert that is suitable for input to
3547 /// VINSERTF128.
3548 bool X86::isVINSERTF128Index(SDNode *N) {
3549   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3550     return false;
3551
3552   // The index should be aligned on a 128-bit boundary.
3553   uint64_t Index =
3554     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3555
3556   unsigned VL = N->getValueType(0).getVectorNumElements();
3557   unsigned VBits = N->getValueType(0).getSizeInBits();
3558   unsigned ElSize = VBits / VL;
3559   bool Result = (Index * ElSize) % 128 == 0;
3560
3561   return Result;
3562 }
3563
3564 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3565 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3566 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3567   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3568   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3569
3570   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3571   unsigned Mask = 0;
3572   for (int i = 0; i < NumOperands; ++i) {
3573     int Val = SVOp->getMaskElt(NumOperands-i-1);
3574     if (Val < 0) Val = 0;
3575     if (Val >= NumOperands) Val -= NumOperands;
3576     Mask |= Val;
3577     if (i != NumOperands - 1)
3578       Mask <<= Shift;
3579   }
3580   return Mask;
3581 }
3582
3583 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3584 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3585 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3586   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3587   unsigned Mask = 0;
3588   // 8 nodes, but we only care about the last 4.
3589   for (unsigned i = 7; i >= 4; --i) {
3590     int Val = SVOp->getMaskElt(i);
3591     if (Val >= 0)
3592       Mask |= (Val - 4);
3593     if (i != 4)
3594       Mask <<= 2;
3595   }
3596   return Mask;
3597 }
3598
3599 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3600 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3601 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3602   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3603   unsigned Mask = 0;
3604   // 8 nodes, but we only care about the first 4.
3605   for (int i = 3; i >= 0; --i) {
3606     int Val = SVOp->getMaskElt(i);
3607     if (Val >= 0)
3608       Mask |= Val;
3609     if (i != 0)
3610       Mask <<= 2;
3611   }
3612   return Mask;
3613 }
3614
3615 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3616 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3617 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3618   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3619   EVT VVT = N->getValueType(0);
3620   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3621   int Val = 0;
3622
3623   unsigned i, e;
3624   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3625     Val = SVOp->getMaskElt(i);
3626     if (Val >= 0)
3627       break;
3628   }
3629   return (Val - i) * EltSize;
3630 }
3631
3632 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3633 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3634 /// instructions.
3635 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3636   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3637     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3638
3639   uint64_t Index =
3640     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3641
3642   EVT VecVT = N->getOperand(0).getValueType();
3643   EVT ElVT = VecVT.getVectorElementType();
3644
3645   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3646
3647   return Index / NumElemsPerChunk;
3648 }
3649
3650 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3651 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3652 /// instructions.
3653 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3654   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3655     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3656
3657   uint64_t Index =
3658     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3659
3660   EVT VecVT = N->getValueType(0);
3661   EVT ElVT = VecVT.getVectorElementType();
3662
3663   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3664
3665   return Index / NumElemsPerChunk;
3666 }
3667
3668 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3669 /// constant +0.0.
3670 bool X86::isZeroNode(SDValue Elt) {
3671   return ((isa<ConstantSDNode>(Elt) &&
3672            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3673           (isa<ConstantFPSDNode>(Elt) &&
3674            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3675 }
3676
3677 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3678 /// their permute mask.
3679 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3680                                     SelectionDAG &DAG) {
3681   EVT VT = SVOp->getValueType(0);
3682   unsigned NumElems = VT.getVectorNumElements();
3683   SmallVector<int, 8> MaskVec;
3684
3685   for (unsigned i = 0; i != NumElems; ++i) {
3686     int idx = SVOp->getMaskElt(i);
3687     if (idx < 0)
3688       MaskVec.push_back(idx);
3689     else if (idx < (int)NumElems)
3690       MaskVec.push_back(idx + NumElems);
3691     else
3692       MaskVec.push_back(idx - NumElems);
3693   }
3694   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3695                               SVOp->getOperand(0), &MaskVec[0]);
3696 }
3697
3698 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3699 /// the two vector operands have swapped position.
3700 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3701   unsigned NumElems = VT.getVectorNumElements();
3702   for (unsigned i = 0; i != NumElems; ++i) {
3703     int idx = Mask[i];
3704     if (idx < 0)
3705       continue;
3706     else if (idx < (int)NumElems)
3707       Mask[i] = idx + NumElems;
3708     else
3709       Mask[i] = idx - NumElems;
3710   }
3711 }
3712
3713 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3714 /// match movhlps. The lower half elements should come from upper half of
3715 /// V1 (and in order), and the upper half elements should come from the upper
3716 /// half of V2 (and in order).
3717 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3718   if (Op->getValueType(0).getVectorNumElements() != 4)
3719     return false;
3720   for (unsigned i = 0, e = 2; i != e; ++i)
3721     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3722       return false;
3723   for (unsigned i = 2; i != 4; ++i)
3724     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3725       return false;
3726   return true;
3727 }
3728
3729 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3730 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3731 /// required.
3732 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3733   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3734     return false;
3735   N = N->getOperand(0).getNode();
3736   if (!ISD::isNON_EXTLoad(N))
3737     return false;
3738   if (LD)
3739     *LD = cast<LoadSDNode>(N);
3740   return true;
3741 }
3742
3743 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3744 /// match movlp{s|d}. The lower half elements should come from lower half of
3745 /// V1 (and in order), and the upper half elements should come from the upper
3746 /// half of V2 (and in order). And since V1 will become the source of the
3747 /// MOVLP, it must be either a vector load or a scalar load to vector.
3748 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3749                                ShuffleVectorSDNode *Op) {
3750   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3751     return false;
3752   // Is V2 is a vector load, don't do this transformation. We will try to use
3753   // load folding shufps op.
3754   if (ISD::isNON_EXTLoad(V2))
3755     return false;
3756
3757   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3758
3759   if (NumElems != 2 && NumElems != 4)
3760     return false;
3761   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3762     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3763       return false;
3764   for (unsigned i = NumElems/2; i != NumElems; ++i)
3765     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3766       return false;
3767   return true;
3768 }
3769
3770 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3771 /// all the same.
3772 static bool isSplatVector(SDNode *N) {
3773   if (N->getOpcode() != ISD::BUILD_VECTOR)
3774     return false;
3775
3776   SDValue SplatValue = N->getOperand(0);
3777   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3778     if (N->getOperand(i) != SplatValue)
3779       return false;
3780   return true;
3781 }
3782
3783 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3784 /// to an zero vector.
3785 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3786 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3787   SDValue V1 = N->getOperand(0);
3788   SDValue V2 = N->getOperand(1);
3789   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3790   for (unsigned i = 0; i != NumElems; ++i) {
3791     int Idx = N->getMaskElt(i);
3792     if (Idx >= (int)NumElems) {
3793       unsigned Opc = V2.getOpcode();
3794       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3795         continue;
3796       if (Opc != ISD::BUILD_VECTOR ||
3797           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3798         return false;
3799     } else if (Idx >= 0) {
3800       unsigned Opc = V1.getOpcode();
3801       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3802         continue;
3803       if (Opc != ISD::BUILD_VECTOR ||
3804           !X86::isZeroNode(V1.getOperand(Idx)))
3805         return false;
3806     }
3807   }
3808   return true;
3809 }
3810
3811 /// getZeroVector - Returns a vector of specified type with all zero elements.
3812 ///
3813 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3814                              DebugLoc dl) {
3815   assert(VT.isVector() && "Expected a vector type");
3816
3817   // Always build SSE zero vectors as <4 x i32> bitcasted
3818   // to their dest type. This ensures they get CSE'd.
3819   SDValue Vec;
3820   if (VT.getSizeInBits() == 128) {  // SSE
3821     if (HasSSE2) {  // SSE2
3822       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3823       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3824     } else { // SSE1
3825       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3826       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3827     }
3828   } else if (VT.getSizeInBits() == 256) { // AVX
3829     // 256-bit logic and arithmetic instructions in AVX are
3830     // all floating-point, no support for integer ops. Default
3831     // to emitting fp zeroed vectors then.
3832     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3833     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3834     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3835   }
3836   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3837 }
3838
3839 /// getOnesVector - Returns a vector of specified type with all bits set.
3840 ///
3841 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3842   assert(VT.isVector() && "Expected a vector type");
3843
3844   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3845   // type.  This ensures they get CSE'd.
3846   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3847   SDValue Vec;
3848   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3849   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3850 }
3851
3852
3853 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3854 /// that point to V2 points to its first element.
3855 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3856   EVT VT = SVOp->getValueType(0);
3857   unsigned NumElems = VT.getVectorNumElements();
3858
3859   bool Changed = false;
3860   SmallVector<int, 8> MaskVec;
3861   SVOp->getMask(MaskVec);
3862
3863   for (unsigned i = 0; i != NumElems; ++i) {
3864     if (MaskVec[i] > (int)NumElems) {
3865       MaskVec[i] = NumElems;
3866       Changed = true;
3867     }
3868   }
3869   if (Changed)
3870     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3871                                 SVOp->getOperand(1), &MaskVec[0]);
3872   return SDValue(SVOp, 0);
3873 }
3874
3875 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3876 /// operation of specified width.
3877 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3878                        SDValue V2) {
3879   unsigned NumElems = VT.getVectorNumElements();
3880   SmallVector<int, 8> Mask;
3881   Mask.push_back(NumElems);
3882   for (unsigned i = 1; i != NumElems; ++i)
3883     Mask.push_back(i);
3884   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3885 }
3886
3887 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3888 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3889                           SDValue V2) {
3890   unsigned NumElems = VT.getVectorNumElements();
3891   SmallVector<int, 8> Mask;
3892   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3893     Mask.push_back(i);
3894     Mask.push_back(i + NumElems);
3895   }
3896   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3897 }
3898
3899 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3900 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3901                           SDValue V2) {
3902   unsigned NumElems = VT.getVectorNumElements();
3903   unsigned Half = NumElems/2;
3904   SmallVector<int, 8> Mask;
3905   for (unsigned i = 0; i != Half; ++i) {
3906     Mask.push_back(i + Half);
3907     Mask.push_back(i + NumElems + Half);
3908   }
3909   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3910 }
3911
3912 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3913 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3914   EVT PVT = MVT::v4f32;
3915   EVT VT = SV->getValueType(0);
3916   DebugLoc dl = SV->getDebugLoc();
3917   SDValue V1 = SV->getOperand(0);
3918   int NumElems = VT.getVectorNumElements();
3919   int EltNo = SV->getSplatIndex();
3920
3921   // unpack elements to the correct location
3922   while (NumElems > 4) {
3923     if (EltNo < NumElems/2) {
3924       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3925     } else {
3926       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3927       EltNo -= NumElems/2;
3928     }
3929     NumElems >>= 1;
3930   }
3931
3932   // Perform the splat.
3933   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3934   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3935   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3936   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3937 }
3938
3939 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3940 /// vector of zero or undef vector.  This produces a shuffle where the low
3941 /// element of V2 is swizzled into the zero/undef vector, landing at element
3942 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3943 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3944                                              bool isZero, bool HasSSE2,
3945                                              SelectionDAG &DAG) {
3946   EVT VT = V2.getValueType();
3947   SDValue V1 = isZero
3948     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3949   unsigned NumElems = VT.getVectorNumElements();
3950   SmallVector<int, 16> MaskVec;
3951   for (unsigned i = 0; i != NumElems; ++i)
3952     // If this is the insertion idx, put the low elt of V2 here.
3953     MaskVec.push_back(i == Idx ? NumElems : i);
3954   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3955 }
3956
3957 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3958 /// element of the result of the vector shuffle.
3959 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3960                                    unsigned Depth) {
3961   if (Depth == 6)
3962     return SDValue();  // Limit search depth.
3963
3964   SDValue V = SDValue(N, 0);
3965   EVT VT = V.getValueType();
3966   unsigned Opcode = V.getOpcode();
3967
3968   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3969   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3970     Index = SV->getMaskElt(Index);
3971
3972     if (Index < 0)
3973       return DAG.getUNDEF(VT.getVectorElementType());
3974
3975     int NumElems = VT.getVectorNumElements();
3976     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3977     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3978   }
3979
3980   // Recurse into target specific vector shuffles to find scalars.
3981   if (isTargetShuffle(Opcode)) {
3982     int NumElems = VT.getVectorNumElements();
3983     SmallVector<unsigned, 16> ShuffleMask;
3984     SDValue ImmN;
3985
3986     switch(Opcode) {
3987     case X86ISD::SHUFPS:
3988     case X86ISD::SHUFPD:
3989       ImmN = N->getOperand(N->getNumOperands()-1);
3990       DecodeSHUFPSMask(NumElems,
3991                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3992                        ShuffleMask);
3993       break;
3994     case X86ISD::PUNPCKHBW:
3995     case X86ISD::PUNPCKHWD:
3996     case X86ISD::PUNPCKHDQ:
3997     case X86ISD::PUNPCKHQDQ:
3998       DecodePUNPCKHMask(NumElems, ShuffleMask);
3999       break;
4000     case X86ISD::UNPCKHPS:
4001     case X86ISD::UNPCKHPD:
4002       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4003       break;
4004     case X86ISD::PUNPCKLBW:
4005     case X86ISD::PUNPCKLWD:
4006     case X86ISD::PUNPCKLDQ:
4007     case X86ISD::PUNPCKLQDQ:
4008       DecodePUNPCKLMask(VT, ShuffleMask);
4009       break;
4010     case X86ISD::UNPCKLPS:
4011     case X86ISD::UNPCKLPD:
4012     case X86ISD::VUNPCKLPS:
4013     case X86ISD::VUNPCKLPD:
4014     case X86ISD::VUNPCKLPSY:
4015     case X86ISD::VUNPCKLPDY:
4016       DecodeUNPCKLPMask(VT, ShuffleMask);
4017       break;
4018     case X86ISD::MOVHLPS:
4019       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4020       break;
4021     case X86ISD::MOVLHPS:
4022       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4023       break;
4024     case X86ISD::PSHUFD:
4025       ImmN = N->getOperand(N->getNumOperands()-1);
4026       DecodePSHUFMask(NumElems,
4027                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4028                       ShuffleMask);
4029       break;
4030     case X86ISD::PSHUFHW:
4031       ImmN = N->getOperand(N->getNumOperands()-1);
4032       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4033                         ShuffleMask);
4034       break;
4035     case X86ISD::PSHUFLW:
4036       ImmN = N->getOperand(N->getNumOperands()-1);
4037       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4038                         ShuffleMask);
4039       break;
4040     case X86ISD::MOVSS:
4041     case X86ISD::MOVSD: {
4042       // The index 0 always comes from the first element of the second source,
4043       // this is why MOVSS and MOVSD are used in the first place. The other
4044       // elements come from the other positions of the first source vector.
4045       unsigned OpNum = (Index == 0) ? 1 : 0;
4046       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4047                                  Depth+1);
4048     }
4049     default:
4050       assert("not implemented for target shuffle node");
4051       return SDValue();
4052     }
4053
4054     Index = ShuffleMask[Index];
4055     if (Index < 0)
4056       return DAG.getUNDEF(VT.getVectorElementType());
4057
4058     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4059     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4060                                Depth+1);
4061   }
4062
4063   // Actual nodes that may contain scalar elements
4064   if (Opcode == ISD::BITCAST) {
4065     V = V.getOperand(0);
4066     EVT SrcVT = V.getValueType();
4067     unsigned NumElems = VT.getVectorNumElements();
4068
4069     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4070       return SDValue();
4071   }
4072
4073   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4074     return (Index == 0) ? V.getOperand(0)
4075                           : DAG.getUNDEF(VT.getVectorElementType());
4076
4077   if (V.getOpcode() == ISD::BUILD_VECTOR)
4078     return V.getOperand(Index);
4079
4080   return SDValue();
4081 }
4082
4083 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4084 /// shuffle operation which come from a consecutively from a zero. The
4085 /// search can start in two different directions, from left or right.
4086 static
4087 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4088                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4089   int i = 0;
4090
4091   while (i < NumElems) {
4092     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4093     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4094     if (!(Elt.getNode() &&
4095          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4096       break;
4097     ++i;
4098   }
4099
4100   return i;
4101 }
4102
4103 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4104 /// MaskE correspond consecutively to elements from one of the vector operands,
4105 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4106 static
4107 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4108                               int OpIdx, int NumElems, unsigned &OpNum) {
4109   bool SeenV1 = false;
4110   bool SeenV2 = false;
4111
4112   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4113     int Idx = SVOp->getMaskElt(i);
4114     // Ignore undef indicies
4115     if (Idx < 0)
4116       continue;
4117
4118     if (Idx < NumElems)
4119       SeenV1 = true;
4120     else
4121       SeenV2 = true;
4122
4123     // Only accept consecutive elements from the same vector
4124     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4125       return false;
4126   }
4127
4128   OpNum = SeenV1 ? 0 : 1;
4129   return true;
4130 }
4131
4132 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4133 /// logical left shift of a vector.
4134 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4135                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4136   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4137   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4138               false /* check zeros from right */, DAG);
4139   unsigned OpSrc;
4140
4141   if (!NumZeros)
4142     return false;
4143
4144   // Considering the elements in the mask that are not consecutive zeros,
4145   // check if they consecutively come from only one of the source vectors.
4146   //
4147   //               V1 = {X, A, B, C}     0
4148   //                         \  \  \    /
4149   //   vector_shuffle V1, V2 <1, 2, 3, X>
4150   //
4151   if (!isShuffleMaskConsecutive(SVOp,
4152             0,                   // Mask Start Index
4153             NumElems-NumZeros-1, // Mask End Index
4154             NumZeros,            // Where to start looking in the src vector
4155             NumElems,            // Number of elements in vector
4156             OpSrc))              // Which source operand ?
4157     return false;
4158
4159   isLeft = false;
4160   ShAmt = NumZeros;
4161   ShVal = SVOp->getOperand(OpSrc);
4162   return true;
4163 }
4164
4165 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4166 /// logical left shift of a vector.
4167 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4168                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4169   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4170   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4171               true /* check zeros from left */, DAG);
4172   unsigned OpSrc;
4173
4174   if (!NumZeros)
4175     return false;
4176
4177   // Considering the elements in the mask that are not consecutive zeros,
4178   // check if they consecutively come from only one of the source vectors.
4179   //
4180   //                           0    { A, B, X, X } = V2
4181   //                          / \    /  /
4182   //   vector_shuffle V1, V2 <X, X, 4, 5>
4183   //
4184   if (!isShuffleMaskConsecutive(SVOp,
4185             NumZeros,     // Mask Start Index
4186             NumElems-1,   // Mask End Index
4187             0,            // Where to start looking in the src vector
4188             NumElems,     // Number of elements in vector
4189             OpSrc))       // Which source operand ?
4190     return false;
4191
4192   isLeft = true;
4193   ShAmt = NumZeros;
4194   ShVal = SVOp->getOperand(OpSrc);
4195   return true;
4196 }
4197
4198 /// isVectorShift - Returns true if the shuffle can be implemented as a
4199 /// logical left or right shift of a vector.
4200 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4201                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4202   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4203       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4204     return true;
4205
4206   return false;
4207 }
4208
4209 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4210 ///
4211 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4212                                        unsigned NumNonZero, unsigned NumZero,
4213                                        SelectionDAG &DAG,
4214                                        const TargetLowering &TLI) {
4215   if (NumNonZero > 8)
4216     return SDValue();
4217
4218   DebugLoc dl = Op.getDebugLoc();
4219   SDValue V(0, 0);
4220   bool First = true;
4221   for (unsigned i = 0; i < 16; ++i) {
4222     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4223     if (ThisIsNonZero && First) {
4224       if (NumZero)
4225         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4226       else
4227         V = DAG.getUNDEF(MVT::v8i16);
4228       First = false;
4229     }
4230
4231     if ((i & 1) != 0) {
4232       SDValue ThisElt(0, 0), LastElt(0, 0);
4233       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4234       if (LastIsNonZero) {
4235         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4236                               MVT::i16, Op.getOperand(i-1));
4237       }
4238       if (ThisIsNonZero) {
4239         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4240         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4241                               ThisElt, DAG.getConstant(8, MVT::i8));
4242         if (LastIsNonZero)
4243           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4244       } else
4245         ThisElt = LastElt;
4246
4247       if (ThisElt.getNode())
4248         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4249                         DAG.getIntPtrConstant(i/2));
4250     }
4251   }
4252
4253   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4254 }
4255
4256 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4257 ///
4258 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4259                                      unsigned NumNonZero, unsigned NumZero,
4260                                      SelectionDAG &DAG,
4261                                      const TargetLowering &TLI) {
4262   if (NumNonZero > 4)
4263     return SDValue();
4264
4265   DebugLoc dl = Op.getDebugLoc();
4266   SDValue V(0, 0);
4267   bool First = true;
4268   for (unsigned i = 0; i < 8; ++i) {
4269     bool isNonZero = (NonZeros & (1 << i)) != 0;
4270     if (isNonZero) {
4271       if (First) {
4272         if (NumZero)
4273           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4274         else
4275           V = DAG.getUNDEF(MVT::v8i16);
4276         First = false;
4277       }
4278       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4279                       MVT::v8i16, V, Op.getOperand(i),
4280                       DAG.getIntPtrConstant(i));
4281     }
4282   }
4283
4284   return V;
4285 }
4286
4287 /// getVShift - Return a vector logical shift node.
4288 ///
4289 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4290                          unsigned NumBits, SelectionDAG &DAG,
4291                          const TargetLowering &TLI, DebugLoc dl) {
4292   EVT ShVT = MVT::v2i64;
4293   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4294   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4295   return DAG.getNode(ISD::BITCAST, dl, VT,
4296                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4297                              DAG.getConstant(NumBits,
4298                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4299 }
4300
4301 SDValue
4302 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4303                                           SelectionDAG &DAG) const {
4304
4305   // Check if the scalar load can be widened into a vector load. And if
4306   // the address is "base + cst" see if the cst can be "absorbed" into
4307   // the shuffle mask.
4308   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4309     SDValue Ptr = LD->getBasePtr();
4310     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4311       return SDValue();
4312     EVT PVT = LD->getValueType(0);
4313     if (PVT != MVT::i32 && PVT != MVT::f32)
4314       return SDValue();
4315
4316     int FI = -1;
4317     int64_t Offset = 0;
4318     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4319       FI = FINode->getIndex();
4320       Offset = 0;
4321     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4322                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4323       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4324       Offset = Ptr.getConstantOperandVal(1);
4325       Ptr = Ptr.getOperand(0);
4326     } else {
4327       return SDValue();
4328     }
4329
4330     SDValue Chain = LD->getChain();
4331     // Make sure the stack object alignment is at least 16.
4332     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4333     if (DAG.InferPtrAlignment(Ptr) < 16) {
4334       if (MFI->isFixedObjectIndex(FI)) {
4335         // Can't change the alignment. FIXME: It's possible to compute
4336         // the exact stack offset and reference FI + adjust offset instead.
4337         // If someone *really* cares about this. That's the way to implement it.
4338         return SDValue();
4339       } else {
4340         MFI->setObjectAlignment(FI, 16);
4341       }
4342     }
4343
4344     // (Offset % 16) must be multiple of 4. Then address is then
4345     // Ptr + (Offset & ~15).
4346     if (Offset < 0)
4347       return SDValue();
4348     if ((Offset % 16) & 3)
4349       return SDValue();
4350     int64_t StartOffset = Offset & ~15;
4351     if (StartOffset)
4352       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4353                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4354
4355     int EltNo = (Offset - StartOffset) >> 2;
4356     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4357     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4358     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4359                              LD->getPointerInfo().getWithOffset(StartOffset),
4360                              false, false, 0);
4361     // Canonicalize it to a v4i32 shuffle.
4362     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4363     return DAG.getNode(ISD::BITCAST, dl, VT,
4364                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4365                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4366   }
4367
4368   return SDValue();
4369 }
4370
4371 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4372 /// vector of type 'VT', see if the elements can be replaced by a single large
4373 /// load which has the same value as a build_vector whose operands are 'elts'.
4374 ///
4375 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4376 ///
4377 /// FIXME: we'd also like to handle the case where the last elements are zero
4378 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4379 /// There's even a handy isZeroNode for that purpose.
4380 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4381                                         DebugLoc &DL, SelectionDAG &DAG) {
4382   EVT EltVT = VT.getVectorElementType();
4383   unsigned NumElems = Elts.size();
4384
4385   LoadSDNode *LDBase = NULL;
4386   unsigned LastLoadedElt = -1U;
4387
4388   // For each element in the initializer, see if we've found a load or an undef.
4389   // If we don't find an initial load element, or later load elements are
4390   // non-consecutive, bail out.
4391   for (unsigned i = 0; i < NumElems; ++i) {
4392     SDValue Elt = Elts[i];
4393
4394     if (!Elt.getNode() ||
4395         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4396       return SDValue();
4397     if (!LDBase) {
4398       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4399         return SDValue();
4400       LDBase = cast<LoadSDNode>(Elt.getNode());
4401       LastLoadedElt = i;
4402       continue;
4403     }
4404     if (Elt.getOpcode() == ISD::UNDEF)
4405       continue;
4406
4407     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4408     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4409       return SDValue();
4410     LastLoadedElt = i;
4411   }
4412
4413   // If we have found an entire vector of loads and undefs, then return a large
4414   // load of the entire vector width starting at the base pointer.  If we found
4415   // consecutive loads for the low half, generate a vzext_load node.
4416   if (LastLoadedElt == NumElems - 1) {
4417     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4418       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4419                          LDBase->getPointerInfo(),
4420                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4421     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4422                        LDBase->getPointerInfo(),
4423                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4424                        LDBase->getAlignment());
4425   } else if (NumElems == 4 && LastLoadedElt == 1) {
4426     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4427     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4428     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4429                                               Ops, 2, MVT::i32,
4430                                               LDBase->getMemOperand());
4431     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4432   }
4433   return SDValue();
4434 }
4435
4436 SDValue
4437 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4438   DebugLoc dl = Op.getDebugLoc();
4439
4440   EVT VT = Op.getValueType();
4441   EVT ExtVT = VT.getVectorElementType();
4442
4443   unsigned NumElems = Op.getNumOperands();
4444
4445   // For AVX-length vectors, build the individual 128-bit pieces and
4446   // use shuffles to put them in place.
4447   if (VT.getSizeInBits() > 256 &&
4448       Subtarget->hasAVX() &&
4449       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4450     SmallVector<SDValue, 8> V;
4451     V.resize(NumElems);
4452     for (unsigned i = 0; i < NumElems; ++i) {
4453       V[i] = Op.getOperand(i);
4454     }
4455
4456     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4457
4458     // Build the lower subvector.
4459     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4460     // Build the upper subvector.
4461     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4462                                 NumElems/2);
4463
4464     return ConcatVectors(Lower, Upper, DAG);
4465   }
4466
4467   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4468   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4469   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4470   // is present, so AllOnes is ignored.
4471   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4472       (Op.getValueType().getSizeInBits() != 256 &&
4473        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4474     // Canonicalize this to <4 x i32> (SSE) to
4475     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4476     // eliminated on x86-32 hosts.
4477     if (Op.getValueType() == MVT::v4i32)
4478       return Op;
4479
4480     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4481       return getOnesVector(Op.getValueType(), DAG, dl);
4482     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4483   }
4484
4485   unsigned EVTBits = ExtVT.getSizeInBits();
4486
4487   unsigned NumZero  = 0;
4488   unsigned NumNonZero = 0;
4489   unsigned NonZeros = 0;
4490   bool IsAllConstants = true;
4491   SmallSet<SDValue, 8> Values;
4492   for (unsigned i = 0; i < NumElems; ++i) {
4493     SDValue Elt = Op.getOperand(i);
4494     if (Elt.getOpcode() == ISD::UNDEF)
4495       continue;
4496     Values.insert(Elt);
4497     if (Elt.getOpcode() != ISD::Constant &&
4498         Elt.getOpcode() != ISD::ConstantFP)
4499       IsAllConstants = false;
4500     if (X86::isZeroNode(Elt))
4501       NumZero++;
4502     else {
4503       NonZeros |= (1 << i);
4504       NumNonZero++;
4505     }
4506   }
4507
4508   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4509   if (NumNonZero == 0)
4510     return DAG.getUNDEF(VT);
4511
4512   // Special case for single non-zero, non-undef, element.
4513   if (NumNonZero == 1) {
4514     unsigned Idx = CountTrailingZeros_32(NonZeros);
4515     SDValue Item = Op.getOperand(Idx);
4516
4517     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4518     // the value are obviously zero, truncate the value to i32 and do the
4519     // insertion that way.  Only do this if the value is non-constant or if the
4520     // value is a constant being inserted into element 0.  It is cheaper to do
4521     // a constant pool load than it is to do a movd + shuffle.
4522     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4523         (!IsAllConstants || Idx == 0)) {
4524       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4525         // Handle SSE only.
4526         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4527         EVT VecVT = MVT::v4i32;
4528         unsigned VecElts = 4;
4529
4530         // Truncate the value (which may itself be a constant) to i32, and
4531         // convert it to a vector with movd (S2V+shuffle to zero extend).
4532         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4533         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4534         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4535                                            Subtarget->hasSSE2(), DAG);
4536
4537         // Now we have our 32-bit value zero extended in the low element of
4538         // a vector.  If Idx != 0, swizzle it into place.
4539         if (Idx != 0) {
4540           SmallVector<int, 4> Mask;
4541           Mask.push_back(Idx);
4542           for (unsigned i = 1; i != VecElts; ++i)
4543             Mask.push_back(i);
4544           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4545                                       DAG.getUNDEF(Item.getValueType()),
4546                                       &Mask[0]);
4547         }
4548         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4549       }
4550     }
4551
4552     // If we have a constant or non-constant insertion into the low element of
4553     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4554     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4555     // depending on what the source datatype is.
4556     if (Idx == 0) {
4557       if (NumZero == 0) {
4558         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4559       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4560           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4561         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4562         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4563         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4564                                            DAG);
4565       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4566         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4567         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4568         EVT MiddleVT = MVT::v4i32;
4569         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4570         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4571                                            Subtarget->hasSSE2(), DAG);
4572         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4573       }
4574     }
4575
4576     // Is it a vector logical left shift?
4577     if (NumElems == 2 && Idx == 1 &&
4578         X86::isZeroNode(Op.getOperand(0)) &&
4579         !X86::isZeroNode(Op.getOperand(1))) {
4580       unsigned NumBits = VT.getSizeInBits();
4581       return getVShift(true, VT,
4582                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4583                                    VT, Op.getOperand(1)),
4584                        NumBits/2, DAG, *this, dl);
4585     }
4586
4587     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4588       return SDValue();
4589
4590     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4591     // is a non-constant being inserted into an element other than the low one,
4592     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4593     // movd/movss) to move this into the low element, then shuffle it into
4594     // place.
4595     if (EVTBits == 32) {
4596       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4597
4598       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4599       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4600                                          Subtarget->hasSSE2(), DAG);
4601       SmallVector<int, 8> MaskVec;
4602       for (unsigned i = 0; i < NumElems; i++)
4603         MaskVec.push_back(i == Idx ? 0 : 1);
4604       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4605     }
4606   }
4607
4608   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4609   if (Values.size() == 1) {
4610     if (EVTBits == 32) {
4611       // Instead of a shuffle like this:
4612       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4613       // Check if it's possible to issue this instead.
4614       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4615       unsigned Idx = CountTrailingZeros_32(NonZeros);
4616       SDValue Item = Op.getOperand(Idx);
4617       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4618         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4619     }
4620     return SDValue();
4621   }
4622
4623   // A vector full of immediates; various special cases are already
4624   // handled, so this is best done with a single constant-pool load.
4625   if (IsAllConstants)
4626     return SDValue();
4627
4628   // Let legalizer expand 2-wide build_vectors.
4629   if (EVTBits == 64) {
4630     if (NumNonZero == 1) {
4631       // One half is zero or undef.
4632       unsigned Idx = CountTrailingZeros_32(NonZeros);
4633       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4634                                  Op.getOperand(Idx));
4635       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4636                                          Subtarget->hasSSE2(), DAG);
4637     }
4638     return SDValue();
4639   }
4640
4641   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4642   if (EVTBits == 8 && NumElems == 16) {
4643     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4644                                         *this);
4645     if (V.getNode()) return V;
4646   }
4647
4648   if (EVTBits == 16 && NumElems == 8) {
4649     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4650                                       *this);
4651     if (V.getNode()) return V;
4652   }
4653
4654   // If element VT is == 32 bits, turn it into a number of shuffles.
4655   SmallVector<SDValue, 8> V;
4656   V.resize(NumElems);
4657   if (NumElems == 4 && NumZero > 0) {
4658     for (unsigned i = 0; i < 4; ++i) {
4659       bool isZero = !(NonZeros & (1 << i));
4660       if (isZero)
4661         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4662       else
4663         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4664     }
4665
4666     for (unsigned i = 0; i < 2; ++i) {
4667       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4668         default: break;
4669         case 0:
4670           V[i] = V[i*2];  // Must be a zero vector.
4671           break;
4672         case 1:
4673           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4674           break;
4675         case 2:
4676           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4677           break;
4678         case 3:
4679           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4680           break;
4681       }
4682     }
4683
4684     SmallVector<int, 8> MaskVec;
4685     bool Reverse = (NonZeros & 0x3) == 2;
4686     for (unsigned i = 0; i < 2; ++i)
4687       MaskVec.push_back(Reverse ? 1-i : i);
4688     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4689     for (unsigned i = 0; i < 2; ++i)
4690       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4691     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4692   }
4693
4694   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4695     // Check for a build vector of consecutive loads.
4696     for (unsigned i = 0; i < NumElems; ++i)
4697       V[i] = Op.getOperand(i);
4698
4699     // Check for elements which are consecutive loads.
4700     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4701     if (LD.getNode())
4702       return LD;
4703
4704     // For SSE 4.1, use insertps to put the high elements into the low element.
4705     if (getSubtarget()->hasSSE41()) {
4706       SDValue Result;
4707       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4708         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4709       else
4710         Result = DAG.getUNDEF(VT);
4711
4712       for (unsigned i = 1; i < NumElems; ++i) {
4713         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4714         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4715                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4716       }
4717       return Result;
4718     }
4719
4720     // Otherwise, expand into a number of unpckl*, start by extending each of
4721     // our (non-undef) elements to the full vector width with the element in the
4722     // bottom slot of the vector (which generates no code for SSE).
4723     for (unsigned i = 0; i < NumElems; ++i) {
4724       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4725         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4726       else
4727         V[i] = DAG.getUNDEF(VT);
4728     }
4729
4730     // Next, we iteratively mix elements, e.g. for v4f32:
4731     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4732     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4733     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4734     unsigned EltStride = NumElems >> 1;
4735     while (EltStride != 0) {
4736       for (unsigned i = 0; i < EltStride; ++i) {
4737         // If V[i+EltStride] is undef and this is the first round of mixing,
4738         // then it is safe to just drop this shuffle: V[i] is already in the
4739         // right place, the one element (since it's the first round) being
4740         // inserted as undef can be dropped.  This isn't safe for successive
4741         // rounds because they will permute elements within both vectors.
4742         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4743             EltStride == NumElems/2)
4744           continue;
4745
4746         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4747       }
4748       EltStride >>= 1;
4749     }
4750     return V[0];
4751   }
4752   return SDValue();
4753 }
4754
4755 SDValue
4756 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4757   // We support concatenate two MMX registers and place them in a MMX
4758   // register.  This is better than doing a stack convert.
4759   DebugLoc dl = Op.getDebugLoc();
4760   EVT ResVT = Op.getValueType();
4761   assert(Op.getNumOperands() == 2);
4762   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4763          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4764   int Mask[2];
4765   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4766   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4767   InVec = Op.getOperand(1);
4768   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4769     unsigned NumElts = ResVT.getVectorNumElements();
4770     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4771     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4772                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4773   } else {
4774     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4775     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4776     Mask[0] = 0; Mask[1] = 2;
4777     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4778   }
4779   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4780 }
4781
4782 // v8i16 shuffles - Prefer shuffles in the following order:
4783 // 1. [all]   pshuflw, pshufhw, optional move
4784 // 2. [ssse3] 1 x pshufb
4785 // 3. [ssse3] 2 x pshufb + 1 x por
4786 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4787 SDValue
4788 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4789                                             SelectionDAG &DAG) const {
4790   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4791   SDValue V1 = SVOp->getOperand(0);
4792   SDValue V2 = SVOp->getOperand(1);
4793   DebugLoc dl = SVOp->getDebugLoc();
4794   SmallVector<int, 8> MaskVals;
4795
4796   // Determine if more than 1 of the words in each of the low and high quadwords
4797   // of the result come from the same quadword of one of the two inputs.  Undef
4798   // mask values count as coming from any quadword, for better codegen.
4799   SmallVector<unsigned, 4> LoQuad(4);
4800   SmallVector<unsigned, 4> HiQuad(4);
4801   BitVector InputQuads(4);
4802   for (unsigned i = 0; i < 8; ++i) {
4803     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4804     int EltIdx = SVOp->getMaskElt(i);
4805     MaskVals.push_back(EltIdx);
4806     if (EltIdx < 0) {
4807       ++Quad[0];
4808       ++Quad[1];
4809       ++Quad[2];
4810       ++Quad[3];
4811       continue;
4812     }
4813     ++Quad[EltIdx / 4];
4814     InputQuads.set(EltIdx / 4);
4815   }
4816
4817   int BestLoQuad = -1;
4818   unsigned MaxQuad = 1;
4819   for (unsigned i = 0; i < 4; ++i) {
4820     if (LoQuad[i] > MaxQuad) {
4821       BestLoQuad = i;
4822       MaxQuad = LoQuad[i];
4823     }
4824   }
4825
4826   int BestHiQuad = -1;
4827   MaxQuad = 1;
4828   for (unsigned i = 0; i < 4; ++i) {
4829     if (HiQuad[i] > MaxQuad) {
4830       BestHiQuad = i;
4831       MaxQuad = HiQuad[i];
4832     }
4833   }
4834
4835   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4836   // of the two input vectors, shuffle them into one input vector so only a
4837   // single pshufb instruction is necessary. If There are more than 2 input
4838   // quads, disable the next transformation since it does not help SSSE3.
4839   bool V1Used = InputQuads[0] || InputQuads[1];
4840   bool V2Used = InputQuads[2] || InputQuads[3];
4841   if (Subtarget->hasSSSE3()) {
4842     if (InputQuads.count() == 2 && V1Used && V2Used) {
4843       BestLoQuad = InputQuads.find_first();
4844       BestHiQuad = InputQuads.find_next(BestLoQuad);
4845     }
4846     if (InputQuads.count() > 2) {
4847       BestLoQuad = -1;
4848       BestHiQuad = -1;
4849     }
4850   }
4851
4852   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4853   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4854   // words from all 4 input quadwords.
4855   SDValue NewV;
4856   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4857     SmallVector<int, 8> MaskV;
4858     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4859     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4860     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4861                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4862                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4863     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4864
4865     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4866     // source words for the shuffle, to aid later transformations.
4867     bool AllWordsInNewV = true;
4868     bool InOrder[2] = { true, true };
4869     for (unsigned i = 0; i != 8; ++i) {
4870       int idx = MaskVals[i];
4871       if (idx != (int)i)
4872         InOrder[i/4] = false;
4873       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4874         continue;
4875       AllWordsInNewV = false;
4876       break;
4877     }
4878
4879     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4880     if (AllWordsInNewV) {
4881       for (int i = 0; i != 8; ++i) {
4882         int idx = MaskVals[i];
4883         if (idx < 0)
4884           continue;
4885         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4886         if ((idx != i) && idx < 4)
4887           pshufhw = false;
4888         if ((idx != i) && idx > 3)
4889           pshuflw = false;
4890       }
4891       V1 = NewV;
4892       V2Used = false;
4893       BestLoQuad = 0;
4894       BestHiQuad = 1;
4895     }
4896
4897     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4898     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4899     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4900       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4901       unsigned TargetMask = 0;
4902       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4903                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4904       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4905                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4906       V1 = NewV.getOperand(0);
4907       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4908     }
4909   }
4910
4911   // If we have SSSE3, and all words of the result are from 1 input vector,
4912   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4913   // is present, fall back to case 4.
4914   if (Subtarget->hasSSSE3()) {
4915     SmallVector<SDValue,16> pshufbMask;
4916
4917     // If we have elements from both input vectors, set the high bit of the
4918     // shuffle mask element to zero out elements that come from V2 in the V1
4919     // mask, and elements that come from V1 in the V2 mask, so that the two
4920     // results can be OR'd together.
4921     bool TwoInputs = V1Used && V2Used;
4922     for (unsigned i = 0; i != 8; ++i) {
4923       int EltIdx = MaskVals[i] * 2;
4924       if (TwoInputs && (EltIdx >= 16)) {
4925         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4926         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4927         continue;
4928       }
4929       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4930       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4931     }
4932     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4933     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4934                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4935                                  MVT::v16i8, &pshufbMask[0], 16));
4936     if (!TwoInputs)
4937       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4938
4939     // Calculate the shuffle mask for the second input, shuffle it, and
4940     // OR it with the first shuffled input.
4941     pshufbMask.clear();
4942     for (unsigned i = 0; i != 8; ++i) {
4943       int EltIdx = MaskVals[i] * 2;
4944       if (EltIdx < 16) {
4945         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4946         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4947         continue;
4948       }
4949       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4950       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4951     }
4952     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4953     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4954                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4955                                  MVT::v16i8, &pshufbMask[0], 16));
4956     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4957     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4958   }
4959
4960   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4961   // and update MaskVals with new element order.
4962   BitVector InOrder(8);
4963   if (BestLoQuad >= 0) {
4964     SmallVector<int, 8> MaskV;
4965     for (int i = 0; i != 4; ++i) {
4966       int idx = MaskVals[i];
4967       if (idx < 0) {
4968         MaskV.push_back(-1);
4969         InOrder.set(i);
4970       } else if ((idx / 4) == BestLoQuad) {
4971         MaskV.push_back(idx & 3);
4972         InOrder.set(i);
4973       } else {
4974         MaskV.push_back(-1);
4975       }
4976     }
4977     for (unsigned i = 4; i != 8; ++i)
4978       MaskV.push_back(i);
4979     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4980                                 &MaskV[0]);
4981
4982     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4983       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4984                                NewV.getOperand(0),
4985                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4986                                DAG);
4987   }
4988
4989   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4990   // and update MaskVals with the new element order.
4991   if (BestHiQuad >= 0) {
4992     SmallVector<int, 8> MaskV;
4993     for (unsigned i = 0; i != 4; ++i)
4994       MaskV.push_back(i);
4995     for (unsigned i = 4; i != 8; ++i) {
4996       int idx = MaskVals[i];
4997       if (idx < 0) {
4998         MaskV.push_back(-1);
4999         InOrder.set(i);
5000       } else if ((idx / 4) == BestHiQuad) {
5001         MaskV.push_back((idx & 3) + 4);
5002         InOrder.set(i);
5003       } else {
5004         MaskV.push_back(-1);
5005       }
5006     }
5007     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5008                                 &MaskV[0]);
5009
5010     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5011       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5012                               NewV.getOperand(0),
5013                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5014                               DAG);
5015   }
5016
5017   // In case BestHi & BestLo were both -1, which means each quadword has a word
5018   // from each of the four input quadwords, calculate the InOrder bitvector now
5019   // before falling through to the insert/extract cleanup.
5020   if (BestLoQuad == -1 && BestHiQuad == -1) {
5021     NewV = V1;
5022     for (int i = 0; i != 8; ++i)
5023       if (MaskVals[i] < 0 || MaskVals[i] == i)
5024         InOrder.set(i);
5025   }
5026
5027   // The other elements are put in the right place using pextrw and pinsrw.
5028   for (unsigned i = 0; i != 8; ++i) {
5029     if (InOrder[i])
5030       continue;
5031     int EltIdx = MaskVals[i];
5032     if (EltIdx < 0)
5033       continue;
5034     SDValue ExtOp = (EltIdx < 8)
5035     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5036                   DAG.getIntPtrConstant(EltIdx))
5037     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5038                   DAG.getIntPtrConstant(EltIdx - 8));
5039     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5040                        DAG.getIntPtrConstant(i));
5041   }
5042   return NewV;
5043 }
5044
5045 // v16i8 shuffles - Prefer shuffles in the following order:
5046 // 1. [ssse3] 1 x pshufb
5047 // 2. [ssse3] 2 x pshufb + 1 x por
5048 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5049 static
5050 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5051                                  SelectionDAG &DAG,
5052                                  const X86TargetLowering &TLI) {
5053   SDValue V1 = SVOp->getOperand(0);
5054   SDValue V2 = SVOp->getOperand(1);
5055   DebugLoc dl = SVOp->getDebugLoc();
5056   SmallVector<int, 16> MaskVals;
5057   SVOp->getMask(MaskVals);
5058
5059   // If we have SSSE3, case 1 is generated when all result bytes come from
5060   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5061   // present, fall back to case 3.
5062   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5063   bool V1Only = true;
5064   bool V2Only = true;
5065   for (unsigned i = 0; i < 16; ++i) {
5066     int EltIdx = MaskVals[i];
5067     if (EltIdx < 0)
5068       continue;
5069     if (EltIdx < 16)
5070       V2Only = false;
5071     else
5072       V1Only = false;
5073   }
5074
5075   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5076   if (TLI.getSubtarget()->hasSSSE3()) {
5077     SmallVector<SDValue,16> pshufbMask;
5078
5079     // If all result elements are from one input vector, then only translate
5080     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5081     //
5082     // Otherwise, we have elements from both input vectors, and must zero out
5083     // elements that come from V2 in the first mask, and V1 in the second mask
5084     // so that we can OR them together.
5085     bool TwoInputs = !(V1Only || V2Only);
5086     for (unsigned i = 0; i != 16; ++i) {
5087       int EltIdx = MaskVals[i];
5088       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5089         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5090         continue;
5091       }
5092       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5093     }
5094     // If all the elements are from V2, assign it to V1 and return after
5095     // building the first pshufb.
5096     if (V2Only)
5097       V1 = V2;
5098     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5099                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5100                                  MVT::v16i8, &pshufbMask[0], 16));
5101     if (!TwoInputs)
5102       return V1;
5103
5104     // Calculate the shuffle mask for the second input, shuffle it, and
5105     // OR it with the first shuffled input.
5106     pshufbMask.clear();
5107     for (unsigned i = 0; i != 16; ++i) {
5108       int EltIdx = MaskVals[i];
5109       if (EltIdx < 16) {
5110         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5111         continue;
5112       }
5113       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5114     }
5115     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5116                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5117                                  MVT::v16i8, &pshufbMask[0], 16));
5118     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5119   }
5120
5121   // No SSSE3 - Calculate in place words and then fix all out of place words
5122   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5123   // the 16 different words that comprise the two doublequadword input vectors.
5124   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5125   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5126   SDValue NewV = V2Only ? V2 : V1;
5127   for (int i = 0; i != 8; ++i) {
5128     int Elt0 = MaskVals[i*2];
5129     int Elt1 = MaskVals[i*2+1];
5130
5131     // This word of the result is all undef, skip it.
5132     if (Elt0 < 0 && Elt1 < 0)
5133       continue;
5134
5135     // This word of the result is already in the correct place, skip it.
5136     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5137       continue;
5138     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5139       continue;
5140
5141     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5142     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5143     SDValue InsElt;
5144
5145     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5146     // using a single extract together, load it and store it.
5147     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5148       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5149                            DAG.getIntPtrConstant(Elt1 / 2));
5150       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5151                         DAG.getIntPtrConstant(i));
5152       continue;
5153     }
5154
5155     // If Elt1 is defined, extract it from the appropriate source.  If the
5156     // source byte is not also odd, shift the extracted word left 8 bits
5157     // otherwise clear the bottom 8 bits if we need to do an or.
5158     if (Elt1 >= 0) {
5159       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5160                            DAG.getIntPtrConstant(Elt1 / 2));
5161       if ((Elt1 & 1) == 0)
5162         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5163                              DAG.getConstant(8,
5164                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5165       else if (Elt0 >= 0)
5166         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5167                              DAG.getConstant(0xFF00, MVT::i16));
5168     }
5169     // If Elt0 is defined, extract it from the appropriate source.  If the
5170     // source byte is not also even, shift the extracted word right 8 bits. If
5171     // Elt1 was also defined, OR the extracted values together before
5172     // inserting them in the result.
5173     if (Elt0 >= 0) {
5174       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5175                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5176       if ((Elt0 & 1) != 0)
5177         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5178                               DAG.getConstant(8,
5179                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5180       else if (Elt1 >= 0)
5181         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5182                              DAG.getConstant(0x00FF, MVT::i16));
5183       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5184                          : InsElt0;
5185     }
5186     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5187                        DAG.getIntPtrConstant(i));
5188   }
5189   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5190 }
5191
5192 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5193 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5194 /// done when every pair / quad of shuffle mask elements point to elements in
5195 /// the right sequence. e.g.
5196 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5197 static
5198 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5199                                  SelectionDAG &DAG, DebugLoc dl) {
5200   EVT VT = SVOp->getValueType(0);
5201   SDValue V1 = SVOp->getOperand(0);
5202   SDValue V2 = SVOp->getOperand(1);
5203   unsigned NumElems = VT.getVectorNumElements();
5204   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5205   EVT NewVT;
5206   switch (VT.getSimpleVT().SimpleTy) {
5207   default: assert(false && "Unexpected!");
5208   case MVT::v4f32: NewVT = MVT::v2f64; break;
5209   case MVT::v4i32: NewVT = MVT::v2i64; break;
5210   case MVT::v8i16: NewVT = MVT::v4i32; break;
5211   case MVT::v16i8: NewVT = MVT::v4i32; break;
5212   }
5213
5214   int Scale = NumElems / NewWidth;
5215   SmallVector<int, 8> MaskVec;
5216   for (unsigned i = 0; i < NumElems; i += Scale) {
5217     int StartIdx = -1;
5218     for (int j = 0; j < Scale; ++j) {
5219       int EltIdx = SVOp->getMaskElt(i+j);
5220       if (EltIdx < 0)
5221         continue;
5222       if (StartIdx == -1)
5223         StartIdx = EltIdx - (EltIdx % Scale);
5224       if (EltIdx != StartIdx + j)
5225         return SDValue();
5226     }
5227     if (StartIdx == -1)
5228       MaskVec.push_back(-1);
5229     else
5230       MaskVec.push_back(StartIdx / Scale);
5231   }
5232
5233   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5234   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5235   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5236 }
5237
5238 /// getVZextMovL - Return a zero-extending vector move low node.
5239 ///
5240 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5241                             SDValue SrcOp, SelectionDAG &DAG,
5242                             const X86Subtarget *Subtarget, DebugLoc dl) {
5243   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5244     LoadSDNode *LD = NULL;
5245     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5246       LD = dyn_cast<LoadSDNode>(SrcOp);
5247     if (!LD) {
5248       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5249       // instead.
5250       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5251       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5252           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5253           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5254           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5255         // PR2108
5256         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5257         return DAG.getNode(ISD::BITCAST, dl, VT,
5258                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5259                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5260                                                    OpVT,
5261                                                    SrcOp.getOperand(0)
5262                                                           .getOperand(0))));
5263       }
5264     }
5265   }
5266
5267   return DAG.getNode(ISD::BITCAST, dl, VT,
5268                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5269                                  DAG.getNode(ISD::BITCAST, dl,
5270                                              OpVT, SrcOp)));
5271 }
5272
5273 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5274 /// shuffles.
5275 static SDValue
5276 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5277   SDValue V1 = SVOp->getOperand(0);
5278   SDValue V2 = SVOp->getOperand(1);
5279   DebugLoc dl = SVOp->getDebugLoc();
5280   EVT VT = SVOp->getValueType(0);
5281
5282   SmallVector<std::pair<int, int>, 8> Locs;
5283   Locs.resize(4);
5284   SmallVector<int, 8> Mask1(4U, -1);
5285   SmallVector<int, 8> PermMask;
5286   SVOp->getMask(PermMask);
5287
5288   unsigned NumHi = 0;
5289   unsigned NumLo = 0;
5290   for (unsigned i = 0; i != 4; ++i) {
5291     int Idx = PermMask[i];
5292     if (Idx < 0) {
5293       Locs[i] = std::make_pair(-1, -1);
5294     } else {
5295       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5296       if (Idx < 4) {
5297         Locs[i] = std::make_pair(0, NumLo);
5298         Mask1[NumLo] = Idx;
5299         NumLo++;
5300       } else {
5301         Locs[i] = std::make_pair(1, NumHi);
5302         if (2+NumHi < 4)
5303           Mask1[2+NumHi] = Idx;
5304         NumHi++;
5305       }
5306     }
5307   }
5308
5309   if (NumLo <= 2 && NumHi <= 2) {
5310     // If no more than two elements come from either vector. This can be
5311     // implemented with two shuffles. First shuffle gather the elements.
5312     // The second shuffle, which takes the first shuffle as both of its
5313     // vector operands, put the elements into the right order.
5314     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5315
5316     SmallVector<int, 8> Mask2(4U, -1);
5317
5318     for (unsigned i = 0; i != 4; ++i) {
5319       if (Locs[i].first == -1)
5320         continue;
5321       else {
5322         unsigned Idx = (i < 2) ? 0 : 4;
5323         Idx += Locs[i].first * 2 + Locs[i].second;
5324         Mask2[i] = Idx;
5325       }
5326     }
5327
5328     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5329   } else if (NumLo == 3 || NumHi == 3) {
5330     // Otherwise, we must have three elements from one vector, call it X, and
5331     // one element from the other, call it Y.  First, use a shufps to build an
5332     // intermediate vector with the one element from Y and the element from X
5333     // that will be in the same half in the final destination (the indexes don't
5334     // matter). Then, use a shufps to build the final vector, taking the half
5335     // containing the element from Y from the intermediate, and the other half
5336     // from X.
5337     if (NumHi == 3) {
5338       // Normalize it so the 3 elements come from V1.
5339       CommuteVectorShuffleMask(PermMask, VT);
5340       std::swap(V1, V2);
5341     }
5342
5343     // Find the element from V2.
5344     unsigned HiIndex;
5345     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5346       int Val = PermMask[HiIndex];
5347       if (Val < 0)
5348         continue;
5349       if (Val >= 4)
5350         break;
5351     }
5352
5353     Mask1[0] = PermMask[HiIndex];
5354     Mask1[1] = -1;
5355     Mask1[2] = PermMask[HiIndex^1];
5356     Mask1[3] = -1;
5357     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5358
5359     if (HiIndex >= 2) {
5360       Mask1[0] = PermMask[0];
5361       Mask1[1] = PermMask[1];
5362       Mask1[2] = HiIndex & 1 ? 6 : 4;
5363       Mask1[3] = HiIndex & 1 ? 4 : 6;
5364       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5365     } else {
5366       Mask1[0] = HiIndex & 1 ? 2 : 0;
5367       Mask1[1] = HiIndex & 1 ? 0 : 2;
5368       Mask1[2] = PermMask[2];
5369       Mask1[3] = PermMask[3];
5370       if (Mask1[2] >= 0)
5371         Mask1[2] += 4;
5372       if (Mask1[3] >= 0)
5373         Mask1[3] += 4;
5374       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5375     }
5376   }
5377
5378   // Break it into (shuffle shuffle_hi, shuffle_lo).
5379   Locs.clear();
5380   Locs.resize(4);
5381   SmallVector<int,8> LoMask(4U, -1);
5382   SmallVector<int,8> HiMask(4U, -1);
5383
5384   SmallVector<int,8> *MaskPtr = &LoMask;
5385   unsigned MaskIdx = 0;
5386   unsigned LoIdx = 0;
5387   unsigned HiIdx = 2;
5388   for (unsigned i = 0; i != 4; ++i) {
5389     if (i == 2) {
5390       MaskPtr = &HiMask;
5391       MaskIdx = 1;
5392       LoIdx = 0;
5393       HiIdx = 2;
5394     }
5395     int Idx = PermMask[i];
5396     if (Idx < 0) {
5397       Locs[i] = std::make_pair(-1, -1);
5398     } else if (Idx < 4) {
5399       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5400       (*MaskPtr)[LoIdx] = Idx;
5401       LoIdx++;
5402     } else {
5403       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5404       (*MaskPtr)[HiIdx] = Idx;
5405       HiIdx++;
5406     }
5407   }
5408
5409   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5410   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5411   SmallVector<int, 8> MaskOps;
5412   for (unsigned i = 0; i != 4; ++i) {
5413     if (Locs[i].first == -1) {
5414       MaskOps.push_back(-1);
5415     } else {
5416       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5417       MaskOps.push_back(Idx);
5418     }
5419   }
5420   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5421 }
5422
5423 static bool MayFoldVectorLoad(SDValue V) {
5424   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5425     V = V.getOperand(0);
5426   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5427     V = V.getOperand(0);
5428   if (MayFoldLoad(V))
5429     return true;
5430   return false;
5431 }
5432
5433 // FIXME: the version above should always be used. Since there's
5434 // a bug where several vector shuffles can't be folded because the
5435 // DAG is not updated during lowering and a node claims to have two
5436 // uses while it only has one, use this version, and let isel match
5437 // another instruction if the load really happens to have more than
5438 // one use. Remove this version after this bug get fixed.
5439 // rdar://8434668, PR8156
5440 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5441   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5442     V = V.getOperand(0);
5443   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5444     V = V.getOperand(0);
5445   if (ISD::isNormalLoad(V.getNode()))
5446     return true;
5447   return false;
5448 }
5449
5450 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5451 /// a vector extract, and if both can be later optimized into a single load.
5452 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5453 /// here because otherwise a target specific shuffle node is going to be
5454 /// emitted for this shuffle, and the optimization not done.
5455 /// FIXME: This is probably not the best approach, but fix the problem
5456 /// until the right path is decided.
5457 static
5458 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5459                                          const TargetLowering &TLI) {
5460   EVT VT = V.getValueType();
5461   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5462
5463   // Be sure that the vector shuffle is present in a pattern like this:
5464   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5465   if (!V.hasOneUse())
5466     return false;
5467
5468   SDNode *N = *V.getNode()->use_begin();
5469   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5470     return false;
5471
5472   SDValue EltNo = N->getOperand(1);
5473   if (!isa<ConstantSDNode>(EltNo))
5474     return false;
5475
5476   // If the bit convert changed the number of elements, it is unsafe
5477   // to examine the mask.
5478   bool HasShuffleIntoBitcast = false;
5479   if (V.getOpcode() == ISD::BITCAST) {
5480     EVT SrcVT = V.getOperand(0).getValueType();
5481     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5482       return false;
5483     V = V.getOperand(0);
5484     HasShuffleIntoBitcast = true;
5485   }
5486
5487   // Select the input vector, guarding against out of range extract vector.
5488   unsigned NumElems = VT.getVectorNumElements();
5489   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5490   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5491   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5492
5493   // Skip one more bit_convert if necessary
5494   if (V.getOpcode() == ISD::BITCAST)
5495     V = V.getOperand(0);
5496
5497   if (ISD::isNormalLoad(V.getNode())) {
5498     // Is the original load suitable?
5499     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5500
5501     // FIXME: avoid the multi-use bug that is preventing lots of
5502     // of foldings to be detected, this is still wrong of course, but
5503     // give the temporary desired behavior, and if it happens that
5504     // the load has real more uses, during isel it will not fold, and
5505     // will generate poor code.
5506     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5507       return false;
5508
5509     if (!HasShuffleIntoBitcast)
5510       return true;
5511
5512     // If there's a bitcast before the shuffle, check if the load type and
5513     // alignment is valid.
5514     unsigned Align = LN0->getAlignment();
5515     unsigned NewAlign =
5516       TLI.getTargetData()->getABITypeAlignment(
5517                                     VT.getTypeForEVT(*DAG.getContext()));
5518
5519     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5520       return false;
5521   }
5522
5523   return true;
5524 }
5525
5526 static
5527 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5528   EVT VT = Op.getValueType();
5529
5530   // Canonizalize to v2f64.
5531   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5532   return DAG.getNode(ISD::BITCAST, dl, VT,
5533                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5534                                           V1, DAG));
5535 }
5536
5537 static
5538 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5539                         bool HasSSE2) {
5540   SDValue V1 = Op.getOperand(0);
5541   SDValue V2 = Op.getOperand(1);
5542   EVT VT = Op.getValueType();
5543
5544   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5545
5546   if (HasSSE2 && VT == MVT::v2f64)
5547     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5548
5549   // v4f32 or v4i32
5550   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5551 }
5552
5553 static
5554 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5555   SDValue V1 = Op.getOperand(0);
5556   SDValue V2 = Op.getOperand(1);
5557   EVT VT = Op.getValueType();
5558
5559   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5560          "unsupported shuffle type");
5561
5562   if (V2.getOpcode() == ISD::UNDEF)
5563     V2 = V1;
5564
5565   // v4i32 or v4f32
5566   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5567 }
5568
5569 static
5570 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5571   SDValue V1 = Op.getOperand(0);
5572   SDValue V2 = Op.getOperand(1);
5573   EVT VT = Op.getValueType();
5574   unsigned NumElems = VT.getVectorNumElements();
5575
5576   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5577   // operand of these instructions is only memory, so check if there's a
5578   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5579   // same masks.
5580   bool CanFoldLoad = false;
5581
5582   // Trivial case, when V2 comes from a load.
5583   if (MayFoldVectorLoad(V2))
5584     CanFoldLoad = true;
5585
5586   // When V1 is a load, it can be folded later into a store in isel, example:
5587   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5588   //    turns into:
5589   //  (MOVLPSmr addr:$src1, VR128:$src2)
5590   // So, recognize this potential and also use MOVLPS or MOVLPD
5591   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5592     CanFoldLoad = true;
5593
5594   // Both of them can't be memory operations though.
5595   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5596     CanFoldLoad = false;
5597
5598   if (CanFoldLoad) {
5599     if (HasSSE2 && NumElems == 2)
5600       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5601
5602     if (NumElems == 4)
5603       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5604   }
5605
5606   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5607   // movl and movlp will both match v2i64, but v2i64 is never matched by
5608   // movl earlier because we make it strict to avoid messing with the movlp load
5609   // folding logic (see the code above getMOVLP call). Match it here then,
5610   // this is horrible, but will stay like this until we move all shuffle
5611   // matching to x86 specific nodes. Note that for the 1st condition all
5612   // types are matched with movsd.
5613   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5614     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5615   else if (HasSSE2)
5616     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5617
5618
5619   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5620
5621   // Invert the operand order and use SHUFPS to match it.
5622   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5623                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5624 }
5625
5626 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5627   switch(VT.getSimpleVT().SimpleTy) {
5628   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5629   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5630   case MVT::v4f32:
5631     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5632   case MVT::v2f64:
5633     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5634   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5635   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5636   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5637   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5638   default:
5639     llvm_unreachable("Unknown type for unpckl");
5640   }
5641   return 0;
5642 }
5643
5644 static inline unsigned getUNPCKHOpcode(EVT VT) {
5645   switch(VT.getSimpleVT().SimpleTy) {
5646   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5647   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5648   case MVT::v4f32: return X86ISD::UNPCKHPS;
5649   case MVT::v2f64: return X86ISD::UNPCKHPD;
5650   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5651   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5652   default:
5653     llvm_unreachable("Unknown type for unpckh");
5654   }
5655   return 0;
5656 }
5657
5658 static
5659 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5660                                const TargetLowering &TLI,
5661                                const X86Subtarget *Subtarget) {
5662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5663   EVT VT = Op.getValueType();
5664   DebugLoc dl = Op.getDebugLoc();
5665   SDValue V1 = Op.getOperand(0);
5666   SDValue V2 = Op.getOperand(1);
5667
5668   if (isZeroShuffle(SVOp))
5669     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5670
5671   // Handle splat operations
5672   if (SVOp->isSplat()) {
5673     // Special case, this is the only place now where it's
5674     // allowed to return a vector_shuffle operation without
5675     // using a target specific node, because *hopefully* it
5676     // will be optimized away by the dag combiner.
5677     if (VT.getVectorNumElements() <= 4 &&
5678         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5679       return Op;
5680
5681     // Handle splats by matching through known masks
5682     if (VT.getVectorNumElements() <= 4)
5683       return SDValue();
5684
5685     // Canonicalize all of the remaining to v4f32.
5686     return PromoteSplat(SVOp, DAG);
5687   }
5688
5689   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5690   // do it!
5691   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5692     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5693     if (NewOp.getNode())
5694       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5695   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5696     // FIXME: Figure out a cleaner way to do this.
5697     // Try to make use of movq to zero out the top part.
5698     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5699       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5700       if (NewOp.getNode()) {
5701         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5702           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5703                               DAG, Subtarget, dl);
5704       }
5705     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5706       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5707       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5708         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5709                             DAG, Subtarget, dl);
5710     }
5711   }
5712   return SDValue();
5713 }
5714
5715 SDValue
5716 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5718   SDValue V1 = Op.getOperand(0);
5719   SDValue V2 = Op.getOperand(1);
5720   EVT VT = Op.getValueType();
5721   DebugLoc dl = Op.getDebugLoc();
5722   unsigned NumElems = VT.getVectorNumElements();
5723   bool isMMX = VT.getSizeInBits() == 64;
5724   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5725   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5726   bool V1IsSplat = false;
5727   bool V2IsSplat = false;
5728   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5729   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5730   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5731   MachineFunction &MF = DAG.getMachineFunction();
5732   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5733
5734   // Shuffle operations on MMX not supported.
5735   if (isMMX)
5736     return Op;
5737
5738   // Vector shuffle lowering takes 3 steps:
5739   //
5740   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5741   //    narrowing and commutation of operands should be handled.
5742   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5743   //    shuffle nodes.
5744   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5745   //    so the shuffle can be broken into other shuffles and the legalizer can
5746   //    try the lowering again.
5747   //
5748   // The general ideia is that no vector_shuffle operation should be left to
5749   // be matched during isel, all of them must be converted to a target specific
5750   // node here.
5751
5752   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5753   // narrowing and commutation of operands should be handled. The actual code
5754   // doesn't include all of those, work in progress...
5755   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5756   if (NewOp.getNode())
5757     return NewOp;
5758
5759   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5760   // unpckh_undef). Only use pshufd if speed is more important than size.
5761   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5762     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5763       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5764   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5765     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5766       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5767
5768   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5769       RelaxedMayFoldVectorLoad(V1))
5770     return getMOVDDup(Op, dl, V1, DAG);
5771
5772   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5773     return getMOVHighToLow(Op, dl, DAG);
5774
5775   // Use to match splats
5776   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5777       (VT == MVT::v2f64 || VT == MVT::v2i64))
5778     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5779
5780   if (X86::isPSHUFDMask(SVOp)) {
5781     // The actual implementation will match the mask in the if above and then
5782     // during isel it can match several different instructions, not only pshufd
5783     // as its name says, sad but true, emulate the behavior for now...
5784     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5785         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5786
5787     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5788
5789     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5790       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5791
5792     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5793       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5794                                   TargetMask, DAG);
5795
5796     if (VT == MVT::v4f32)
5797       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5798                                   TargetMask, DAG);
5799   }
5800
5801   // Check if this can be converted into a logical shift.
5802   bool isLeft = false;
5803   unsigned ShAmt = 0;
5804   SDValue ShVal;
5805   bool isShift = getSubtarget()->hasSSE2() &&
5806     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5807   if (isShift && ShVal.hasOneUse()) {
5808     // If the shifted value has multiple uses, it may be cheaper to use
5809     // v_set0 + movlhps or movhlps, etc.
5810     EVT EltVT = VT.getVectorElementType();
5811     ShAmt *= EltVT.getSizeInBits();
5812     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5813   }
5814
5815   if (X86::isMOVLMask(SVOp)) {
5816     if (V1IsUndef)
5817       return V2;
5818     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5819       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5820     if (!X86::isMOVLPMask(SVOp)) {
5821       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5822         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5823
5824       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5825         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5826     }
5827   }
5828
5829   // FIXME: fold these into legal mask.
5830   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5831     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5832
5833   if (X86::isMOVHLPSMask(SVOp))
5834     return getMOVHighToLow(Op, dl, DAG);
5835
5836   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5837     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5838
5839   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5840     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5841
5842   if (X86::isMOVLPMask(SVOp))
5843     return getMOVLP(Op, dl, DAG, HasSSE2);
5844
5845   if (ShouldXformToMOVHLPS(SVOp) ||
5846       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5847     return CommuteVectorShuffle(SVOp, DAG);
5848
5849   if (isShift) {
5850     // No better options. Use a vshl / vsrl.
5851     EVT EltVT = VT.getVectorElementType();
5852     ShAmt *= EltVT.getSizeInBits();
5853     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5854   }
5855
5856   bool Commuted = false;
5857   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5858   // 1,1,1,1 -> v8i16 though.
5859   V1IsSplat = isSplatVector(V1.getNode());
5860   V2IsSplat = isSplatVector(V2.getNode());
5861
5862   // Canonicalize the splat or undef, if present, to be on the RHS.
5863   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5864     Op = CommuteVectorShuffle(SVOp, DAG);
5865     SVOp = cast<ShuffleVectorSDNode>(Op);
5866     V1 = SVOp->getOperand(0);
5867     V2 = SVOp->getOperand(1);
5868     std::swap(V1IsSplat, V2IsSplat);
5869     std::swap(V1IsUndef, V2IsUndef);
5870     Commuted = true;
5871   }
5872
5873   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5874     // Shuffling low element of v1 into undef, just return v1.
5875     if (V2IsUndef)
5876       return V1;
5877     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5878     // the instruction selector will not match, so get a canonical MOVL with
5879     // swapped operands to undo the commute.
5880     return getMOVL(DAG, dl, VT, V2, V1);
5881   }
5882
5883   if (X86::isUNPCKLMask(SVOp))
5884     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5885                                 dl, VT, V1, V2, DAG);
5886
5887   if (X86::isUNPCKHMask(SVOp))
5888     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5889
5890   if (V2IsSplat) {
5891     // Normalize mask so all entries that point to V2 points to its first
5892     // element then try to match unpck{h|l} again. If match, return a
5893     // new vector_shuffle with the corrected mask.
5894     SDValue NewMask = NormalizeMask(SVOp, DAG);
5895     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5896     if (NSVOp != SVOp) {
5897       if (X86::isUNPCKLMask(NSVOp, true)) {
5898         return NewMask;
5899       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5900         return NewMask;
5901       }
5902     }
5903   }
5904
5905   if (Commuted) {
5906     // Commute is back and try unpck* again.
5907     // FIXME: this seems wrong.
5908     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5909     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5910
5911     if (X86::isUNPCKLMask(NewSVOp))
5912       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5913                                   dl, VT, V2, V1, DAG);
5914
5915     if (X86::isUNPCKHMask(NewSVOp))
5916       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5917   }
5918
5919   // Normalize the node to match x86 shuffle ops if needed
5920   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5921     return CommuteVectorShuffle(SVOp, DAG);
5922
5923   // The checks below are all present in isShuffleMaskLegal, but they are
5924   // inlined here right now to enable us to directly emit target specific
5925   // nodes, and remove one by one until they don't return Op anymore.
5926   SmallVector<int, 16> M;
5927   SVOp->getMask(M);
5928
5929   if (isPALIGNRMask(M, VT, HasSSSE3))
5930     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5931                                 X86::getShufflePALIGNRImmediate(SVOp),
5932                                 DAG);
5933
5934   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5935       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5936     if (VT == MVT::v2f64) {
5937       X86ISD::NodeType Opcode =
5938         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5939       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5940     }
5941     if (VT == MVT::v2i64)
5942       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5943   }
5944
5945   if (isPSHUFHWMask(M, VT))
5946     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5947                                 X86::getShufflePSHUFHWImmediate(SVOp),
5948                                 DAG);
5949
5950   if (isPSHUFLWMask(M, VT))
5951     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5952                                 X86::getShufflePSHUFLWImmediate(SVOp),
5953                                 DAG);
5954
5955   if (isSHUFPMask(M, VT)) {
5956     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5957     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5958       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5959                                   TargetMask, DAG);
5960     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5961       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5962                                   TargetMask, DAG);
5963   }
5964
5965   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5966     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5967       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5968                                   dl, VT, V1, V1, DAG);
5969   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5970     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5971       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5972
5973   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5974   if (VT == MVT::v8i16) {
5975     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5976     if (NewOp.getNode())
5977       return NewOp;
5978   }
5979
5980   if (VT == MVT::v16i8) {
5981     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5982     if (NewOp.getNode())
5983       return NewOp;
5984   }
5985
5986   // Handle all 4 wide cases with a number of shuffles.
5987   if (NumElems == 4)
5988     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5989
5990   return SDValue();
5991 }
5992
5993 SDValue
5994 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5995                                                 SelectionDAG &DAG) const {
5996   EVT VT = Op.getValueType();
5997   DebugLoc dl = Op.getDebugLoc();
5998   if (VT.getSizeInBits() == 8) {
5999     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6000                                     Op.getOperand(0), Op.getOperand(1));
6001     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6002                                     DAG.getValueType(VT));
6003     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6004   } else if (VT.getSizeInBits() == 16) {
6005     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6006     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6007     if (Idx == 0)
6008       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6009                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6010                                      DAG.getNode(ISD::BITCAST, dl,
6011                                                  MVT::v4i32,
6012                                                  Op.getOperand(0)),
6013                                      Op.getOperand(1)));
6014     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6015                                     Op.getOperand(0), Op.getOperand(1));
6016     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6017                                     DAG.getValueType(VT));
6018     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6019   } else if (VT == MVT::f32) {
6020     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6021     // the result back to FR32 register. It's only worth matching if the
6022     // result has a single use which is a store or a bitcast to i32.  And in
6023     // the case of a store, it's not worth it if the index is a constant 0,
6024     // because a MOVSSmr can be used instead, which is smaller and faster.
6025     if (!Op.hasOneUse())
6026       return SDValue();
6027     SDNode *User = *Op.getNode()->use_begin();
6028     if ((User->getOpcode() != ISD::STORE ||
6029          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6030           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6031         (User->getOpcode() != ISD::BITCAST ||
6032          User->getValueType(0) != MVT::i32))
6033       return SDValue();
6034     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6035                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6036                                               Op.getOperand(0)),
6037                                               Op.getOperand(1));
6038     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6039   } else if (VT == MVT::i32) {
6040     // ExtractPS works with constant index.
6041     if (isa<ConstantSDNode>(Op.getOperand(1)))
6042       return Op;
6043   }
6044   return SDValue();
6045 }
6046
6047
6048 SDValue
6049 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6050                                            SelectionDAG &DAG) const {
6051   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6052     return SDValue();
6053
6054   SDValue Vec = Op.getOperand(0);
6055   EVT VecVT = Vec.getValueType();
6056
6057   // If this is a 256-bit vector result, first extract the 128-bit
6058   // vector and then extract from the 128-bit vector.
6059   if (VecVT.getSizeInBits() > 128) {
6060     DebugLoc dl = Op.getNode()->getDebugLoc();
6061     unsigned NumElems = VecVT.getVectorNumElements();
6062     SDValue Idx = Op.getOperand(1);
6063
6064     if (!isa<ConstantSDNode>(Idx))
6065       return SDValue();
6066
6067     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6068     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6069
6070     // Get the 128-bit vector.
6071     bool Upper = IdxVal >= ExtractNumElems;
6072     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6073
6074     // Extract from it.
6075     SDValue ScaledIdx = Idx;
6076     if (Upper)
6077       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6078                               DAG.getConstant(ExtractNumElems,
6079                                               Idx.getValueType()));
6080     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6081                        ScaledIdx);
6082   }
6083
6084   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6085
6086   if (Subtarget->hasSSE41()) {
6087     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6088     if (Res.getNode())
6089       return Res;
6090   }
6091
6092   EVT VT = Op.getValueType();
6093   DebugLoc dl = Op.getDebugLoc();
6094   // TODO: handle v16i8.
6095   if (VT.getSizeInBits() == 16) {
6096     SDValue Vec = Op.getOperand(0);
6097     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6098     if (Idx == 0)
6099       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6100                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6101                                      DAG.getNode(ISD::BITCAST, dl,
6102                                                  MVT::v4i32, Vec),
6103                                      Op.getOperand(1)));
6104     // Transform it so it match pextrw which produces a 32-bit result.
6105     EVT EltVT = MVT::i32;
6106     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6107                                     Op.getOperand(0), Op.getOperand(1));
6108     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6109                                     DAG.getValueType(VT));
6110     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6111   } else if (VT.getSizeInBits() == 32) {
6112     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6113     if (Idx == 0)
6114       return Op;
6115
6116     // SHUFPS the element to the lowest double word, then movss.
6117     int Mask[4] = { Idx, -1, -1, -1 };
6118     EVT VVT = Op.getOperand(0).getValueType();
6119     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6120                                        DAG.getUNDEF(VVT), Mask);
6121     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6122                        DAG.getIntPtrConstant(0));
6123   } else if (VT.getSizeInBits() == 64) {
6124     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6125     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6126     //        to match extract_elt for f64.
6127     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6128     if (Idx == 0)
6129       return Op;
6130
6131     // UNPCKHPD the element to the lowest double word, then movsd.
6132     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6133     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6134     int Mask[2] = { 1, -1 };
6135     EVT VVT = Op.getOperand(0).getValueType();
6136     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6137                                        DAG.getUNDEF(VVT), Mask);
6138     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6139                        DAG.getIntPtrConstant(0));
6140   }
6141
6142   return SDValue();
6143 }
6144
6145 SDValue
6146 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6147                                                SelectionDAG &DAG) const {
6148   EVT VT = Op.getValueType();
6149   EVT EltVT = VT.getVectorElementType();
6150   DebugLoc dl = Op.getDebugLoc();
6151
6152   SDValue N0 = Op.getOperand(0);
6153   SDValue N1 = Op.getOperand(1);
6154   SDValue N2 = Op.getOperand(2);
6155
6156   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6157       isa<ConstantSDNode>(N2)) {
6158     unsigned Opc;
6159     if (VT == MVT::v8i16)
6160       Opc = X86ISD::PINSRW;
6161     else if (VT == MVT::v16i8)
6162       Opc = X86ISD::PINSRB;
6163     else
6164       Opc = X86ISD::PINSRB;
6165
6166     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6167     // argument.
6168     if (N1.getValueType() != MVT::i32)
6169       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6170     if (N2.getValueType() != MVT::i32)
6171       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6172     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6173   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6174     // Bits [7:6] of the constant are the source select.  This will always be
6175     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6176     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6177     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6178     // Bits [5:4] of the constant are the destination select.  This is the
6179     //  value of the incoming immediate.
6180     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6181     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6182     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6183     // Create this as a scalar to vector..
6184     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6185     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6186   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6187     // PINSR* works with constant index.
6188     return Op;
6189   }
6190   return SDValue();
6191 }
6192
6193 SDValue
6194 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6195   EVT VT = Op.getValueType();
6196   EVT EltVT = VT.getVectorElementType();
6197
6198   DebugLoc dl = Op.getDebugLoc();
6199   SDValue N0 = Op.getOperand(0);
6200   SDValue N1 = Op.getOperand(1);
6201   SDValue N2 = Op.getOperand(2);
6202
6203   // If this is a 256-bit vector result, first insert into a 128-bit
6204   // vector and then insert into the 256-bit vector.
6205   if (VT.getSizeInBits() > 128) {
6206     if (!isa<ConstantSDNode>(N2))
6207       return SDValue();
6208
6209     // Get the 128-bit vector.
6210     unsigned NumElems = VT.getVectorNumElements();
6211     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6212     bool Upper = IdxVal >= NumElems / 2;
6213
6214     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6215
6216     // Insert into it.
6217     SDValue ScaledN2 = N2;
6218     if (Upper)
6219       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6220                              DAG.getConstant(NumElems /
6221                                              (VT.getSizeInBits() / 128),
6222                                              N2.getValueType()));
6223     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6224                      N1, ScaledN2);
6225
6226     // Insert the 128-bit vector
6227     // FIXME: Why UNDEF?
6228     return Insert128BitVector(N0, Op, N2, DAG, dl);
6229   }
6230
6231   if (Subtarget->hasSSE41())
6232     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6233
6234   if (EltVT == MVT::i8)
6235     return SDValue();
6236
6237   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6238     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6239     // as its second argument.
6240     if (N1.getValueType() != MVT::i32)
6241       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6242     if (N2.getValueType() != MVT::i32)
6243       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6244     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6245   }
6246   return SDValue();
6247 }
6248
6249 SDValue
6250 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6251   LLVMContext *Context = DAG.getContext();
6252   DebugLoc dl = Op.getDebugLoc();
6253   EVT OpVT = Op.getValueType();
6254
6255   // If this is a 256-bit vector result, first insert into a 128-bit
6256   // vector and then insert into the 256-bit vector.
6257   if (OpVT.getSizeInBits() > 128) {
6258     // Insert into a 128-bit vector.
6259     EVT VT128 = EVT::getVectorVT(*Context,
6260                                  OpVT.getVectorElementType(),
6261                                  OpVT.getVectorNumElements() / 2);
6262
6263     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6264
6265     // Insert the 128-bit vector.
6266     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6267                               DAG.getConstant(0, MVT::i32),
6268                               DAG, dl);
6269   }
6270
6271   if (Op.getValueType() == MVT::v1i64 &&
6272       Op.getOperand(0).getValueType() == MVT::i64)
6273     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6274
6275   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6276   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6277          "Expected an SSE type!");
6278   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6279                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6280 }
6281
6282 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6283 // a simple subregister reference or explicit instructions to grab
6284 // upper bits of a vector.
6285 SDValue
6286 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6287   if (Subtarget->hasAVX()) {
6288     DebugLoc dl = Op.getNode()->getDebugLoc();
6289     SDValue Vec = Op.getNode()->getOperand(0);
6290     SDValue Idx = Op.getNode()->getOperand(1);
6291
6292     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6293         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6294         return Extract128BitVector(Vec, Idx, DAG, dl);
6295     }
6296   }
6297   return SDValue();
6298 }
6299
6300 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6301 // simple superregister reference or explicit instructions to insert
6302 // the upper bits of a vector.
6303 SDValue
6304 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6305   if (Subtarget->hasAVX()) {
6306     DebugLoc dl = Op.getNode()->getDebugLoc();
6307     SDValue Vec = Op.getNode()->getOperand(0);
6308     SDValue SubVec = Op.getNode()->getOperand(1);
6309     SDValue Idx = Op.getNode()->getOperand(2);
6310
6311     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6312         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6313       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6314     }
6315   }
6316   return SDValue();
6317 }
6318
6319 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6320 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6321 // one of the above mentioned nodes. It has to be wrapped because otherwise
6322 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6323 // be used to form addressing mode. These wrapped nodes will be selected
6324 // into MOV32ri.
6325 SDValue
6326 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6327   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6328
6329   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6330   // global base reg.
6331   unsigned char OpFlag = 0;
6332   unsigned WrapperKind = X86ISD::Wrapper;
6333   CodeModel::Model M = getTargetMachine().getCodeModel();
6334
6335   if (Subtarget->isPICStyleRIPRel() &&
6336       (M == CodeModel::Small || M == CodeModel::Kernel))
6337     WrapperKind = X86ISD::WrapperRIP;
6338   else if (Subtarget->isPICStyleGOT())
6339     OpFlag = X86II::MO_GOTOFF;
6340   else if (Subtarget->isPICStyleStubPIC())
6341     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6342
6343   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6344                                              CP->getAlignment(),
6345                                              CP->getOffset(), OpFlag);
6346   DebugLoc DL = CP->getDebugLoc();
6347   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6348   // With PIC, the address is actually $g + Offset.
6349   if (OpFlag) {
6350     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6351                          DAG.getNode(X86ISD::GlobalBaseReg,
6352                                      DebugLoc(), getPointerTy()),
6353                          Result);
6354   }
6355
6356   return Result;
6357 }
6358
6359 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6360   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6361
6362   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6363   // global base reg.
6364   unsigned char OpFlag = 0;
6365   unsigned WrapperKind = X86ISD::Wrapper;
6366   CodeModel::Model M = getTargetMachine().getCodeModel();
6367
6368   if (Subtarget->isPICStyleRIPRel() &&
6369       (M == CodeModel::Small || M == CodeModel::Kernel))
6370     WrapperKind = X86ISD::WrapperRIP;
6371   else if (Subtarget->isPICStyleGOT())
6372     OpFlag = X86II::MO_GOTOFF;
6373   else if (Subtarget->isPICStyleStubPIC())
6374     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6375
6376   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6377                                           OpFlag);
6378   DebugLoc DL = JT->getDebugLoc();
6379   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6380
6381   // With PIC, the address is actually $g + Offset.
6382   if (OpFlag)
6383     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6384                          DAG.getNode(X86ISD::GlobalBaseReg,
6385                                      DebugLoc(), getPointerTy()),
6386                          Result);
6387
6388   return Result;
6389 }
6390
6391 SDValue
6392 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6393   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6394
6395   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6396   // global base reg.
6397   unsigned char OpFlag = 0;
6398   unsigned WrapperKind = X86ISD::Wrapper;
6399   CodeModel::Model M = getTargetMachine().getCodeModel();
6400
6401   if (Subtarget->isPICStyleRIPRel() &&
6402       (M == CodeModel::Small || M == CodeModel::Kernel))
6403     WrapperKind = X86ISD::WrapperRIP;
6404   else if (Subtarget->isPICStyleGOT())
6405     OpFlag = X86II::MO_GOTOFF;
6406   else if (Subtarget->isPICStyleStubPIC())
6407     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6408
6409   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6410
6411   DebugLoc DL = Op.getDebugLoc();
6412   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6413
6414
6415   // With PIC, the address is actually $g + Offset.
6416   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6417       !Subtarget->is64Bit()) {
6418     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6419                          DAG.getNode(X86ISD::GlobalBaseReg,
6420                                      DebugLoc(), getPointerTy()),
6421                          Result);
6422   }
6423
6424   return Result;
6425 }
6426
6427 SDValue
6428 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6429   // Create the TargetBlockAddressAddress node.
6430   unsigned char OpFlags =
6431     Subtarget->ClassifyBlockAddressReference();
6432   CodeModel::Model M = getTargetMachine().getCodeModel();
6433   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6434   DebugLoc dl = Op.getDebugLoc();
6435   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6436                                        /*isTarget=*/true, OpFlags);
6437
6438   if (Subtarget->isPICStyleRIPRel() &&
6439       (M == CodeModel::Small || M == CodeModel::Kernel))
6440     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6441   else
6442     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6443
6444   // With PIC, the address is actually $g + Offset.
6445   if (isGlobalRelativeToPICBase(OpFlags)) {
6446     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6447                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6448                          Result);
6449   }
6450
6451   return Result;
6452 }
6453
6454 SDValue
6455 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6456                                       int64_t Offset,
6457                                       SelectionDAG &DAG) const {
6458   // Create the TargetGlobalAddress node, folding in the constant
6459   // offset if it is legal.
6460   unsigned char OpFlags =
6461     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6462   CodeModel::Model M = getTargetMachine().getCodeModel();
6463   SDValue Result;
6464   if (OpFlags == X86II::MO_NO_FLAG &&
6465       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6466     // A direct static reference to a global.
6467     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6468     Offset = 0;
6469   } else {
6470     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6471   }
6472
6473   if (Subtarget->isPICStyleRIPRel() &&
6474       (M == CodeModel::Small || M == CodeModel::Kernel))
6475     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6476   else
6477     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6478
6479   // With PIC, the address is actually $g + Offset.
6480   if (isGlobalRelativeToPICBase(OpFlags)) {
6481     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6482                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6483                          Result);
6484   }
6485
6486   // For globals that require a load from a stub to get the address, emit the
6487   // load.
6488   if (isGlobalStubReference(OpFlags))
6489     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6490                          MachinePointerInfo::getGOT(), false, false, 0);
6491
6492   // If there was a non-zero offset that we didn't fold, create an explicit
6493   // addition for it.
6494   if (Offset != 0)
6495     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6496                          DAG.getConstant(Offset, getPointerTy()));
6497
6498   return Result;
6499 }
6500
6501 SDValue
6502 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6503   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6504   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6505   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6506 }
6507
6508 static SDValue
6509 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6510            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6511            unsigned char OperandFlags) {
6512   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6513   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6514   DebugLoc dl = GA->getDebugLoc();
6515   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6516                                            GA->getValueType(0),
6517                                            GA->getOffset(),
6518                                            OperandFlags);
6519   if (InFlag) {
6520     SDValue Ops[] = { Chain,  TGA, *InFlag };
6521     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6522   } else {
6523     SDValue Ops[]  = { Chain, TGA };
6524     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6525   }
6526
6527   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6528   MFI->setAdjustsStack(true);
6529
6530   SDValue Flag = Chain.getValue(1);
6531   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6532 }
6533
6534 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6535 static SDValue
6536 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6537                                 const EVT PtrVT) {
6538   SDValue InFlag;
6539   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6540   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6541                                      DAG.getNode(X86ISD::GlobalBaseReg,
6542                                                  DebugLoc(), PtrVT), InFlag);
6543   InFlag = Chain.getValue(1);
6544
6545   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6546 }
6547
6548 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6549 static SDValue
6550 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6551                                 const EVT PtrVT) {
6552   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6553                     X86::RAX, X86II::MO_TLSGD);
6554 }
6555
6556 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6557 // "local exec" model.
6558 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6559                                    const EVT PtrVT, TLSModel::Model model,
6560                                    bool is64Bit) {
6561   DebugLoc dl = GA->getDebugLoc();
6562
6563   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6564   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6565                                                          is64Bit ? 257 : 256));
6566
6567   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6568                                       DAG.getIntPtrConstant(0),
6569                                       MachinePointerInfo(Ptr), false, false, 0);
6570
6571   unsigned char OperandFlags = 0;
6572   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6573   // initialexec.
6574   unsigned WrapperKind = X86ISD::Wrapper;
6575   if (model == TLSModel::LocalExec) {
6576     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6577   } else if (is64Bit) {
6578     assert(model == TLSModel::InitialExec);
6579     OperandFlags = X86II::MO_GOTTPOFF;
6580     WrapperKind = X86ISD::WrapperRIP;
6581   } else {
6582     assert(model == TLSModel::InitialExec);
6583     OperandFlags = X86II::MO_INDNTPOFF;
6584   }
6585
6586   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6587   // exec)
6588   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6589                                            GA->getValueType(0),
6590                                            GA->getOffset(), OperandFlags);
6591   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6592
6593   if (model == TLSModel::InitialExec)
6594     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6595                          MachinePointerInfo::getGOT(), false, false, 0);
6596
6597   // The address of the thread local variable is the add of the thread
6598   // pointer with the offset of the variable.
6599   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6600 }
6601
6602 SDValue
6603 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6604
6605   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6606   const GlobalValue *GV = GA->getGlobal();
6607
6608   if (Subtarget->isTargetELF()) {
6609     // TODO: implement the "local dynamic" model
6610     // TODO: implement the "initial exec"model for pic executables
6611
6612     // If GV is an alias then use the aliasee for determining
6613     // thread-localness.
6614     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6615       GV = GA->resolveAliasedGlobal(false);
6616
6617     TLSModel::Model model
6618       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6619
6620     switch (model) {
6621       case TLSModel::GeneralDynamic:
6622       case TLSModel::LocalDynamic: // not implemented
6623         if (Subtarget->is64Bit())
6624           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6625         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6626
6627       case TLSModel::InitialExec:
6628       case TLSModel::LocalExec:
6629         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6630                                    Subtarget->is64Bit());
6631     }
6632   } else if (Subtarget->isTargetDarwin()) {
6633     // Darwin only has one model of TLS.  Lower to that.
6634     unsigned char OpFlag = 0;
6635     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6636                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6637
6638     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6639     // global base reg.
6640     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6641                   !Subtarget->is64Bit();
6642     if (PIC32)
6643       OpFlag = X86II::MO_TLVP_PIC_BASE;
6644     else
6645       OpFlag = X86II::MO_TLVP;
6646     DebugLoc DL = Op.getDebugLoc();
6647     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6648                                                 GA->getValueType(0),
6649                                                 GA->getOffset(), OpFlag);
6650     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6651
6652     // With PIC32, the address is actually $g + Offset.
6653     if (PIC32)
6654       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6655                            DAG.getNode(X86ISD::GlobalBaseReg,
6656                                        DebugLoc(), getPointerTy()),
6657                            Offset);
6658
6659     // Lowering the machine isd will make sure everything is in the right
6660     // location.
6661     SDValue Chain = DAG.getEntryNode();
6662     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6663     SDValue Args[] = { Chain, Offset };
6664     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6665
6666     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6667     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6668     MFI->setAdjustsStack(true);
6669
6670     // And our return value (tls address) is in the standard call return value
6671     // location.
6672     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6673     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6674   }
6675
6676   assert(false &&
6677          "TLS not implemented for this target.");
6678
6679   llvm_unreachable("Unreachable");
6680   return SDValue();
6681 }
6682
6683
6684 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6685 /// take a 2 x i32 value to shift plus a shift amount.
6686 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6687   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6688   EVT VT = Op.getValueType();
6689   unsigned VTBits = VT.getSizeInBits();
6690   DebugLoc dl = Op.getDebugLoc();
6691   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6692   SDValue ShOpLo = Op.getOperand(0);
6693   SDValue ShOpHi = Op.getOperand(1);
6694   SDValue ShAmt  = Op.getOperand(2);
6695   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6696                                      DAG.getConstant(VTBits - 1, MVT::i8))
6697                        : DAG.getConstant(0, VT);
6698
6699   SDValue Tmp2, Tmp3;
6700   if (Op.getOpcode() == ISD::SHL_PARTS) {
6701     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6702     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6703   } else {
6704     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6705     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6706   }
6707
6708   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6709                                 DAG.getConstant(VTBits, MVT::i8));
6710   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6711                              AndNode, DAG.getConstant(0, MVT::i8));
6712
6713   SDValue Hi, Lo;
6714   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6715   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6716   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6717
6718   if (Op.getOpcode() == ISD::SHL_PARTS) {
6719     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6720     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6721   } else {
6722     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6723     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6724   }
6725
6726   SDValue Ops[2] = { Lo, Hi };
6727   return DAG.getMergeValues(Ops, 2, dl);
6728 }
6729
6730 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6731                                            SelectionDAG &DAG) const {
6732   EVT SrcVT = Op.getOperand(0).getValueType();
6733
6734   if (SrcVT.isVector())
6735     return SDValue();
6736
6737   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6738          "Unknown SINT_TO_FP to lower!");
6739
6740   // These are really Legal; return the operand so the caller accepts it as
6741   // Legal.
6742   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6743     return Op;
6744   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6745       Subtarget->is64Bit()) {
6746     return Op;
6747   }
6748
6749   DebugLoc dl = Op.getDebugLoc();
6750   unsigned Size = SrcVT.getSizeInBits()/8;
6751   MachineFunction &MF = DAG.getMachineFunction();
6752   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6753   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6754   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6755                                StackSlot,
6756                                MachinePointerInfo::getFixedStack(SSFI),
6757                                false, false, 0);
6758   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6759 }
6760
6761 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6762                                      SDValue StackSlot,
6763                                      SelectionDAG &DAG) const {
6764   // Build the FILD
6765   DebugLoc DL = Op.getDebugLoc();
6766   SDVTList Tys;
6767   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6768   if (useSSE)
6769     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6770   else
6771     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6772
6773   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6774
6775   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6776   MachineMemOperand *MMO;
6777   if (FI) {
6778     int SSFI = FI->getIndex();
6779     MMO =
6780       DAG.getMachineFunction()
6781       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6782                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6783   } else {
6784     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6785     StackSlot = StackSlot.getOperand(1);
6786   }
6787   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6788   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6789                                            X86ISD::FILD, DL,
6790                                            Tys, Ops, array_lengthof(Ops),
6791                                            SrcVT, MMO);
6792
6793   if (useSSE) {
6794     Chain = Result.getValue(1);
6795     SDValue InFlag = Result.getValue(2);
6796
6797     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6798     // shouldn't be necessary except that RFP cannot be live across
6799     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6800     MachineFunction &MF = DAG.getMachineFunction();
6801     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6802     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6803     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6804     Tys = DAG.getVTList(MVT::Other);
6805     SDValue Ops[] = {
6806       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6807     };
6808     MachineMemOperand *MMO =
6809       DAG.getMachineFunction()
6810       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6811                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6812
6813     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6814                                     Ops, array_lengthof(Ops),
6815                                     Op.getValueType(), MMO);
6816     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6817                          MachinePointerInfo::getFixedStack(SSFI),
6818                          false, false, 0);
6819   }
6820
6821   return Result;
6822 }
6823
6824 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6825 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6826                                                SelectionDAG &DAG) const {
6827   // This algorithm is not obvious. Here it is in C code, more or less:
6828   /*
6829     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6830       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6831       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6832
6833       // Copy ints to xmm registers.
6834       __m128i xh = _mm_cvtsi32_si128( hi );
6835       __m128i xl = _mm_cvtsi32_si128( lo );
6836
6837       // Combine into low half of a single xmm register.
6838       __m128i x = _mm_unpacklo_epi32( xh, xl );
6839       __m128d d;
6840       double sd;
6841
6842       // Merge in appropriate exponents to give the integer bits the right
6843       // magnitude.
6844       x = _mm_unpacklo_epi32( x, exp );
6845
6846       // Subtract away the biases to deal with the IEEE-754 double precision
6847       // implicit 1.
6848       d = _mm_sub_pd( (__m128d) x, bias );
6849
6850       // All conversions up to here are exact. The correctly rounded result is
6851       // calculated using the current rounding mode using the following
6852       // horizontal add.
6853       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6854       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6855                                 // store doesn't really need to be here (except
6856                                 // maybe to zero the other double)
6857       return sd;
6858     }
6859   */
6860
6861   DebugLoc dl = Op.getDebugLoc();
6862   LLVMContext *Context = DAG.getContext();
6863
6864   // Build some magic constants.
6865   std::vector<Constant*> CV0;
6866   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6867   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6868   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6869   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6870   Constant *C0 = ConstantVector::get(CV0);
6871   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6872
6873   std::vector<Constant*> CV1;
6874   CV1.push_back(
6875     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6876   CV1.push_back(
6877     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6878   Constant *C1 = ConstantVector::get(CV1);
6879   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6880
6881   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6882                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6883                                         Op.getOperand(0),
6884                                         DAG.getIntPtrConstant(1)));
6885   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6886                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6887                                         Op.getOperand(0),
6888                                         DAG.getIntPtrConstant(0)));
6889   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6890   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6891                               MachinePointerInfo::getConstantPool(),
6892                               false, false, 16);
6893   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6894   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6895   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6896                               MachinePointerInfo::getConstantPool(),
6897                               false, false, 16);
6898   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6899
6900   // Add the halves; easiest way is to swap them into another reg first.
6901   int ShufMask[2] = { 1, -1 };
6902   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6903                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6904   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6905   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6906                      DAG.getIntPtrConstant(0));
6907 }
6908
6909 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6910 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6911                                                SelectionDAG &DAG) const {
6912   DebugLoc dl = Op.getDebugLoc();
6913   // FP constant to bias correct the final result.
6914   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6915                                    MVT::f64);
6916
6917   // Load the 32-bit value into an XMM register.
6918   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6919                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6920                                          Op.getOperand(0),
6921                                          DAG.getIntPtrConstant(0)));
6922
6923   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6924                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6925                      DAG.getIntPtrConstant(0));
6926
6927   // Or the load with the bias.
6928   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6929                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6930                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6931                                                    MVT::v2f64, Load)),
6932                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6933                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6934                                                    MVT::v2f64, Bias)));
6935   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6936                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6937                    DAG.getIntPtrConstant(0));
6938
6939   // Subtract the bias.
6940   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6941
6942   // Handle final rounding.
6943   EVT DestVT = Op.getValueType();
6944
6945   if (DestVT.bitsLT(MVT::f64)) {
6946     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6947                        DAG.getIntPtrConstant(0));
6948   } else if (DestVT.bitsGT(MVT::f64)) {
6949     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6950   }
6951
6952   // Handle final rounding.
6953   return Sub;
6954 }
6955
6956 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6957                                            SelectionDAG &DAG) const {
6958   SDValue N0 = Op.getOperand(0);
6959   DebugLoc dl = Op.getDebugLoc();
6960
6961   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6962   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6963   // the optimization here.
6964   if (DAG.SignBitIsZero(N0))
6965     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6966
6967   EVT SrcVT = N0.getValueType();
6968   EVT DstVT = Op.getValueType();
6969   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6970     return LowerUINT_TO_FP_i64(Op, DAG);
6971   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6972     return LowerUINT_TO_FP_i32(Op, DAG);
6973
6974   // Make a 64-bit buffer, and use it to build an FILD.
6975   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6976   if (SrcVT == MVT::i32) {
6977     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6978     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6979                                      getPointerTy(), StackSlot, WordOff);
6980     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6981                                   StackSlot, MachinePointerInfo(),
6982                                   false, false, 0);
6983     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6984                                   OffsetSlot, MachinePointerInfo(),
6985                                   false, false, 0);
6986     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6987     return Fild;
6988   }
6989
6990   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6991   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6992                                 StackSlot, MachinePointerInfo(),
6993                                false, false, 0);
6994   // For i64 source, we need to add the appropriate power of 2 if the input
6995   // was negative.  This is the same as the optimization in
6996   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6997   // we must be careful to do the computation in x87 extended precision, not
6998   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6999   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7000   MachineMemOperand *MMO =
7001     DAG.getMachineFunction()
7002     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7003                           MachineMemOperand::MOLoad, 8, 8);
7004
7005   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7006   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7007   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7008                                          MVT::i64, MMO);
7009
7010   APInt FF(32, 0x5F800000ULL);
7011
7012   // Check whether the sign bit is set.
7013   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7014                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7015                                  ISD::SETLT);
7016
7017   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7018   SDValue FudgePtr = DAG.getConstantPool(
7019                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7020                                          getPointerTy());
7021
7022   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7023   SDValue Zero = DAG.getIntPtrConstant(0);
7024   SDValue Four = DAG.getIntPtrConstant(4);
7025   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7026                                Zero, Four);
7027   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7028
7029   // Load the value out, extending it from f32 to f80.
7030   // FIXME: Avoid the extend by constructing the right constant pool?
7031   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7032                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7033                                  MVT::f32, false, false, 4);
7034   // Extend everything to 80 bits to force it to be done on x87.
7035   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7036   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7037 }
7038
7039 std::pair<SDValue,SDValue> X86TargetLowering::
7040 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7041   DebugLoc DL = Op.getDebugLoc();
7042
7043   EVT DstTy = Op.getValueType();
7044
7045   if (!IsSigned) {
7046     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7047     DstTy = MVT::i64;
7048   }
7049
7050   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7051          DstTy.getSimpleVT() >= MVT::i16 &&
7052          "Unknown FP_TO_SINT to lower!");
7053
7054   // These are really Legal.
7055   if (DstTy == MVT::i32 &&
7056       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7057     return std::make_pair(SDValue(), SDValue());
7058   if (Subtarget->is64Bit() &&
7059       DstTy == MVT::i64 &&
7060       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7061     return std::make_pair(SDValue(), SDValue());
7062
7063   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7064   // stack slot.
7065   MachineFunction &MF = DAG.getMachineFunction();
7066   unsigned MemSize = DstTy.getSizeInBits()/8;
7067   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7068   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7069
7070
7071
7072   unsigned Opc;
7073   switch (DstTy.getSimpleVT().SimpleTy) {
7074   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7075   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7076   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7077   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7078   }
7079
7080   SDValue Chain = DAG.getEntryNode();
7081   SDValue Value = Op.getOperand(0);
7082   EVT TheVT = Op.getOperand(0).getValueType();
7083   if (isScalarFPTypeInSSEReg(TheVT)) {
7084     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7085     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7086                          MachinePointerInfo::getFixedStack(SSFI),
7087                          false, false, 0);
7088     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7089     SDValue Ops[] = {
7090       Chain, StackSlot, DAG.getValueType(TheVT)
7091     };
7092
7093     MachineMemOperand *MMO =
7094       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7095                               MachineMemOperand::MOLoad, MemSize, MemSize);
7096     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7097                                     DstTy, MMO);
7098     Chain = Value.getValue(1);
7099     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7100     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7101   }
7102
7103   MachineMemOperand *MMO =
7104     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7105                             MachineMemOperand::MOStore, MemSize, MemSize);
7106
7107   // Build the FP_TO_INT*_IN_MEM
7108   SDValue Ops[] = { Chain, Value, StackSlot };
7109   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7110                                          Ops, 3, DstTy, MMO);
7111
7112   return std::make_pair(FIST, StackSlot);
7113 }
7114
7115 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7116                                            SelectionDAG &DAG) const {
7117   if (Op.getValueType().isVector())
7118     return SDValue();
7119
7120   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7121   SDValue FIST = Vals.first, StackSlot = Vals.second;
7122   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7123   if (FIST.getNode() == 0) return Op;
7124
7125   // Load the result.
7126   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7127                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7128 }
7129
7130 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7131                                            SelectionDAG &DAG) const {
7132   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7133   SDValue FIST = Vals.first, StackSlot = Vals.second;
7134   assert(FIST.getNode() && "Unexpected failure");
7135
7136   // Load the result.
7137   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7138                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7139 }
7140
7141 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7142                                      SelectionDAG &DAG) const {
7143   LLVMContext *Context = DAG.getContext();
7144   DebugLoc dl = Op.getDebugLoc();
7145   EVT VT = Op.getValueType();
7146   EVT EltVT = VT;
7147   if (VT.isVector())
7148     EltVT = VT.getVectorElementType();
7149   std::vector<Constant*> CV;
7150   if (EltVT == MVT::f64) {
7151     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7152     CV.push_back(C);
7153     CV.push_back(C);
7154   } else {
7155     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7156     CV.push_back(C);
7157     CV.push_back(C);
7158     CV.push_back(C);
7159     CV.push_back(C);
7160   }
7161   Constant *C = ConstantVector::get(CV);
7162   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7163   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7164                              MachinePointerInfo::getConstantPool(),
7165                              false, false, 16);
7166   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7167 }
7168
7169 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7170   LLVMContext *Context = DAG.getContext();
7171   DebugLoc dl = Op.getDebugLoc();
7172   EVT VT = Op.getValueType();
7173   EVT EltVT = VT;
7174   if (VT.isVector())
7175     EltVT = VT.getVectorElementType();
7176   std::vector<Constant*> CV;
7177   if (EltVT == MVT::f64) {
7178     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7179     CV.push_back(C);
7180     CV.push_back(C);
7181   } else {
7182     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7183     CV.push_back(C);
7184     CV.push_back(C);
7185     CV.push_back(C);
7186     CV.push_back(C);
7187   }
7188   Constant *C = ConstantVector::get(CV);
7189   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7190   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7191                              MachinePointerInfo::getConstantPool(),
7192                              false, false, 16);
7193   if (VT.isVector()) {
7194     return DAG.getNode(ISD::BITCAST, dl, VT,
7195                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7196                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7197                                 Op.getOperand(0)),
7198                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7199   } else {
7200     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7201   }
7202 }
7203
7204 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7205   LLVMContext *Context = DAG.getContext();
7206   SDValue Op0 = Op.getOperand(0);
7207   SDValue Op1 = Op.getOperand(1);
7208   DebugLoc dl = Op.getDebugLoc();
7209   EVT VT = Op.getValueType();
7210   EVT SrcVT = Op1.getValueType();
7211
7212   // If second operand is smaller, extend it first.
7213   if (SrcVT.bitsLT(VT)) {
7214     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7215     SrcVT = VT;
7216   }
7217   // And if it is bigger, shrink it first.
7218   if (SrcVT.bitsGT(VT)) {
7219     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7220     SrcVT = VT;
7221   }
7222
7223   // At this point the operands and the result should have the same
7224   // type, and that won't be f80 since that is not custom lowered.
7225
7226   // First get the sign bit of second operand.
7227   std::vector<Constant*> CV;
7228   if (SrcVT == MVT::f64) {
7229     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7230     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7231   } else {
7232     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7233     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7234     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7235     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7236   }
7237   Constant *C = ConstantVector::get(CV);
7238   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7239   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7240                               MachinePointerInfo::getConstantPool(),
7241                               false, false, 16);
7242   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7243
7244   // Shift sign bit right or left if the two operands have different types.
7245   if (SrcVT.bitsGT(VT)) {
7246     // Op0 is MVT::f32, Op1 is MVT::f64.
7247     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7248     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7249                           DAG.getConstant(32, MVT::i32));
7250     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7251     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7252                           DAG.getIntPtrConstant(0));
7253   }
7254
7255   // Clear first operand sign bit.
7256   CV.clear();
7257   if (VT == MVT::f64) {
7258     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7259     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7260   } else {
7261     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7262     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7263     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7264     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7265   }
7266   C = ConstantVector::get(CV);
7267   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7268   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7269                               MachinePointerInfo::getConstantPool(),
7270                               false, false, 16);
7271   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7272
7273   // Or the value with the sign bit.
7274   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7275 }
7276
7277 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7278   SDValue N0 = Op.getOperand(0);
7279   DebugLoc dl = Op.getDebugLoc();
7280   EVT VT = Op.getValueType();
7281
7282   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7283   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7284                                   DAG.getConstant(1, VT));
7285   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7286 }
7287
7288 /// Emit nodes that will be selected as "test Op0,Op0", or something
7289 /// equivalent.
7290 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7291                                     SelectionDAG &DAG) const {
7292   DebugLoc dl = Op.getDebugLoc();
7293
7294   // CF and OF aren't always set the way we want. Determine which
7295   // of these we need.
7296   bool NeedCF = false;
7297   bool NeedOF = false;
7298   switch (X86CC) {
7299   default: break;
7300   case X86::COND_A: case X86::COND_AE:
7301   case X86::COND_B: case X86::COND_BE:
7302     NeedCF = true;
7303     break;
7304   case X86::COND_G: case X86::COND_GE:
7305   case X86::COND_L: case X86::COND_LE:
7306   case X86::COND_O: case X86::COND_NO:
7307     NeedOF = true;
7308     break;
7309   }
7310
7311   // See if we can use the EFLAGS value from the operand instead of
7312   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7313   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7314   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7315     // Emit a CMP with 0, which is the TEST pattern.
7316     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7317                        DAG.getConstant(0, Op.getValueType()));
7318
7319   unsigned Opcode = 0;
7320   unsigned NumOperands = 0;
7321   switch (Op.getNode()->getOpcode()) {
7322   case ISD::ADD:
7323     // Due to an isel shortcoming, be conservative if this add is likely to be
7324     // selected as part of a load-modify-store instruction. When the root node
7325     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7326     // uses of other nodes in the match, such as the ADD in this case. This
7327     // leads to the ADD being left around and reselected, with the result being
7328     // two adds in the output.  Alas, even if none our users are stores, that
7329     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7330     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7331     // climbing the DAG back to the root, and it doesn't seem to be worth the
7332     // effort.
7333     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7334            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7335       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7336         goto default_case;
7337
7338     if (ConstantSDNode *C =
7339         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7340       // An add of one will be selected as an INC.
7341       if (C->getAPIntValue() == 1) {
7342         Opcode = X86ISD::INC;
7343         NumOperands = 1;
7344         break;
7345       }
7346
7347       // An add of negative one (subtract of one) will be selected as a DEC.
7348       if (C->getAPIntValue().isAllOnesValue()) {
7349         Opcode = X86ISD::DEC;
7350         NumOperands = 1;
7351         break;
7352       }
7353     }
7354
7355     // Otherwise use a regular EFLAGS-setting add.
7356     Opcode = X86ISD::ADD;
7357     NumOperands = 2;
7358     break;
7359   case ISD::AND: {
7360     // If the primary and result isn't used, don't bother using X86ISD::AND,
7361     // because a TEST instruction will be better.
7362     bool NonFlagUse = false;
7363     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7364            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7365       SDNode *User = *UI;
7366       unsigned UOpNo = UI.getOperandNo();
7367       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7368         // Look pass truncate.
7369         UOpNo = User->use_begin().getOperandNo();
7370         User = *User->use_begin();
7371       }
7372
7373       if (User->getOpcode() != ISD::BRCOND &&
7374           User->getOpcode() != ISD::SETCC &&
7375           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7376         NonFlagUse = true;
7377         break;
7378       }
7379     }
7380
7381     if (!NonFlagUse)
7382       break;
7383   }
7384     // FALL THROUGH
7385   case ISD::SUB:
7386   case ISD::OR:
7387   case ISD::XOR:
7388     // Due to the ISEL shortcoming noted above, be conservative if this op is
7389     // likely to be selected as part of a load-modify-store instruction.
7390     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7391            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7392       if (UI->getOpcode() == ISD::STORE)
7393         goto default_case;
7394
7395     // Otherwise use a regular EFLAGS-setting instruction.
7396     switch (Op.getNode()->getOpcode()) {
7397     default: llvm_unreachable("unexpected operator!");
7398     case ISD::SUB: Opcode = X86ISD::SUB; break;
7399     case ISD::OR:  Opcode = X86ISD::OR;  break;
7400     case ISD::XOR: Opcode = X86ISD::XOR; break;
7401     case ISD::AND: Opcode = X86ISD::AND; break;
7402     }
7403
7404     NumOperands = 2;
7405     break;
7406   case X86ISD::ADD:
7407   case X86ISD::SUB:
7408   case X86ISD::INC:
7409   case X86ISD::DEC:
7410   case X86ISD::OR:
7411   case X86ISD::XOR:
7412   case X86ISD::AND:
7413     return SDValue(Op.getNode(), 1);
7414   default:
7415   default_case:
7416     break;
7417   }
7418
7419   if (Opcode == 0)
7420     // Emit a CMP with 0, which is the TEST pattern.
7421     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7422                        DAG.getConstant(0, Op.getValueType()));
7423
7424   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7425   SmallVector<SDValue, 4> Ops;
7426   for (unsigned i = 0; i != NumOperands; ++i)
7427     Ops.push_back(Op.getOperand(i));
7428
7429   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7430   DAG.ReplaceAllUsesWith(Op, New);
7431   return SDValue(New.getNode(), 1);
7432 }
7433
7434 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7435 /// equivalent.
7436 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7437                                    SelectionDAG &DAG) const {
7438   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7439     if (C->getAPIntValue() == 0)
7440       return EmitTest(Op0, X86CC, DAG);
7441
7442   DebugLoc dl = Op0.getDebugLoc();
7443   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7444 }
7445
7446 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7447 /// if it's possible.
7448 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7449                                      DebugLoc dl, SelectionDAG &DAG) const {
7450   SDValue Op0 = And.getOperand(0);
7451   SDValue Op1 = And.getOperand(1);
7452   if (Op0.getOpcode() == ISD::TRUNCATE)
7453     Op0 = Op0.getOperand(0);
7454   if (Op1.getOpcode() == ISD::TRUNCATE)
7455     Op1 = Op1.getOperand(0);
7456
7457   SDValue LHS, RHS;
7458   if (Op1.getOpcode() == ISD::SHL)
7459     std::swap(Op0, Op1);
7460   if (Op0.getOpcode() == ISD::SHL) {
7461     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7462       if (And00C->getZExtValue() == 1) {
7463         // If we looked past a truncate, check that it's only truncating away
7464         // known zeros.
7465         unsigned BitWidth = Op0.getValueSizeInBits();
7466         unsigned AndBitWidth = And.getValueSizeInBits();
7467         if (BitWidth > AndBitWidth) {
7468           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7469           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7470           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7471             return SDValue();
7472         }
7473         LHS = Op1;
7474         RHS = Op0.getOperand(1);
7475       }
7476   } else if (Op1.getOpcode() == ISD::Constant) {
7477     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7478     SDValue AndLHS = Op0;
7479     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7480       LHS = AndLHS.getOperand(0);
7481       RHS = AndLHS.getOperand(1);
7482     }
7483   }
7484
7485   if (LHS.getNode()) {
7486     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7487     // instruction.  Since the shift amount is in-range-or-undefined, we know
7488     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7489     // the encoding for the i16 version is larger than the i32 version.
7490     // Also promote i16 to i32 for performance / code size reason.
7491     if (LHS.getValueType() == MVT::i8 ||
7492         LHS.getValueType() == MVT::i16)
7493       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7494
7495     // If the operand types disagree, extend the shift amount to match.  Since
7496     // BT ignores high bits (like shifts) we can use anyextend.
7497     if (LHS.getValueType() != RHS.getValueType())
7498       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7499
7500     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7501     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7502     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7503                        DAG.getConstant(Cond, MVT::i8), BT);
7504   }
7505
7506   return SDValue();
7507 }
7508
7509 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7510   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7511   SDValue Op0 = Op.getOperand(0);
7512   SDValue Op1 = Op.getOperand(1);
7513   DebugLoc dl = Op.getDebugLoc();
7514   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7515
7516   // Optimize to BT if possible.
7517   // Lower (X & (1 << N)) == 0 to BT(X, N).
7518   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7519   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7520   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7521       Op1.getOpcode() == ISD::Constant &&
7522       cast<ConstantSDNode>(Op1)->isNullValue() &&
7523       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7524     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7525     if (NewSetCC.getNode())
7526       return NewSetCC;
7527   }
7528
7529   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7530   // these.
7531   if (Op1.getOpcode() == ISD::Constant &&
7532       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7533        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7534       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7535
7536     // If the input is a setcc, then reuse the input setcc or use a new one with
7537     // the inverted condition.
7538     if (Op0.getOpcode() == X86ISD::SETCC) {
7539       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7540       bool Invert = (CC == ISD::SETNE) ^
7541         cast<ConstantSDNode>(Op1)->isNullValue();
7542       if (!Invert) return Op0;
7543
7544       CCode = X86::GetOppositeBranchCondition(CCode);
7545       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7546                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7547     }
7548   }
7549
7550   bool isFP = Op1.getValueType().isFloatingPoint();
7551   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7552   if (X86CC == X86::COND_INVALID)
7553     return SDValue();
7554
7555   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7556   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7557                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7558 }
7559
7560 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7561   SDValue Cond;
7562   SDValue Op0 = Op.getOperand(0);
7563   SDValue Op1 = Op.getOperand(1);
7564   SDValue CC = Op.getOperand(2);
7565   EVT VT = Op.getValueType();
7566   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7567   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7568   DebugLoc dl = Op.getDebugLoc();
7569
7570   if (isFP) {
7571     unsigned SSECC = 8;
7572     EVT VT0 = Op0.getValueType();
7573     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7574     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7575     bool Swap = false;
7576
7577     switch (SetCCOpcode) {
7578     default: break;
7579     case ISD::SETOEQ:
7580     case ISD::SETEQ:  SSECC = 0; break;
7581     case ISD::SETOGT:
7582     case ISD::SETGT: Swap = true; // Fallthrough
7583     case ISD::SETLT:
7584     case ISD::SETOLT: SSECC = 1; break;
7585     case ISD::SETOGE:
7586     case ISD::SETGE: Swap = true; // Fallthrough
7587     case ISD::SETLE:
7588     case ISD::SETOLE: SSECC = 2; break;
7589     case ISD::SETUO:  SSECC = 3; break;
7590     case ISD::SETUNE:
7591     case ISD::SETNE:  SSECC = 4; break;
7592     case ISD::SETULE: Swap = true;
7593     case ISD::SETUGE: SSECC = 5; break;
7594     case ISD::SETULT: Swap = true;
7595     case ISD::SETUGT: SSECC = 6; break;
7596     case ISD::SETO:   SSECC = 7; break;
7597     }
7598     if (Swap)
7599       std::swap(Op0, Op1);
7600
7601     // In the two special cases we can't handle, emit two comparisons.
7602     if (SSECC == 8) {
7603       if (SetCCOpcode == ISD::SETUEQ) {
7604         SDValue UNORD, EQ;
7605         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7606         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7607         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7608       }
7609       else if (SetCCOpcode == ISD::SETONE) {
7610         SDValue ORD, NEQ;
7611         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7612         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7613         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7614       }
7615       llvm_unreachable("Illegal FP comparison");
7616     }
7617     // Handle all other FP comparisons here.
7618     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7619   }
7620
7621   // We are handling one of the integer comparisons here.  Since SSE only has
7622   // GT and EQ comparisons for integer, swapping operands and multiple
7623   // operations may be required for some comparisons.
7624   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7625   bool Swap = false, Invert = false, FlipSigns = false;
7626
7627   switch (VT.getSimpleVT().SimpleTy) {
7628   default: break;
7629   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7630   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7631   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7632   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7633   }
7634
7635   switch (SetCCOpcode) {
7636   default: break;
7637   case ISD::SETNE:  Invert = true;
7638   case ISD::SETEQ:  Opc = EQOpc; break;
7639   case ISD::SETLT:  Swap = true;
7640   case ISD::SETGT:  Opc = GTOpc; break;
7641   case ISD::SETGE:  Swap = true;
7642   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7643   case ISD::SETULT: Swap = true;
7644   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7645   case ISD::SETUGE: Swap = true;
7646   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7647   }
7648   if (Swap)
7649     std::swap(Op0, Op1);
7650
7651   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7652   // bits of the inputs before performing those operations.
7653   if (FlipSigns) {
7654     EVT EltVT = VT.getVectorElementType();
7655     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7656                                       EltVT);
7657     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7658     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7659                                     SignBits.size());
7660     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7661     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7662   }
7663
7664   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7665
7666   // If the logical-not of the result is required, perform that now.
7667   if (Invert)
7668     Result = DAG.getNOT(dl, Result, VT);
7669
7670   return Result;
7671 }
7672
7673 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7674 static bool isX86LogicalCmp(SDValue Op) {
7675   unsigned Opc = Op.getNode()->getOpcode();
7676   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7677     return true;
7678   if (Op.getResNo() == 1 &&
7679       (Opc == X86ISD::ADD ||
7680        Opc == X86ISD::SUB ||
7681        Opc == X86ISD::ADC ||
7682        Opc == X86ISD::SBB ||
7683        Opc == X86ISD::SMUL ||
7684        Opc == X86ISD::UMUL ||
7685        Opc == X86ISD::INC ||
7686        Opc == X86ISD::DEC ||
7687        Opc == X86ISD::OR ||
7688        Opc == X86ISD::XOR ||
7689        Opc == X86ISD::AND))
7690     return true;
7691
7692   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7693     return true;
7694
7695   return false;
7696 }
7697
7698 static bool isZero(SDValue V) {
7699   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7700   return C && C->isNullValue();
7701 }
7702
7703 static bool isAllOnes(SDValue V) {
7704   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7705   return C && C->isAllOnesValue();
7706 }
7707
7708 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7709   bool addTest = true;
7710   SDValue Cond  = Op.getOperand(0);
7711   SDValue Op1 = Op.getOperand(1);
7712   SDValue Op2 = Op.getOperand(2);
7713   DebugLoc DL = Op.getDebugLoc();
7714   SDValue CC;
7715
7716   if (Cond.getOpcode() == ISD::SETCC) {
7717     SDValue NewCond = LowerSETCC(Cond, DAG);
7718     if (NewCond.getNode())
7719       Cond = NewCond;
7720   }
7721
7722   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7723   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7724   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7725   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7726   if (Cond.getOpcode() == X86ISD::SETCC &&
7727       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7728       isZero(Cond.getOperand(1).getOperand(1))) {
7729     SDValue Cmp = Cond.getOperand(1);
7730
7731     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7732
7733     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7734         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7735       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7736
7737       SDValue CmpOp0 = Cmp.getOperand(0);
7738       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7739                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7740
7741       SDValue Res =   // Res = 0 or -1.
7742         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7743                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7744
7745       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7746         Res = DAG.getNOT(DL, Res, Res.getValueType());
7747
7748       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7749       if (N2C == 0 || !N2C->isNullValue())
7750         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7751       return Res;
7752     }
7753   }
7754
7755   // Look past (and (setcc_carry (cmp ...)), 1).
7756   if (Cond.getOpcode() == ISD::AND &&
7757       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7758     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7759     if (C && C->getAPIntValue() == 1)
7760       Cond = Cond.getOperand(0);
7761   }
7762
7763   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7764   // setting operand in place of the X86ISD::SETCC.
7765   if (Cond.getOpcode() == X86ISD::SETCC ||
7766       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7767     CC = Cond.getOperand(0);
7768
7769     SDValue Cmp = Cond.getOperand(1);
7770     unsigned Opc = Cmp.getOpcode();
7771     EVT VT = Op.getValueType();
7772
7773     bool IllegalFPCMov = false;
7774     if (VT.isFloatingPoint() && !VT.isVector() &&
7775         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7776       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7777
7778     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7779         Opc == X86ISD::BT) { // FIXME
7780       Cond = Cmp;
7781       addTest = false;
7782     }
7783   }
7784
7785   if (addTest) {
7786     // Look pass the truncate.
7787     if (Cond.getOpcode() == ISD::TRUNCATE)
7788       Cond = Cond.getOperand(0);
7789
7790     // We know the result of AND is compared against zero. Try to match
7791     // it to BT.
7792     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7793       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7794       if (NewSetCC.getNode()) {
7795         CC = NewSetCC.getOperand(0);
7796         Cond = NewSetCC.getOperand(1);
7797         addTest = false;
7798       }
7799     }
7800   }
7801
7802   if (addTest) {
7803     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7804     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7805   }
7806
7807   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7808   // a <  b ?  0 : -1 -> RES = setcc_carry
7809   // a >= b ? -1 :  0 -> RES = setcc_carry
7810   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7811   if (Cond.getOpcode() == X86ISD::CMP) {
7812     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7813
7814     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7815         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7816       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7817                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7818       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7819         return DAG.getNOT(DL, Res, Res.getValueType());
7820       return Res;
7821     }
7822   }
7823
7824   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7825   // condition is true.
7826   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7827   SDValue Ops[] = { Op2, Op1, CC, Cond };
7828   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7829 }
7830
7831 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7832 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7833 // from the AND / OR.
7834 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7835   Opc = Op.getOpcode();
7836   if (Opc != ISD::OR && Opc != ISD::AND)
7837     return false;
7838   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7839           Op.getOperand(0).hasOneUse() &&
7840           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7841           Op.getOperand(1).hasOneUse());
7842 }
7843
7844 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7845 // 1 and that the SETCC node has a single use.
7846 static bool isXor1OfSetCC(SDValue Op) {
7847   if (Op.getOpcode() != ISD::XOR)
7848     return false;
7849   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7850   if (N1C && N1C->getAPIntValue() == 1) {
7851     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7852       Op.getOperand(0).hasOneUse();
7853   }
7854   return false;
7855 }
7856
7857 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7858   bool addTest = true;
7859   SDValue Chain = Op.getOperand(0);
7860   SDValue Cond  = Op.getOperand(1);
7861   SDValue Dest  = Op.getOperand(2);
7862   DebugLoc dl = Op.getDebugLoc();
7863   SDValue CC;
7864
7865   if (Cond.getOpcode() == ISD::SETCC) {
7866     SDValue NewCond = LowerSETCC(Cond, DAG);
7867     if (NewCond.getNode())
7868       Cond = NewCond;
7869   }
7870 #if 0
7871   // FIXME: LowerXALUO doesn't handle these!!
7872   else if (Cond.getOpcode() == X86ISD::ADD  ||
7873            Cond.getOpcode() == X86ISD::SUB  ||
7874            Cond.getOpcode() == X86ISD::SMUL ||
7875            Cond.getOpcode() == X86ISD::UMUL)
7876     Cond = LowerXALUO(Cond, DAG);
7877 #endif
7878
7879   // Look pass (and (setcc_carry (cmp ...)), 1).
7880   if (Cond.getOpcode() == ISD::AND &&
7881       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7882     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7883     if (C && C->getAPIntValue() == 1)
7884       Cond = Cond.getOperand(0);
7885   }
7886
7887   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7888   // setting operand in place of the X86ISD::SETCC.
7889   if (Cond.getOpcode() == X86ISD::SETCC ||
7890       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7891     CC = Cond.getOperand(0);
7892
7893     SDValue Cmp = Cond.getOperand(1);
7894     unsigned Opc = Cmp.getOpcode();
7895     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7896     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7897       Cond = Cmp;
7898       addTest = false;
7899     } else {
7900       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7901       default: break;
7902       case X86::COND_O:
7903       case X86::COND_B:
7904         // These can only come from an arithmetic instruction with overflow,
7905         // e.g. SADDO, UADDO.
7906         Cond = Cond.getNode()->getOperand(1);
7907         addTest = false;
7908         break;
7909       }
7910     }
7911   } else {
7912     unsigned CondOpc;
7913     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7914       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7915       if (CondOpc == ISD::OR) {
7916         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7917         // two branches instead of an explicit OR instruction with a
7918         // separate test.
7919         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7920             isX86LogicalCmp(Cmp)) {
7921           CC = Cond.getOperand(0).getOperand(0);
7922           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7923                               Chain, Dest, CC, Cmp);
7924           CC = Cond.getOperand(1).getOperand(0);
7925           Cond = Cmp;
7926           addTest = false;
7927         }
7928       } else { // ISD::AND
7929         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7930         // two branches instead of an explicit AND instruction with a
7931         // separate test. However, we only do this if this block doesn't
7932         // have a fall-through edge, because this requires an explicit
7933         // jmp when the condition is false.
7934         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7935             isX86LogicalCmp(Cmp) &&
7936             Op.getNode()->hasOneUse()) {
7937           X86::CondCode CCode =
7938             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7939           CCode = X86::GetOppositeBranchCondition(CCode);
7940           CC = DAG.getConstant(CCode, MVT::i8);
7941           SDNode *User = *Op.getNode()->use_begin();
7942           // Look for an unconditional branch following this conditional branch.
7943           // We need this because we need to reverse the successors in order
7944           // to implement FCMP_OEQ.
7945           if (User->getOpcode() == ISD::BR) {
7946             SDValue FalseBB = User->getOperand(1);
7947             SDNode *NewBR =
7948               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7949             assert(NewBR == User);
7950             (void)NewBR;
7951             Dest = FalseBB;
7952
7953             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7954                                 Chain, Dest, CC, Cmp);
7955             X86::CondCode CCode =
7956               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7957             CCode = X86::GetOppositeBranchCondition(CCode);
7958             CC = DAG.getConstant(CCode, MVT::i8);
7959             Cond = Cmp;
7960             addTest = false;
7961           }
7962         }
7963       }
7964     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7965       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7966       // It should be transformed during dag combiner except when the condition
7967       // is set by a arithmetics with overflow node.
7968       X86::CondCode CCode =
7969         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7970       CCode = X86::GetOppositeBranchCondition(CCode);
7971       CC = DAG.getConstant(CCode, MVT::i8);
7972       Cond = Cond.getOperand(0).getOperand(1);
7973       addTest = false;
7974     }
7975   }
7976
7977   if (addTest) {
7978     // Look pass the truncate.
7979     if (Cond.getOpcode() == ISD::TRUNCATE)
7980       Cond = Cond.getOperand(0);
7981
7982     // We know the result of AND is compared against zero. Try to match
7983     // it to BT.
7984     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7985       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7986       if (NewSetCC.getNode()) {
7987         CC = NewSetCC.getOperand(0);
7988         Cond = NewSetCC.getOperand(1);
7989         addTest = false;
7990       }
7991     }
7992   }
7993
7994   if (addTest) {
7995     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7996     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7997   }
7998   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7999                      Chain, Dest, CC, Cond);
8000 }
8001
8002
8003 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8004 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8005 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8006 // that the guard pages used by the OS virtual memory manager are allocated in
8007 // correct sequence.
8008 SDValue
8009 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8010                                            SelectionDAG &DAG) const {
8011   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8012          "This should be used only on Windows targets");
8013   assert(!Subtarget->isTargetEnvMacho());
8014   DebugLoc dl = Op.getDebugLoc();
8015
8016   // Get the inputs.
8017   SDValue Chain = Op.getOperand(0);
8018   SDValue Size  = Op.getOperand(1);
8019   // FIXME: Ensure alignment here
8020
8021   SDValue Flag;
8022
8023   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8024   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8025
8026   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8027   Flag = Chain.getValue(1);
8028
8029   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8030
8031   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8032   Flag = Chain.getValue(1);
8033
8034   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8035
8036   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8037   return DAG.getMergeValues(Ops1, 2, dl);
8038 }
8039
8040 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8041   MachineFunction &MF = DAG.getMachineFunction();
8042   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8043
8044   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8045   DebugLoc DL = Op.getDebugLoc();
8046
8047   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8048     // vastart just stores the address of the VarArgsFrameIndex slot into the
8049     // memory location argument.
8050     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8051                                    getPointerTy());
8052     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8053                         MachinePointerInfo(SV), false, false, 0);
8054   }
8055
8056   // __va_list_tag:
8057   //   gp_offset         (0 - 6 * 8)
8058   //   fp_offset         (48 - 48 + 8 * 16)
8059   //   overflow_arg_area (point to parameters coming in memory).
8060   //   reg_save_area
8061   SmallVector<SDValue, 8> MemOps;
8062   SDValue FIN = Op.getOperand(1);
8063   // Store gp_offset
8064   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8065                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8066                                                MVT::i32),
8067                                FIN, MachinePointerInfo(SV), false, false, 0);
8068   MemOps.push_back(Store);
8069
8070   // Store fp_offset
8071   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8072                     FIN, DAG.getIntPtrConstant(4));
8073   Store = DAG.getStore(Op.getOperand(0), DL,
8074                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8075                                        MVT::i32),
8076                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8077   MemOps.push_back(Store);
8078
8079   // Store ptr to overflow_arg_area
8080   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8081                     FIN, DAG.getIntPtrConstant(4));
8082   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8083                                     getPointerTy());
8084   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8085                        MachinePointerInfo(SV, 8),
8086                        false, false, 0);
8087   MemOps.push_back(Store);
8088
8089   // Store ptr to reg_save_area.
8090   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8091                     FIN, DAG.getIntPtrConstant(8));
8092   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8093                                     getPointerTy());
8094   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8095                        MachinePointerInfo(SV, 16), false, false, 0);
8096   MemOps.push_back(Store);
8097   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8098                      &MemOps[0], MemOps.size());
8099 }
8100
8101 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8102   assert(Subtarget->is64Bit() &&
8103          "LowerVAARG only handles 64-bit va_arg!");
8104   assert((Subtarget->isTargetLinux() ||
8105           Subtarget->isTargetDarwin()) &&
8106           "Unhandled target in LowerVAARG");
8107   assert(Op.getNode()->getNumOperands() == 4);
8108   SDValue Chain = Op.getOperand(0);
8109   SDValue SrcPtr = Op.getOperand(1);
8110   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8111   unsigned Align = Op.getConstantOperandVal(3);
8112   DebugLoc dl = Op.getDebugLoc();
8113
8114   EVT ArgVT = Op.getNode()->getValueType(0);
8115   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8116   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8117   uint8_t ArgMode;
8118
8119   // Decide which area this value should be read from.
8120   // TODO: Implement the AMD64 ABI in its entirety. This simple
8121   // selection mechanism works only for the basic types.
8122   if (ArgVT == MVT::f80) {
8123     llvm_unreachable("va_arg for f80 not yet implemented");
8124   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8125     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8126   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8127     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8128   } else {
8129     llvm_unreachable("Unhandled argument type in LowerVAARG");
8130   }
8131
8132   if (ArgMode == 2) {
8133     // Sanity Check: Make sure using fp_offset makes sense.
8134     assert(!UseSoftFloat &&
8135            !(DAG.getMachineFunction()
8136                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8137            Subtarget->hasXMM());
8138   }
8139
8140   // Insert VAARG_64 node into the DAG
8141   // VAARG_64 returns two values: Variable Argument Address, Chain
8142   SmallVector<SDValue, 11> InstOps;
8143   InstOps.push_back(Chain);
8144   InstOps.push_back(SrcPtr);
8145   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8146   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8147   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8148   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8149   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8150                                           VTs, &InstOps[0], InstOps.size(),
8151                                           MVT::i64,
8152                                           MachinePointerInfo(SV),
8153                                           /*Align=*/0,
8154                                           /*Volatile=*/false,
8155                                           /*ReadMem=*/true,
8156                                           /*WriteMem=*/true);
8157   Chain = VAARG.getValue(1);
8158
8159   // Load the next argument and return it
8160   return DAG.getLoad(ArgVT, dl,
8161                      Chain,
8162                      VAARG,
8163                      MachinePointerInfo(),
8164                      false, false, 0);
8165 }
8166
8167 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8168   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8169   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8170   SDValue Chain = Op.getOperand(0);
8171   SDValue DstPtr = Op.getOperand(1);
8172   SDValue SrcPtr = Op.getOperand(2);
8173   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8174   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8175   DebugLoc DL = Op.getDebugLoc();
8176
8177   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8178                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8179                        false,
8180                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8181 }
8182
8183 SDValue
8184 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8185   DebugLoc dl = Op.getDebugLoc();
8186   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8187   switch (IntNo) {
8188   default: return SDValue();    // Don't custom lower most intrinsics.
8189   // Comparison intrinsics.
8190   case Intrinsic::x86_sse_comieq_ss:
8191   case Intrinsic::x86_sse_comilt_ss:
8192   case Intrinsic::x86_sse_comile_ss:
8193   case Intrinsic::x86_sse_comigt_ss:
8194   case Intrinsic::x86_sse_comige_ss:
8195   case Intrinsic::x86_sse_comineq_ss:
8196   case Intrinsic::x86_sse_ucomieq_ss:
8197   case Intrinsic::x86_sse_ucomilt_ss:
8198   case Intrinsic::x86_sse_ucomile_ss:
8199   case Intrinsic::x86_sse_ucomigt_ss:
8200   case Intrinsic::x86_sse_ucomige_ss:
8201   case Intrinsic::x86_sse_ucomineq_ss:
8202   case Intrinsic::x86_sse2_comieq_sd:
8203   case Intrinsic::x86_sse2_comilt_sd:
8204   case Intrinsic::x86_sse2_comile_sd:
8205   case Intrinsic::x86_sse2_comigt_sd:
8206   case Intrinsic::x86_sse2_comige_sd:
8207   case Intrinsic::x86_sse2_comineq_sd:
8208   case Intrinsic::x86_sse2_ucomieq_sd:
8209   case Intrinsic::x86_sse2_ucomilt_sd:
8210   case Intrinsic::x86_sse2_ucomile_sd:
8211   case Intrinsic::x86_sse2_ucomigt_sd:
8212   case Intrinsic::x86_sse2_ucomige_sd:
8213   case Intrinsic::x86_sse2_ucomineq_sd: {
8214     unsigned Opc = 0;
8215     ISD::CondCode CC = ISD::SETCC_INVALID;
8216     switch (IntNo) {
8217     default: break;
8218     case Intrinsic::x86_sse_comieq_ss:
8219     case Intrinsic::x86_sse2_comieq_sd:
8220       Opc = X86ISD::COMI;
8221       CC = ISD::SETEQ;
8222       break;
8223     case Intrinsic::x86_sse_comilt_ss:
8224     case Intrinsic::x86_sse2_comilt_sd:
8225       Opc = X86ISD::COMI;
8226       CC = ISD::SETLT;
8227       break;
8228     case Intrinsic::x86_sse_comile_ss:
8229     case Intrinsic::x86_sse2_comile_sd:
8230       Opc = X86ISD::COMI;
8231       CC = ISD::SETLE;
8232       break;
8233     case Intrinsic::x86_sse_comigt_ss:
8234     case Intrinsic::x86_sse2_comigt_sd:
8235       Opc = X86ISD::COMI;
8236       CC = ISD::SETGT;
8237       break;
8238     case Intrinsic::x86_sse_comige_ss:
8239     case Intrinsic::x86_sse2_comige_sd:
8240       Opc = X86ISD::COMI;
8241       CC = ISD::SETGE;
8242       break;
8243     case Intrinsic::x86_sse_comineq_ss:
8244     case Intrinsic::x86_sse2_comineq_sd:
8245       Opc = X86ISD::COMI;
8246       CC = ISD::SETNE;
8247       break;
8248     case Intrinsic::x86_sse_ucomieq_ss:
8249     case Intrinsic::x86_sse2_ucomieq_sd:
8250       Opc = X86ISD::UCOMI;
8251       CC = ISD::SETEQ;
8252       break;
8253     case Intrinsic::x86_sse_ucomilt_ss:
8254     case Intrinsic::x86_sse2_ucomilt_sd:
8255       Opc = X86ISD::UCOMI;
8256       CC = ISD::SETLT;
8257       break;
8258     case Intrinsic::x86_sse_ucomile_ss:
8259     case Intrinsic::x86_sse2_ucomile_sd:
8260       Opc = X86ISD::UCOMI;
8261       CC = ISD::SETLE;
8262       break;
8263     case Intrinsic::x86_sse_ucomigt_ss:
8264     case Intrinsic::x86_sse2_ucomigt_sd:
8265       Opc = X86ISD::UCOMI;
8266       CC = ISD::SETGT;
8267       break;
8268     case Intrinsic::x86_sse_ucomige_ss:
8269     case Intrinsic::x86_sse2_ucomige_sd:
8270       Opc = X86ISD::UCOMI;
8271       CC = ISD::SETGE;
8272       break;
8273     case Intrinsic::x86_sse_ucomineq_ss:
8274     case Intrinsic::x86_sse2_ucomineq_sd:
8275       Opc = X86ISD::UCOMI;
8276       CC = ISD::SETNE;
8277       break;
8278     }
8279
8280     SDValue LHS = Op.getOperand(1);
8281     SDValue RHS = Op.getOperand(2);
8282     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8283     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8284     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8285     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8286                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8287     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8288   }
8289   // ptest and testp intrinsics. The intrinsic these come from are designed to
8290   // return an integer value, not just an instruction so lower it to the ptest
8291   // or testp pattern and a setcc for the result.
8292   case Intrinsic::x86_sse41_ptestz:
8293   case Intrinsic::x86_sse41_ptestc:
8294   case Intrinsic::x86_sse41_ptestnzc:
8295   case Intrinsic::x86_avx_ptestz_256:
8296   case Intrinsic::x86_avx_ptestc_256:
8297   case Intrinsic::x86_avx_ptestnzc_256:
8298   case Intrinsic::x86_avx_vtestz_ps:
8299   case Intrinsic::x86_avx_vtestc_ps:
8300   case Intrinsic::x86_avx_vtestnzc_ps:
8301   case Intrinsic::x86_avx_vtestz_pd:
8302   case Intrinsic::x86_avx_vtestc_pd:
8303   case Intrinsic::x86_avx_vtestnzc_pd:
8304   case Intrinsic::x86_avx_vtestz_ps_256:
8305   case Intrinsic::x86_avx_vtestc_ps_256:
8306   case Intrinsic::x86_avx_vtestnzc_ps_256:
8307   case Intrinsic::x86_avx_vtestz_pd_256:
8308   case Intrinsic::x86_avx_vtestc_pd_256:
8309   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8310     bool IsTestPacked = false;
8311     unsigned X86CC = 0;
8312     switch (IntNo) {
8313     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8314     case Intrinsic::x86_avx_vtestz_ps:
8315     case Intrinsic::x86_avx_vtestz_pd:
8316     case Intrinsic::x86_avx_vtestz_ps_256:
8317     case Intrinsic::x86_avx_vtestz_pd_256:
8318       IsTestPacked = true; // Fallthrough
8319     case Intrinsic::x86_sse41_ptestz:
8320     case Intrinsic::x86_avx_ptestz_256:
8321       // ZF = 1
8322       X86CC = X86::COND_E;
8323       break;
8324     case Intrinsic::x86_avx_vtestc_ps:
8325     case Intrinsic::x86_avx_vtestc_pd:
8326     case Intrinsic::x86_avx_vtestc_ps_256:
8327     case Intrinsic::x86_avx_vtestc_pd_256:
8328       IsTestPacked = true; // Fallthrough
8329     case Intrinsic::x86_sse41_ptestc:
8330     case Intrinsic::x86_avx_ptestc_256:
8331       // CF = 1
8332       X86CC = X86::COND_B;
8333       break;
8334     case Intrinsic::x86_avx_vtestnzc_ps:
8335     case Intrinsic::x86_avx_vtestnzc_pd:
8336     case Intrinsic::x86_avx_vtestnzc_ps_256:
8337     case Intrinsic::x86_avx_vtestnzc_pd_256:
8338       IsTestPacked = true; // Fallthrough
8339     case Intrinsic::x86_sse41_ptestnzc:
8340     case Intrinsic::x86_avx_ptestnzc_256:
8341       // ZF and CF = 0
8342       X86CC = X86::COND_A;
8343       break;
8344     }
8345
8346     SDValue LHS = Op.getOperand(1);
8347     SDValue RHS = Op.getOperand(2);
8348     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8349     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8350     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8351     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8352     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8353   }
8354
8355   // Fix vector shift instructions where the last operand is a non-immediate
8356   // i32 value.
8357   case Intrinsic::x86_sse2_pslli_w:
8358   case Intrinsic::x86_sse2_pslli_d:
8359   case Intrinsic::x86_sse2_pslli_q:
8360   case Intrinsic::x86_sse2_psrli_w:
8361   case Intrinsic::x86_sse2_psrli_d:
8362   case Intrinsic::x86_sse2_psrli_q:
8363   case Intrinsic::x86_sse2_psrai_w:
8364   case Intrinsic::x86_sse2_psrai_d:
8365   case Intrinsic::x86_mmx_pslli_w:
8366   case Intrinsic::x86_mmx_pslli_d:
8367   case Intrinsic::x86_mmx_pslli_q:
8368   case Intrinsic::x86_mmx_psrli_w:
8369   case Intrinsic::x86_mmx_psrli_d:
8370   case Intrinsic::x86_mmx_psrli_q:
8371   case Intrinsic::x86_mmx_psrai_w:
8372   case Intrinsic::x86_mmx_psrai_d: {
8373     SDValue ShAmt = Op.getOperand(2);
8374     if (isa<ConstantSDNode>(ShAmt))
8375       return SDValue();
8376
8377     unsigned NewIntNo = 0;
8378     EVT ShAmtVT = MVT::v4i32;
8379     switch (IntNo) {
8380     case Intrinsic::x86_sse2_pslli_w:
8381       NewIntNo = Intrinsic::x86_sse2_psll_w;
8382       break;
8383     case Intrinsic::x86_sse2_pslli_d:
8384       NewIntNo = Intrinsic::x86_sse2_psll_d;
8385       break;
8386     case Intrinsic::x86_sse2_pslli_q:
8387       NewIntNo = Intrinsic::x86_sse2_psll_q;
8388       break;
8389     case Intrinsic::x86_sse2_psrli_w:
8390       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8391       break;
8392     case Intrinsic::x86_sse2_psrli_d:
8393       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8394       break;
8395     case Intrinsic::x86_sse2_psrli_q:
8396       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8397       break;
8398     case Intrinsic::x86_sse2_psrai_w:
8399       NewIntNo = Intrinsic::x86_sse2_psra_w;
8400       break;
8401     case Intrinsic::x86_sse2_psrai_d:
8402       NewIntNo = Intrinsic::x86_sse2_psra_d;
8403       break;
8404     default: {
8405       ShAmtVT = MVT::v2i32;
8406       switch (IntNo) {
8407       case Intrinsic::x86_mmx_pslli_w:
8408         NewIntNo = Intrinsic::x86_mmx_psll_w;
8409         break;
8410       case Intrinsic::x86_mmx_pslli_d:
8411         NewIntNo = Intrinsic::x86_mmx_psll_d;
8412         break;
8413       case Intrinsic::x86_mmx_pslli_q:
8414         NewIntNo = Intrinsic::x86_mmx_psll_q;
8415         break;
8416       case Intrinsic::x86_mmx_psrli_w:
8417         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8418         break;
8419       case Intrinsic::x86_mmx_psrli_d:
8420         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8421         break;
8422       case Intrinsic::x86_mmx_psrli_q:
8423         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8424         break;
8425       case Intrinsic::x86_mmx_psrai_w:
8426         NewIntNo = Intrinsic::x86_mmx_psra_w;
8427         break;
8428       case Intrinsic::x86_mmx_psrai_d:
8429         NewIntNo = Intrinsic::x86_mmx_psra_d;
8430         break;
8431       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8432       }
8433       break;
8434     }
8435     }
8436
8437     // The vector shift intrinsics with scalars uses 32b shift amounts but
8438     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8439     // to be zero.
8440     SDValue ShOps[4];
8441     ShOps[0] = ShAmt;
8442     ShOps[1] = DAG.getConstant(0, MVT::i32);
8443     if (ShAmtVT == MVT::v4i32) {
8444       ShOps[2] = DAG.getUNDEF(MVT::i32);
8445       ShOps[3] = DAG.getUNDEF(MVT::i32);
8446       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8447     } else {
8448       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8449 // FIXME this must be lowered to get rid of the invalid type.
8450     }
8451
8452     EVT VT = Op.getValueType();
8453     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8454     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8455                        DAG.getConstant(NewIntNo, MVT::i32),
8456                        Op.getOperand(1), ShAmt);
8457   }
8458   }
8459 }
8460
8461 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8462                                            SelectionDAG &DAG) const {
8463   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8464   MFI->setReturnAddressIsTaken(true);
8465
8466   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8467   DebugLoc dl = Op.getDebugLoc();
8468
8469   if (Depth > 0) {
8470     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8471     SDValue Offset =
8472       DAG.getConstant(TD->getPointerSize(),
8473                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8474     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8475                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8476                                    FrameAddr, Offset),
8477                        MachinePointerInfo(), false, false, 0);
8478   }
8479
8480   // Just load the return address.
8481   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8482   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8483                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8484 }
8485
8486 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8487   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8488   MFI->setFrameAddressIsTaken(true);
8489
8490   EVT VT = Op.getValueType();
8491   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8492   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8493   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8494   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8495   while (Depth--)
8496     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8497                             MachinePointerInfo(),
8498                             false, false, 0);
8499   return FrameAddr;
8500 }
8501
8502 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8503                                                      SelectionDAG &DAG) const {
8504   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8505 }
8506
8507 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8508   MachineFunction &MF = DAG.getMachineFunction();
8509   SDValue Chain     = Op.getOperand(0);
8510   SDValue Offset    = Op.getOperand(1);
8511   SDValue Handler   = Op.getOperand(2);
8512   DebugLoc dl       = Op.getDebugLoc();
8513
8514   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8515                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8516                                      getPointerTy());
8517   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8518
8519   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8520                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8521   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8522   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8523                        false, false, 0);
8524   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8525   MF.getRegInfo().addLiveOut(StoreAddrReg);
8526
8527   return DAG.getNode(X86ISD::EH_RETURN, dl,
8528                      MVT::Other,
8529                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8530 }
8531
8532 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8533                                              SelectionDAG &DAG) const {
8534   SDValue Root = Op.getOperand(0);
8535   SDValue Trmp = Op.getOperand(1); // trampoline
8536   SDValue FPtr = Op.getOperand(2); // nested function
8537   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8538   DebugLoc dl  = Op.getDebugLoc();
8539
8540   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8541
8542   if (Subtarget->is64Bit()) {
8543     SDValue OutChains[6];
8544
8545     // Large code-model.
8546     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8547     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8548
8549     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8550     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8551
8552     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8553
8554     // Load the pointer to the nested function into R11.
8555     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8556     SDValue Addr = Trmp;
8557     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8558                                 Addr, MachinePointerInfo(TrmpAddr),
8559                                 false, false, 0);
8560
8561     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8562                        DAG.getConstant(2, MVT::i64));
8563     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8564                                 MachinePointerInfo(TrmpAddr, 2),
8565                                 false, false, 2);
8566
8567     // Load the 'nest' parameter value into R10.
8568     // R10 is specified in X86CallingConv.td
8569     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8570     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8571                        DAG.getConstant(10, MVT::i64));
8572     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8573                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8574                                 false, false, 0);
8575
8576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8577                        DAG.getConstant(12, MVT::i64));
8578     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8579                                 MachinePointerInfo(TrmpAddr, 12),
8580                                 false, false, 2);
8581
8582     // Jump to the nested function.
8583     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8584     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8585                        DAG.getConstant(20, MVT::i64));
8586     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8587                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8588                                 false, false, 0);
8589
8590     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8591     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8592                        DAG.getConstant(22, MVT::i64));
8593     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8594                                 MachinePointerInfo(TrmpAddr, 22),
8595                                 false, false, 0);
8596
8597     SDValue Ops[] =
8598       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8599     return DAG.getMergeValues(Ops, 2, dl);
8600   } else {
8601     const Function *Func =
8602       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8603     CallingConv::ID CC = Func->getCallingConv();
8604     unsigned NestReg;
8605
8606     switch (CC) {
8607     default:
8608       llvm_unreachable("Unsupported calling convention");
8609     case CallingConv::C:
8610     case CallingConv::X86_StdCall: {
8611       // Pass 'nest' parameter in ECX.
8612       // Must be kept in sync with X86CallingConv.td
8613       NestReg = X86::ECX;
8614
8615       // Check that ECX wasn't needed by an 'inreg' parameter.
8616       const FunctionType *FTy = Func->getFunctionType();
8617       const AttrListPtr &Attrs = Func->getAttributes();
8618
8619       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8620         unsigned InRegCount = 0;
8621         unsigned Idx = 1;
8622
8623         for (FunctionType::param_iterator I = FTy->param_begin(),
8624              E = FTy->param_end(); I != E; ++I, ++Idx)
8625           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8626             // FIXME: should only count parameters that are lowered to integers.
8627             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8628
8629         if (InRegCount > 2) {
8630           report_fatal_error("Nest register in use - reduce number of inreg"
8631                              " parameters!");
8632         }
8633       }
8634       break;
8635     }
8636     case CallingConv::X86_FastCall:
8637     case CallingConv::X86_ThisCall:
8638     case CallingConv::Fast:
8639       // Pass 'nest' parameter in EAX.
8640       // Must be kept in sync with X86CallingConv.td
8641       NestReg = X86::EAX;
8642       break;
8643     }
8644
8645     SDValue OutChains[4];
8646     SDValue Addr, Disp;
8647
8648     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8649                        DAG.getConstant(10, MVT::i32));
8650     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8651
8652     // This is storing the opcode for MOV32ri.
8653     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8654     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8655     OutChains[0] = DAG.getStore(Root, dl,
8656                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8657                                 Trmp, MachinePointerInfo(TrmpAddr),
8658                                 false, false, 0);
8659
8660     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8661                        DAG.getConstant(1, MVT::i32));
8662     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8663                                 MachinePointerInfo(TrmpAddr, 1),
8664                                 false, false, 1);
8665
8666     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8667     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8668                        DAG.getConstant(5, MVT::i32));
8669     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8670                                 MachinePointerInfo(TrmpAddr, 5),
8671                                 false, false, 1);
8672
8673     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8674                        DAG.getConstant(6, MVT::i32));
8675     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8676                                 MachinePointerInfo(TrmpAddr, 6),
8677                                 false, false, 1);
8678
8679     SDValue Ops[] =
8680       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8681     return DAG.getMergeValues(Ops, 2, dl);
8682   }
8683 }
8684
8685 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8686                                             SelectionDAG &DAG) const {
8687   /*
8688    The rounding mode is in bits 11:10 of FPSR, and has the following
8689    settings:
8690      00 Round to nearest
8691      01 Round to -inf
8692      10 Round to +inf
8693      11 Round to 0
8694
8695   FLT_ROUNDS, on the other hand, expects the following:
8696     -1 Undefined
8697      0 Round to 0
8698      1 Round to nearest
8699      2 Round to +inf
8700      3 Round to -inf
8701
8702   To perform the conversion, we do:
8703     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8704   */
8705
8706   MachineFunction &MF = DAG.getMachineFunction();
8707   const TargetMachine &TM = MF.getTarget();
8708   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8709   unsigned StackAlignment = TFI.getStackAlignment();
8710   EVT VT = Op.getValueType();
8711   DebugLoc DL = Op.getDebugLoc();
8712
8713   // Save FP Control Word to stack slot
8714   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8715   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8716
8717
8718   MachineMemOperand *MMO =
8719    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8720                            MachineMemOperand::MOStore, 2, 2);
8721
8722   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8723   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8724                                           DAG.getVTList(MVT::Other),
8725                                           Ops, 2, MVT::i16, MMO);
8726
8727   // Load FP Control Word from stack slot
8728   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8729                             MachinePointerInfo(), false, false, 0);
8730
8731   // Transform as necessary
8732   SDValue CWD1 =
8733     DAG.getNode(ISD::SRL, DL, MVT::i16,
8734                 DAG.getNode(ISD::AND, DL, MVT::i16,
8735                             CWD, DAG.getConstant(0x800, MVT::i16)),
8736                 DAG.getConstant(11, MVT::i8));
8737   SDValue CWD2 =
8738     DAG.getNode(ISD::SRL, DL, MVT::i16,
8739                 DAG.getNode(ISD::AND, DL, MVT::i16,
8740                             CWD, DAG.getConstant(0x400, MVT::i16)),
8741                 DAG.getConstant(9, MVT::i8));
8742
8743   SDValue RetVal =
8744     DAG.getNode(ISD::AND, DL, MVT::i16,
8745                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8746                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8747                             DAG.getConstant(1, MVT::i16)),
8748                 DAG.getConstant(3, MVT::i16));
8749
8750
8751   return DAG.getNode((VT.getSizeInBits() < 16 ?
8752                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8753 }
8754
8755 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8756   EVT VT = Op.getValueType();
8757   EVT OpVT = VT;
8758   unsigned NumBits = VT.getSizeInBits();
8759   DebugLoc dl = Op.getDebugLoc();
8760
8761   Op = Op.getOperand(0);
8762   if (VT == MVT::i8) {
8763     // Zero extend to i32 since there is not an i8 bsr.
8764     OpVT = MVT::i32;
8765     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8766   }
8767
8768   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8769   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8770   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8771
8772   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8773   SDValue Ops[] = {
8774     Op,
8775     DAG.getConstant(NumBits+NumBits-1, OpVT),
8776     DAG.getConstant(X86::COND_E, MVT::i8),
8777     Op.getValue(1)
8778   };
8779   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8780
8781   // Finally xor with NumBits-1.
8782   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8783
8784   if (VT == MVT::i8)
8785     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8786   return Op;
8787 }
8788
8789 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8790   EVT VT = Op.getValueType();
8791   EVT OpVT = VT;
8792   unsigned NumBits = VT.getSizeInBits();
8793   DebugLoc dl = Op.getDebugLoc();
8794
8795   Op = Op.getOperand(0);
8796   if (VT == MVT::i8) {
8797     OpVT = MVT::i32;
8798     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8799   }
8800
8801   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8802   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8803   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8804
8805   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8806   SDValue Ops[] = {
8807     Op,
8808     DAG.getConstant(NumBits, OpVT),
8809     DAG.getConstant(X86::COND_E, MVT::i8),
8810     Op.getValue(1)
8811   };
8812   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8813
8814   if (VT == MVT::i8)
8815     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8816   return Op;
8817 }
8818
8819 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8820   EVT VT = Op.getValueType();
8821   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8822   DebugLoc dl = Op.getDebugLoc();
8823
8824   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8825   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8826   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8827   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8828   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8829   //
8830   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8831   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8832   //  return AloBlo + AloBhi + AhiBlo;
8833
8834   SDValue A = Op.getOperand(0);
8835   SDValue B = Op.getOperand(1);
8836
8837   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8838                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8839                        A, DAG.getConstant(32, MVT::i32));
8840   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8841                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8842                        B, DAG.getConstant(32, MVT::i32));
8843   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8844                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8845                        A, B);
8846   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8847                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8848                        A, Bhi);
8849   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8850                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8851                        Ahi, B);
8852   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8853                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8854                        AloBhi, DAG.getConstant(32, MVT::i32));
8855   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8856                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8857                        AhiBlo, DAG.getConstant(32, MVT::i32));
8858   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8859   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8860   return Res;
8861 }
8862
8863 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8864
8865   EVT VT = Op.getValueType();
8866   DebugLoc dl = Op.getDebugLoc();
8867   SDValue R = Op.getOperand(0);
8868   SDValue Amt = Op.getOperand(1);
8869
8870   LLVMContext *Context = DAG.getContext();
8871
8872   // Must have SSE2.
8873   if (!Subtarget->hasSSE2()) return SDValue();
8874
8875   // Optimize shl/srl/sra with constant shift amount.
8876   if (isSplatVector(Amt.getNode())) {
8877     SDValue SclrAmt = Amt->getOperand(0);
8878     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8879       uint64_t ShiftAmt = C->getZExtValue();
8880
8881       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8882        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8883                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8884                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8885
8886       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8887        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8888                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8889                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8890
8891       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8892        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8893                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8894                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8895
8896       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8897        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8898                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8899                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8900
8901       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8902        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8903                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8904                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8905
8906       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8907        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8908                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8909                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8910
8911       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8912        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8913                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8914                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8915
8916       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8917        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8918                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8919                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8920     }
8921   }
8922
8923   // Lower SHL with variable shift amount.
8924   // Cannot lower SHL without SSE4.1 or later.
8925   if (!Subtarget->hasSSE41()) return SDValue();
8926
8927   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8928     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8929                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8930                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8931
8932     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8933
8934     std::vector<Constant*> CV(4, CI);
8935     Constant *C = ConstantVector::get(CV);
8936     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8937     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8938                                  MachinePointerInfo::getConstantPool(),
8939                                  false, false, 16);
8940
8941     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8942     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8943     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8944     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8945   }
8946   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8947     // a = a << 5;
8948     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8949                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8950                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8951
8952     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8953     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8954
8955     std::vector<Constant*> CVM1(16, CM1);
8956     std::vector<Constant*> CVM2(16, CM2);
8957     Constant *C = ConstantVector::get(CVM1);
8958     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8959     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8960                             MachinePointerInfo::getConstantPool(),
8961                             false, false, 16);
8962
8963     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8964     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8965     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8966                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8967                     DAG.getConstant(4, MVT::i32));
8968     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8969     // a += a
8970     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8971
8972     C = ConstantVector::get(CVM2);
8973     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8974     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8975                     MachinePointerInfo::getConstantPool(),
8976                     false, false, 16);
8977
8978     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8979     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8980     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8981                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8982                     DAG.getConstant(2, MVT::i32));
8983     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8984     // a += a
8985     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8986
8987     // return pblendv(r, r+r, a);
8988     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8989                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8990     return R;
8991   }
8992   return SDValue();
8993 }
8994
8995 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8996   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8997   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8998   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8999   // has only one use.
9000   SDNode *N = Op.getNode();
9001   SDValue LHS = N->getOperand(0);
9002   SDValue RHS = N->getOperand(1);
9003   unsigned BaseOp = 0;
9004   unsigned Cond = 0;
9005   DebugLoc DL = Op.getDebugLoc();
9006   switch (Op.getOpcode()) {
9007   default: llvm_unreachable("Unknown ovf instruction!");
9008   case ISD::SADDO:
9009     // A subtract of one will be selected as a INC. Note that INC doesn't
9010     // set CF, so we can't do this for UADDO.
9011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9012       if (C->isOne()) {
9013         BaseOp = X86ISD::INC;
9014         Cond = X86::COND_O;
9015         break;
9016       }
9017     BaseOp = X86ISD::ADD;
9018     Cond = X86::COND_O;
9019     break;
9020   case ISD::UADDO:
9021     BaseOp = X86ISD::ADD;
9022     Cond = X86::COND_B;
9023     break;
9024   case ISD::SSUBO:
9025     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9026     // set CF, so we can't do this for USUBO.
9027     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9028       if (C->isOne()) {
9029         BaseOp = X86ISD::DEC;
9030         Cond = X86::COND_O;
9031         break;
9032       }
9033     BaseOp = X86ISD::SUB;
9034     Cond = X86::COND_O;
9035     break;
9036   case ISD::USUBO:
9037     BaseOp = X86ISD::SUB;
9038     Cond = X86::COND_B;
9039     break;
9040   case ISD::SMULO:
9041     BaseOp = X86ISD::SMUL;
9042     Cond = X86::COND_O;
9043     break;
9044   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9045     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9046                                  MVT::i32);
9047     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9048
9049     SDValue SetCC =
9050       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9051                   DAG.getConstant(X86::COND_O, MVT::i32),
9052                   SDValue(Sum.getNode(), 2));
9053
9054     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9055     return Sum;
9056   }
9057   }
9058
9059   // Also sets EFLAGS.
9060   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9061   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9062
9063   SDValue SetCC =
9064     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9065                 DAG.getConstant(Cond, MVT::i32),
9066                 SDValue(Sum.getNode(), 1));
9067
9068   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9069   return Sum;
9070 }
9071
9072 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9073   DebugLoc dl = Op.getDebugLoc();
9074
9075   if (!Subtarget->hasSSE2()) {
9076     SDValue Chain = Op.getOperand(0);
9077     SDValue Zero = DAG.getConstant(0,
9078                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9079     SDValue Ops[] = {
9080       DAG.getRegister(X86::ESP, MVT::i32), // Base
9081       DAG.getTargetConstant(1, MVT::i8),   // Scale
9082       DAG.getRegister(0, MVT::i32),        // Index
9083       DAG.getTargetConstant(0, MVT::i32),  // Disp
9084       DAG.getRegister(0, MVT::i32),        // Segment.
9085       Zero,
9086       Chain
9087     };
9088     SDNode *Res =
9089       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9090                           array_lengthof(Ops));
9091     return SDValue(Res, 0);
9092   }
9093
9094   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9095   if (!isDev)
9096     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9097
9098   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9099   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9100   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9101   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9102
9103   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9104   if (!Op1 && !Op2 && !Op3 && Op4)
9105     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9106
9107   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9108   if (Op1 && !Op2 && !Op3 && !Op4)
9109     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9110
9111   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9112   //           (MFENCE)>;
9113   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9114 }
9115
9116 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9117   EVT T = Op.getValueType();
9118   DebugLoc DL = Op.getDebugLoc();
9119   unsigned Reg = 0;
9120   unsigned size = 0;
9121   switch(T.getSimpleVT().SimpleTy) {
9122   default:
9123     assert(false && "Invalid value type!");
9124   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9125   case MVT::i16: Reg = X86::AX;  size = 2; break;
9126   case MVT::i32: Reg = X86::EAX; size = 4; break;
9127   case MVT::i64:
9128     assert(Subtarget->is64Bit() && "Node not type legal!");
9129     Reg = X86::RAX; size = 8;
9130     break;
9131   }
9132   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9133                                     Op.getOperand(2), SDValue());
9134   SDValue Ops[] = { cpIn.getValue(0),
9135                     Op.getOperand(1),
9136                     Op.getOperand(3),
9137                     DAG.getTargetConstant(size, MVT::i8),
9138                     cpIn.getValue(1) };
9139   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9140   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9141   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9142                                            Ops, 5, T, MMO);
9143   SDValue cpOut =
9144     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9145   return cpOut;
9146 }
9147
9148 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9149                                                  SelectionDAG &DAG) const {
9150   assert(Subtarget->is64Bit() && "Result not type legalized?");
9151   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9152   SDValue TheChain = Op.getOperand(0);
9153   DebugLoc dl = Op.getDebugLoc();
9154   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9155   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9156   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9157                                    rax.getValue(2));
9158   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9159                             DAG.getConstant(32, MVT::i8));
9160   SDValue Ops[] = {
9161     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9162     rdx.getValue(1)
9163   };
9164   return DAG.getMergeValues(Ops, 2, dl);
9165 }
9166
9167 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9168                                             SelectionDAG &DAG) const {
9169   EVT SrcVT = Op.getOperand(0).getValueType();
9170   EVT DstVT = Op.getValueType();
9171   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9172          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9173   assert((DstVT == MVT::i64 ||
9174           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9175          "Unexpected custom BITCAST");
9176   // i64 <=> MMX conversions are Legal.
9177   if (SrcVT==MVT::i64 && DstVT.isVector())
9178     return Op;
9179   if (DstVT==MVT::i64 && SrcVT.isVector())
9180     return Op;
9181   // MMX <=> MMX conversions are Legal.
9182   if (SrcVT.isVector() && DstVT.isVector())
9183     return Op;
9184   // All other conversions need to be expanded.
9185   return SDValue();
9186 }
9187
9188 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9189   SDNode *Node = Op.getNode();
9190   DebugLoc dl = Node->getDebugLoc();
9191   EVT T = Node->getValueType(0);
9192   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9193                               DAG.getConstant(0, T), Node->getOperand(2));
9194   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9195                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9196                        Node->getOperand(0),
9197                        Node->getOperand(1), negOp,
9198                        cast<AtomicSDNode>(Node)->getSrcValue(),
9199                        cast<AtomicSDNode>(Node)->getAlignment());
9200 }
9201
9202 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9203   EVT VT = Op.getNode()->getValueType(0);
9204
9205   // Let legalize expand this if it isn't a legal type yet.
9206   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9207     return SDValue();
9208
9209   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9210
9211   unsigned Opc;
9212   bool ExtraOp = false;
9213   switch (Op.getOpcode()) {
9214   default: assert(0 && "Invalid code");
9215   case ISD::ADDC: Opc = X86ISD::ADD; break;
9216   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9217   case ISD::SUBC: Opc = X86ISD::SUB; break;
9218   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9219   }
9220
9221   if (!ExtraOp)
9222     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9223                        Op.getOperand(1));
9224   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9225                      Op.getOperand(1), Op.getOperand(2));
9226 }
9227
9228 /// LowerOperation - Provide custom lowering hooks for some operations.
9229 ///
9230 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9231   switch (Op.getOpcode()) {
9232   default: llvm_unreachable("Should not custom lower this!");
9233   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9234   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9235   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9236   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9237   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9238   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9239   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9240   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9241   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9242   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9243   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9244   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9245   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9246   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9247   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9248   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9249   case ISD::SHL_PARTS:
9250   case ISD::SRA_PARTS:
9251   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9252   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9253   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9254   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9255   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9256   case ISD::FABS:               return LowerFABS(Op, DAG);
9257   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9258   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9259   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9260   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9261   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9262   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9263   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9264   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9265   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9266   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9267   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9268   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9269   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9270   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9271   case ISD::FRAME_TO_ARGS_OFFSET:
9272                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9273   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9274   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9275   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9276   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9277   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9278   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9279   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9280   case ISD::SRA:
9281   case ISD::SRL:
9282   case ISD::SHL:                return LowerShift(Op, DAG);
9283   case ISD::SADDO:
9284   case ISD::UADDO:
9285   case ISD::SSUBO:
9286   case ISD::USUBO:
9287   case ISD::SMULO:
9288   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9289   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9290   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9291   case ISD::ADDC:
9292   case ISD::ADDE:
9293   case ISD::SUBC:
9294   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9295   }
9296 }
9297
9298 void X86TargetLowering::
9299 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9300                         SelectionDAG &DAG, unsigned NewOp) const {
9301   EVT T = Node->getValueType(0);
9302   DebugLoc dl = Node->getDebugLoc();
9303   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9304
9305   SDValue Chain = Node->getOperand(0);
9306   SDValue In1 = Node->getOperand(1);
9307   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9308                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9309   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9310                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9311   SDValue Ops[] = { Chain, In1, In2L, In2H };
9312   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9313   SDValue Result =
9314     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9315                             cast<MemSDNode>(Node)->getMemOperand());
9316   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9317   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9318   Results.push_back(Result.getValue(2));
9319 }
9320
9321 /// ReplaceNodeResults - Replace a node with an illegal result type
9322 /// with a new node built out of custom code.
9323 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9324                                            SmallVectorImpl<SDValue>&Results,
9325                                            SelectionDAG &DAG) const {
9326   DebugLoc dl = N->getDebugLoc();
9327   switch (N->getOpcode()) {
9328   default:
9329     assert(false && "Do not know how to custom type legalize this operation!");
9330     return;
9331   case ISD::ADDC:
9332   case ISD::ADDE:
9333   case ISD::SUBC:
9334   case ISD::SUBE:
9335     // We don't want to expand or promote these.
9336     return;
9337   case ISD::FP_TO_SINT: {
9338     std::pair<SDValue,SDValue> Vals =
9339         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9340     SDValue FIST = Vals.first, StackSlot = Vals.second;
9341     if (FIST.getNode() != 0) {
9342       EVT VT = N->getValueType(0);
9343       // Return a load from the stack slot.
9344       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9345                                     MachinePointerInfo(), false, false, 0));
9346     }
9347     return;
9348   }
9349   case ISD::READCYCLECOUNTER: {
9350     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9351     SDValue TheChain = N->getOperand(0);
9352     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9353     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9354                                      rd.getValue(1));
9355     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9356                                      eax.getValue(2));
9357     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9358     SDValue Ops[] = { eax, edx };
9359     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9360     Results.push_back(edx.getValue(1));
9361     return;
9362   }
9363   case ISD::ATOMIC_CMP_SWAP: {
9364     EVT T = N->getValueType(0);
9365     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9366     SDValue cpInL, cpInH;
9367     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9368                         DAG.getConstant(0, MVT::i32));
9369     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9370                         DAG.getConstant(1, MVT::i32));
9371     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9372     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9373                              cpInL.getValue(1));
9374     SDValue swapInL, swapInH;
9375     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9376                           DAG.getConstant(0, MVT::i32));
9377     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9378                           DAG.getConstant(1, MVT::i32));
9379     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9380                                cpInH.getValue(1));
9381     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9382                                swapInL.getValue(1));
9383     SDValue Ops[] = { swapInH.getValue(0),
9384                       N->getOperand(1),
9385                       swapInH.getValue(1) };
9386     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9387     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9388     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9389                                              Ops, 3, T, MMO);
9390     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9391                                         MVT::i32, Result.getValue(1));
9392     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9393                                         MVT::i32, cpOutL.getValue(2));
9394     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9395     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9396     Results.push_back(cpOutH.getValue(1));
9397     return;
9398   }
9399   case ISD::ATOMIC_LOAD_ADD:
9400     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9401     return;
9402   case ISD::ATOMIC_LOAD_AND:
9403     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9404     return;
9405   case ISD::ATOMIC_LOAD_NAND:
9406     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9407     return;
9408   case ISD::ATOMIC_LOAD_OR:
9409     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9410     return;
9411   case ISD::ATOMIC_LOAD_SUB:
9412     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9413     return;
9414   case ISD::ATOMIC_LOAD_XOR:
9415     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9416     return;
9417   case ISD::ATOMIC_SWAP:
9418     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9419     return;
9420   }
9421 }
9422
9423 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9424   switch (Opcode) {
9425   default: return NULL;
9426   case X86ISD::BSF:                return "X86ISD::BSF";
9427   case X86ISD::BSR:                return "X86ISD::BSR";
9428   case X86ISD::SHLD:               return "X86ISD::SHLD";
9429   case X86ISD::SHRD:               return "X86ISD::SHRD";
9430   case X86ISD::FAND:               return "X86ISD::FAND";
9431   case X86ISD::FOR:                return "X86ISD::FOR";
9432   case X86ISD::FXOR:               return "X86ISD::FXOR";
9433   case X86ISD::FSRL:               return "X86ISD::FSRL";
9434   case X86ISD::FILD:               return "X86ISD::FILD";
9435   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9436   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9437   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9438   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9439   case X86ISD::FLD:                return "X86ISD::FLD";
9440   case X86ISD::FST:                return "X86ISD::FST";
9441   case X86ISD::CALL:               return "X86ISD::CALL";
9442   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9443   case X86ISD::BT:                 return "X86ISD::BT";
9444   case X86ISD::CMP:                return "X86ISD::CMP";
9445   case X86ISD::COMI:               return "X86ISD::COMI";
9446   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9447   case X86ISD::SETCC:              return "X86ISD::SETCC";
9448   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9449   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9450   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9451   case X86ISD::CMOV:               return "X86ISD::CMOV";
9452   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9453   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9454   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9455   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9456   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9457   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9458   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9459   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9460   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9461   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9462   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9463   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9464   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9465   case X86ISD::PANDN:              return "X86ISD::PANDN";
9466   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9467   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9468   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9469   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9470   case X86ISD::FMAX:               return "X86ISD::FMAX";
9471   case X86ISD::FMIN:               return "X86ISD::FMIN";
9472   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9473   case X86ISD::FRCP:               return "X86ISD::FRCP";
9474   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9475   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9476   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9477   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9478   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9479   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9480   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9481   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9482   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9483   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9484   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9485   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9486   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9487   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9488   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9489   case X86ISD::VSHL:               return "X86ISD::VSHL";
9490   case X86ISD::VSRL:               return "X86ISD::VSRL";
9491   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9492   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9493   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9494   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9495   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9496   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9497   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9498   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9499   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9500   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9501   case X86ISD::ADD:                return "X86ISD::ADD";
9502   case X86ISD::SUB:                return "X86ISD::SUB";
9503   case X86ISD::ADC:                return "X86ISD::ADC";
9504   case X86ISD::SBB:                return "X86ISD::SBB";
9505   case X86ISD::SMUL:               return "X86ISD::SMUL";
9506   case X86ISD::UMUL:               return "X86ISD::UMUL";
9507   case X86ISD::INC:                return "X86ISD::INC";
9508   case X86ISD::DEC:                return "X86ISD::DEC";
9509   case X86ISD::OR:                 return "X86ISD::OR";
9510   case X86ISD::XOR:                return "X86ISD::XOR";
9511   case X86ISD::AND:                return "X86ISD::AND";
9512   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9513   case X86ISD::PTEST:              return "X86ISD::PTEST";
9514   case X86ISD::TESTP:              return "X86ISD::TESTP";
9515   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9516   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9517   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9518   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9519   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9520   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9521   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9522   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9523   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9524   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9525   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9526   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9527   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9528   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9529   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9530   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9531   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9532   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9533   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9534   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9535   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9536   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9537   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9538   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9539   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9540   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9541   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9542   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9543   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9544   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9545   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9546   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9547   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9548   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9549   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9550   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9551   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9552   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9553   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9554   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9555   }
9556 }
9557
9558 // isLegalAddressingMode - Return true if the addressing mode represented
9559 // by AM is legal for this target, for a load/store of the specified type.
9560 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9561                                               const Type *Ty) const {
9562   // X86 supports extremely general addressing modes.
9563   CodeModel::Model M = getTargetMachine().getCodeModel();
9564   Reloc::Model R = getTargetMachine().getRelocationModel();
9565
9566   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9567   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9568     return false;
9569
9570   if (AM.BaseGV) {
9571     unsigned GVFlags =
9572       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9573
9574     // If a reference to this global requires an extra load, we can't fold it.
9575     if (isGlobalStubReference(GVFlags))
9576       return false;
9577
9578     // If BaseGV requires a register for the PIC base, we cannot also have a
9579     // BaseReg specified.
9580     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9581       return false;
9582
9583     // If lower 4G is not available, then we must use rip-relative addressing.
9584     if ((M != CodeModel::Small || R != Reloc::Static) &&
9585         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9586       return false;
9587   }
9588
9589   switch (AM.Scale) {
9590   case 0:
9591   case 1:
9592   case 2:
9593   case 4:
9594   case 8:
9595     // These scales always work.
9596     break;
9597   case 3:
9598   case 5:
9599   case 9:
9600     // These scales are formed with basereg+scalereg.  Only accept if there is
9601     // no basereg yet.
9602     if (AM.HasBaseReg)
9603       return false;
9604     break;
9605   default:  // Other stuff never works.
9606     return false;
9607   }
9608
9609   return true;
9610 }
9611
9612
9613 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9614   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9615     return false;
9616   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9617   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9618   if (NumBits1 <= NumBits2)
9619     return false;
9620   return true;
9621 }
9622
9623 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9624   if (!VT1.isInteger() || !VT2.isInteger())
9625     return false;
9626   unsigned NumBits1 = VT1.getSizeInBits();
9627   unsigned NumBits2 = VT2.getSizeInBits();
9628   if (NumBits1 <= NumBits2)
9629     return false;
9630   return true;
9631 }
9632
9633 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9634   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9635   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9636 }
9637
9638 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9639   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9640   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9641 }
9642
9643 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9644   // i16 instructions are longer (0x66 prefix) and potentially slower.
9645   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9646 }
9647
9648 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9649 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9650 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9651 /// are assumed to be legal.
9652 bool
9653 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9654                                       EVT VT) const {
9655   // Very little shuffling can be done for 64-bit vectors right now.
9656   if (VT.getSizeInBits() == 64)
9657     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9658
9659   // FIXME: pshufb, blends, shifts.
9660   return (VT.getVectorNumElements() == 2 ||
9661           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9662           isMOVLMask(M, VT) ||
9663           isSHUFPMask(M, VT) ||
9664           isPSHUFDMask(M, VT) ||
9665           isPSHUFHWMask(M, VT) ||
9666           isPSHUFLWMask(M, VT) ||
9667           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9668           isUNPCKLMask(M, VT) ||
9669           isUNPCKHMask(M, VT) ||
9670           isUNPCKL_v_undef_Mask(M, VT) ||
9671           isUNPCKH_v_undef_Mask(M, VT));
9672 }
9673
9674 bool
9675 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9676                                           EVT VT) const {
9677   unsigned NumElts = VT.getVectorNumElements();
9678   // FIXME: This collection of masks seems suspect.
9679   if (NumElts == 2)
9680     return true;
9681   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9682     return (isMOVLMask(Mask, VT)  ||
9683             isCommutedMOVLMask(Mask, VT, true) ||
9684             isSHUFPMask(Mask, VT) ||
9685             isCommutedSHUFPMask(Mask, VT));
9686   }
9687   return false;
9688 }
9689
9690 //===----------------------------------------------------------------------===//
9691 //                           X86 Scheduler Hooks
9692 //===----------------------------------------------------------------------===//
9693
9694 // private utility function
9695 MachineBasicBlock *
9696 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9697                                                        MachineBasicBlock *MBB,
9698                                                        unsigned regOpc,
9699                                                        unsigned immOpc,
9700                                                        unsigned LoadOpc,
9701                                                        unsigned CXchgOpc,
9702                                                        unsigned notOpc,
9703                                                        unsigned EAXreg,
9704                                                        TargetRegisterClass *RC,
9705                                                        bool invSrc) const {
9706   // For the atomic bitwise operator, we generate
9707   //   thisMBB:
9708   //   newMBB:
9709   //     ld  t1 = [bitinstr.addr]
9710   //     op  t2 = t1, [bitinstr.val]
9711   //     mov EAX = t1
9712   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9713   //     bz  newMBB
9714   //     fallthrough -->nextMBB
9715   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9716   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9717   MachineFunction::iterator MBBIter = MBB;
9718   ++MBBIter;
9719
9720   /// First build the CFG
9721   MachineFunction *F = MBB->getParent();
9722   MachineBasicBlock *thisMBB = MBB;
9723   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9724   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9725   F->insert(MBBIter, newMBB);
9726   F->insert(MBBIter, nextMBB);
9727
9728   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9729   nextMBB->splice(nextMBB->begin(), thisMBB,
9730                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9731                   thisMBB->end());
9732   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9733
9734   // Update thisMBB to fall through to newMBB
9735   thisMBB->addSuccessor(newMBB);
9736
9737   // newMBB jumps to itself and fall through to nextMBB
9738   newMBB->addSuccessor(nextMBB);
9739   newMBB->addSuccessor(newMBB);
9740
9741   // Insert instructions into newMBB based on incoming instruction
9742   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9743          "unexpected number of operands");
9744   DebugLoc dl = bInstr->getDebugLoc();
9745   MachineOperand& destOper = bInstr->getOperand(0);
9746   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9747   int numArgs = bInstr->getNumOperands() - 1;
9748   for (int i=0; i < numArgs; ++i)
9749     argOpers[i] = &bInstr->getOperand(i+1);
9750
9751   // x86 address has 4 operands: base, index, scale, and displacement
9752   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9753   int valArgIndx = lastAddrIndx + 1;
9754
9755   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9756   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9757   for (int i=0; i <= lastAddrIndx; ++i)
9758     (*MIB).addOperand(*argOpers[i]);
9759
9760   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9761   if (invSrc) {
9762     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9763   }
9764   else
9765     tt = t1;
9766
9767   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9768   assert((argOpers[valArgIndx]->isReg() ||
9769           argOpers[valArgIndx]->isImm()) &&
9770          "invalid operand");
9771   if (argOpers[valArgIndx]->isReg())
9772     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9773   else
9774     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9775   MIB.addReg(tt);
9776   (*MIB).addOperand(*argOpers[valArgIndx]);
9777
9778   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9779   MIB.addReg(t1);
9780
9781   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9782   for (int i=0; i <= lastAddrIndx; ++i)
9783     (*MIB).addOperand(*argOpers[i]);
9784   MIB.addReg(t2);
9785   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9786   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9787                     bInstr->memoperands_end());
9788
9789   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9790   MIB.addReg(EAXreg);
9791
9792   // insert branch
9793   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9794
9795   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9796   return nextMBB;
9797 }
9798
9799 // private utility function:  64 bit atomics on 32 bit host.
9800 MachineBasicBlock *
9801 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9802                                                        MachineBasicBlock *MBB,
9803                                                        unsigned regOpcL,
9804                                                        unsigned regOpcH,
9805                                                        unsigned immOpcL,
9806                                                        unsigned immOpcH,
9807                                                        bool invSrc) const {
9808   // For the atomic bitwise operator, we generate
9809   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9810   //     ld t1,t2 = [bitinstr.addr]
9811   //   newMBB:
9812   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9813   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9814   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9815   //     mov ECX, EBX <- t5, t6
9816   //     mov EAX, EDX <- t1, t2
9817   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9818   //     mov t3, t4 <- EAX, EDX
9819   //     bz  newMBB
9820   //     result in out1, out2
9821   //     fallthrough -->nextMBB
9822
9823   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9824   const unsigned LoadOpc = X86::MOV32rm;
9825   const unsigned NotOpc = X86::NOT32r;
9826   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9827   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9828   MachineFunction::iterator MBBIter = MBB;
9829   ++MBBIter;
9830
9831   /// First build the CFG
9832   MachineFunction *F = MBB->getParent();
9833   MachineBasicBlock *thisMBB = MBB;
9834   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9835   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9836   F->insert(MBBIter, newMBB);
9837   F->insert(MBBIter, nextMBB);
9838
9839   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9840   nextMBB->splice(nextMBB->begin(), thisMBB,
9841                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9842                   thisMBB->end());
9843   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9844
9845   // Update thisMBB to fall through to newMBB
9846   thisMBB->addSuccessor(newMBB);
9847
9848   // newMBB jumps to itself and fall through to nextMBB
9849   newMBB->addSuccessor(nextMBB);
9850   newMBB->addSuccessor(newMBB);
9851
9852   DebugLoc dl = bInstr->getDebugLoc();
9853   // Insert instructions into newMBB based on incoming instruction
9854   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9855   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9856          "unexpected number of operands");
9857   MachineOperand& dest1Oper = bInstr->getOperand(0);
9858   MachineOperand& dest2Oper = bInstr->getOperand(1);
9859   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9860   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9861     argOpers[i] = &bInstr->getOperand(i+2);
9862
9863     // We use some of the operands multiple times, so conservatively just
9864     // clear any kill flags that might be present.
9865     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9866       argOpers[i]->setIsKill(false);
9867   }
9868
9869   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9870   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9871
9872   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9873   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9874   for (int i=0; i <= lastAddrIndx; ++i)
9875     (*MIB).addOperand(*argOpers[i]);
9876   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9877   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9878   // add 4 to displacement.
9879   for (int i=0; i <= lastAddrIndx-2; ++i)
9880     (*MIB).addOperand(*argOpers[i]);
9881   MachineOperand newOp3 = *(argOpers[3]);
9882   if (newOp3.isImm())
9883     newOp3.setImm(newOp3.getImm()+4);
9884   else
9885     newOp3.setOffset(newOp3.getOffset()+4);
9886   (*MIB).addOperand(newOp3);
9887   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9888
9889   // t3/4 are defined later, at the bottom of the loop
9890   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9891   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9892   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9893     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9894   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9895     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9896
9897   // The subsequent operations should be using the destination registers of
9898   //the PHI instructions.
9899   if (invSrc) {
9900     t1 = F->getRegInfo().createVirtualRegister(RC);
9901     t2 = F->getRegInfo().createVirtualRegister(RC);
9902     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9903     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9904   } else {
9905     t1 = dest1Oper.getReg();
9906     t2 = dest2Oper.getReg();
9907   }
9908
9909   int valArgIndx = lastAddrIndx + 1;
9910   assert((argOpers[valArgIndx]->isReg() ||
9911           argOpers[valArgIndx]->isImm()) &&
9912          "invalid operand");
9913   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9914   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9915   if (argOpers[valArgIndx]->isReg())
9916     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9917   else
9918     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9919   if (regOpcL != X86::MOV32rr)
9920     MIB.addReg(t1);
9921   (*MIB).addOperand(*argOpers[valArgIndx]);
9922   assert(argOpers[valArgIndx + 1]->isReg() ==
9923          argOpers[valArgIndx]->isReg());
9924   assert(argOpers[valArgIndx + 1]->isImm() ==
9925          argOpers[valArgIndx]->isImm());
9926   if (argOpers[valArgIndx + 1]->isReg())
9927     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9928   else
9929     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9930   if (regOpcH != X86::MOV32rr)
9931     MIB.addReg(t2);
9932   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9933
9934   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9935   MIB.addReg(t1);
9936   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9937   MIB.addReg(t2);
9938
9939   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9940   MIB.addReg(t5);
9941   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9942   MIB.addReg(t6);
9943
9944   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9945   for (int i=0; i <= lastAddrIndx; ++i)
9946     (*MIB).addOperand(*argOpers[i]);
9947
9948   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9949   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9950                     bInstr->memoperands_end());
9951
9952   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9953   MIB.addReg(X86::EAX);
9954   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9955   MIB.addReg(X86::EDX);
9956
9957   // insert branch
9958   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9959
9960   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9961   return nextMBB;
9962 }
9963
9964 // private utility function
9965 MachineBasicBlock *
9966 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9967                                                       MachineBasicBlock *MBB,
9968                                                       unsigned cmovOpc) const {
9969   // For the atomic min/max operator, we generate
9970   //   thisMBB:
9971   //   newMBB:
9972   //     ld t1 = [min/max.addr]
9973   //     mov t2 = [min/max.val]
9974   //     cmp  t1, t2
9975   //     cmov[cond] t2 = t1
9976   //     mov EAX = t1
9977   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9978   //     bz   newMBB
9979   //     fallthrough -->nextMBB
9980   //
9981   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9982   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9983   MachineFunction::iterator MBBIter = MBB;
9984   ++MBBIter;
9985
9986   /// First build the CFG
9987   MachineFunction *F = MBB->getParent();
9988   MachineBasicBlock *thisMBB = MBB;
9989   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9990   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9991   F->insert(MBBIter, newMBB);
9992   F->insert(MBBIter, nextMBB);
9993
9994   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9995   nextMBB->splice(nextMBB->begin(), thisMBB,
9996                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9997                   thisMBB->end());
9998   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9999
10000   // Update thisMBB to fall through to newMBB
10001   thisMBB->addSuccessor(newMBB);
10002
10003   // newMBB jumps to newMBB and fall through to nextMBB
10004   newMBB->addSuccessor(nextMBB);
10005   newMBB->addSuccessor(newMBB);
10006
10007   DebugLoc dl = mInstr->getDebugLoc();
10008   // Insert instructions into newMBB based on incoming instruction
10009   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10010          "unexpected number of operands");
10011   MachineOperand& destOper = mInstr->getOperand(0);
10012   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10013   int numArgs = mInstr->getNumOperands() - 1;
10014   for (int i=0; i < numArgs; ++i)
10015     argOpers[i] = &mInstr->getOperand(i+1);
10016
10017   // x86 address has 4 operands: base, index, scale, and displacement
10018   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10019   int valArgIndx = lastAddrIndx + 1;
10020
10021   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10022   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10023   for (int i=0; i <= lastAddrIndx; ++i)
10024     (*MIB).addOperand(*argOpers[i]);
10025
10026   // We only support register and immediate values
10027   assert((argOpers[valArgIndx]->isReg() ||
10028           argOpers[valArgIndx]->isImm()) &&
10029          "invalid operand");
10030
10031   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10032   if (argOpers[valArgIndx]->isReg())
10033     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10034   else
10035     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10036   (*MIB).addOperand(*argOpers[valArgIndx]);
10037
10038   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10039   MIB.addReg(t1);
10040
10041   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10042   MIB.addReg(t1);
10043   MIB.addReg(t2);
10044
10045   // Generate movc
10046   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10047   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10048   MIB.addReg(t2);
10049   MIB.addReg(t1);
10050
10051   // Cmp and exchange if none has modified the memory location
10052   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10053   for (int i=0; i <= lastAddrIndx; ++i)
10054     (*MIB).addOperand(*argOpers[i]);
10055   MIB.addReg(t3);
10056   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10057   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10058                     mInstr->memoperands_end());
10059
10060   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10061   MIB.addReg(X86::EAX);
10062
10063   // insert branch
10064   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10065
10066   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10067   return nextMBB;
10068 }
10069
10070 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10071 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10072 // in the .td file.
10073 MachineBasicBlock *
10074 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10075                             unsigned numArgs, bool memArg) const {
10076   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10077          "Target must have SSE4.2 or AVX features enabled");
10078
10079   DebugLoc dl = MI->getDebugLoc();
10080   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10081   unsigned Opc;
10082   if (!Subtarget->hasAVX()) {
10083     if (memArg)
10084       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10085     else
10086       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10087   } else {
10088     if (memArg)
10089       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10090     else
10091       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10092   }
10093
10094   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10095   for (unsigned i = 0; i < numArgs; ++i) {
10096     MachineOperand &Op = MI->getOperand(i+1);
10097     if (!(Op.isReg() && Op.isImplicit()))
10098       MIB.addOperand(Op);
10099   }
10100   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10101     .addReg(X86::XMM0);
10102
10103   MI->eraseFromParent();
10104   return BB;
10105 }
10106
10107 MachineBasicBlock *
10108 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10109   DebugLoc dl = MI->getDebugLoc();
10110   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10111
10112   // Address into RAX/EAX, other two args into ECX, EDX.
10113   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10114   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10115   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10116   for (int i = 0; i < X86::AddrNumOperands; ++i)
10117     MIB.addOperand(MI->getOperand(i));
10118
10119   unsigned ValOps = X86::AddrNumOperands;
10120   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10121     .addReg(MI->getOperand(ValOps).getReg());
10122   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10123     .addReg(MI->getOperand(ValOps+1).getReg());
10124
10125   // The instruction doesn't actually take any operands though.
10126   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10127
10128   MI->eraseFromParent(); // The pseudo is gone now.
10129   return BB;
10130 }
10131
10132 MachineBasicBlock *
10133 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10134   DebugLoc dl = MI->getDebugLoc();
10135   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10136
10137   // First arg in ECX, the second in EAX.
10138   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10139     .addReg(MI->getOperand(0).getReg());
10140   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10141     .addReg(MI->getOperand(1).getReg());
10142
10143   // The instruction doesn't actually take any operands though.
10144   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10145
10146   MI->eraseFromParent(); // The pseudo is gone now.
10147   return BB;
10148 }
10149
10150 MachineBasicBlock *
10151 X86TargetLowering::EmitVAARG64WithCustomInserter(
10152                    MachineInstr *MI,
10153                    MachineBasicBlock *MBB) const {
10154   // Emit va_arg instruction on X86-64.
10155
10156   // Operands to this pseudo-instruction:
10157   // 0  ) Output        : destination address (reg)
10158   // 1-5) Input         : va_list address (addr, i64mem)
10159   // 6  ) ArgSize       : Size (in bytes) of vararg type
10160   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10161   // 8  ) Align         : Alignment of type
10162   // 9  ) EFLAGS (implicit-def)
10163
10164   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10165   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10166
10167   unsigned DestReg = MI->getOperand(0).getReg();
10168   MachineOperand &Base = MI->getOperand(1);
10169   MachineOperand &Scale = MI->getOperand(2);
10170   MachineOperand &Index = MI->getOperand(3);
10171   MachineOperand &Disp = MI->getOperand(4);
10172   MachineOperand &Segment = MI->getOperand(5);
10173   unsigned ArgSize = MI->getOperand(6).getImm();
10174   unsigned ArgMode = MI->getOperand(7).getImm();
10175   unsigned Align = MI->getOperand(8).getImm();
10176
10177   // Memory Reference
10178   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10179   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10180   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10181
10182   // Machine Information
10183   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10184   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10185   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10186   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10187   DebugLoc DL = MI->getDebugLoc();
10188
10189   // struct va_list {
10190   //   i32   gp_offset
10191   //   i32   fp_offset
10192   //   i64   overflow_area (address)
10193   //   i64   reg_save_area (address)
10194   // }
10195   // sizeof(va_list) = 24
10196   // alignment(va_list) = 8
10197
10198   unsigned TotalNumIntRegs = 6;
10199   unsigned TotalNumXMMRegs = 8;
10200   bool UseGPOffset = (ArgMode == 1);
10201   bool UseFPOffset = (ArgMode == 2);
10202   unsigned MaxOffset = TotalNumIntRegs * 8 +
10203                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10204
10205   /* Align ArgSize to a multiple of 8 */
10206   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10207   bool NeedsAlign = (Align > 8);
10208
10209   MachineBasicBlock *thisMBB = MBB;
10210   MachineBasicBlock *overflowMBB;
10211   MachineBasicBlock *offsetMBB;
10212   MachineBasicBlock *endMBB;
10213
10214   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10215   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10216   unsigned OffsetReg = 0;
10217
10218   if (!UseGPOffset && !UseFPOffset) {
10219     // If we only pull from the overflow region, we don't create a branch.
10220     // We don't need to alter control flow.
10221     OffsetDestReg = 0; // unused
10222     OverflowDestReg = DestReg;
10223
10224     offsetMBB = NULL;
10225     overflowMBB = thisMBB;
10226     endMBB = thisMBB;
10227   } else {
10228     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10229     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10230     // If not, pull from overflow_area. (branch to overflowMBB)
10231     //
10232     //       thisMBB
10233     //         |     .
10234     //         |        .
10235     //     offsetMBB   overflowMBB
10236     //         |        .
10237     //         |     .
10238     //        endMBB
10239
10240     // Registers for the PHI in endMBB
10241     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10242     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10243
10244     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10245     MachineFunction *MF = MBB->getParent();
10246     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10247     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10248     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10249
10250     MachineFunction::iterator MBBIter = MBB;
10251     ++MBBIter;
10252
10253     // Insert the new basic blocks
10254     MF->insert(MBBIter, offsetMBB);
10255     MF->insert(MBBIter, overflowMBB);
10256     MF->insert(MBBIter, endMBB);
10257
10258     // Transfer the remainder of MBB and its successor edges to endMBB.
10259     endMBB->splice(endMBB->begin(), thisMBB,
10260                     llvm::next(MachineBasicBlock::iterator(MI)),
10261                     thisMBB->end());
10262     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10263
10264     // Make offsetMBB and overflowMBB successors of thisMBB
10265     thisMBB->addSuccessor(offsetMBB);
10266     thisMBB->addSuccessor(overflowMBB);
10267
10268     // endMBB is a successor of both offsetMBB and overflowMBB
10269     offsetMBB->addSuccessor(endMBB);
10270     overflowMBB->addSuccessor(endMBB);
10271
10272     // Load the offset value into a register
10273     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10274     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10275       .addOperand(Base)
10276       .addOperand(Scale)
10277       .addOperand(Index)
10278       .addDisp(Disp, UseFPOffset ? 4 : 0)
10279       .addOperand(Segment)
10280       .setMemRefs(MMOBegin, MMOEnd);
10281
10282     // Check if there is enough room left to pull this argument.
10283     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10284       .addReg(OffsetReg)
10285       .addImm(MaxOffset + 8 - ArgSizeA8);
10286
10287     // Branch to "overflowMBB" if offset >= max
10288     // Fall through to "offsetMBB" otherwise
10289     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10290       .addMBB(overflowMBB);
10291   }
10292
10293   // In offsetMBB, emit code to use the reg_save_area.
10294   if (offsetMBB) {
10295     assert(OffsetReg != 0);
10296
10297     // Read the reg_save_area address.
10298     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10299     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10300       .addOperand(Base)
10301       .addOperand(Scale)
10302       .addOperand(Index)
10303       .addDisp(Disp, 16)
10304       .addOperand(Segment)
10305       .setMemRefs(MMOBegin, MMOEnd);
10306
10307     // Zero-extend the offset
10308     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10309       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10310         .addImm(0)
10311         .addReg(OffsetReg)
10312         .addImm(X86::sub_32bit);
10313
10314     // Add the offset to the reg_save_area to get the final address.
10315     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10316       .addReg(OffsetReg64)
10317       .addReg(RegSaveReg);
10318
10319     // Compute the offset for the next argument
10320     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10321     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10322       .addReg(OffsetReg)
10323       .addImm(UseFPOffset ? 16 : 8);
10324
10325     // Store it back into the va_list.
10326     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10327       .addOperand(Base)
10328       .addOperand(Scale)
10329       .addOperand(Index)
10330       .addDisp(Disp, UseFPOffset ? 4 : 0)
10331       .addOperand(Segment)
10332       .addReg(NextOffsetReg)
10333       .setMemRefs(MMOBegin, MMOEnd);
10334
10335     // Jump to endMBB
10336     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10337       .addMBB(endMBB);
10338   }
10339
10340   //
10341   // Emit code to use overflow area
10342   //
10343
10344   // Load the overflow_area address into a register.
10345   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10346   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10347     .addOperand(Base)
10348     .addOperand(Scale)
10349     .addOperand(Index)
10350     .addDisp(Disp, 8)
10351     .addOperand(Segment)
10352     .setMemRefs(MMOBegin, MMOEnd);
10353
10354   // If we need to align it, do so. Otherwise, just copy the address
10355   // to OverflowDestReg.
10356   if (NeedsAlign) {
10357     // Align the overflow address
10358     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10359     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10360
10361     // aligned_addr = (addr + (align-1)) & ~(align-1)
10362     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10363       .addReg(OverflowAddrReg)
10364       .addImm(Align-1);
10365
10366     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10367       .addReg(TmpReg)
10368       .addImm(~(uint64_t)(Align-1));
10369   } else {
10370     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10371       .addReg(OverflowAddrReg);
10372   }
10373
10374   // Compute the next overflow address after this argument.
10375   // (the overflow address should be kept 8-byte aligned)
10376   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10377   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10378     .addReg(OverflowDestReg)
10379     .addImm(ArgSizeA8);
10380
10381   // Store the new overflow address.
10382   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10383     .addOperand(Base)
10384     .addOperand(Scale)
10385     .addOperand(Index)
10386     .addDisp(Disp, 8)
10387     .addOperand(Segment)
10388     .addReg(NextAddrReg)
10389     .setMemRefs(MMOBegin, MMOEnd);
10390
10391   // If we branched, emit the PHI to the front of endMBB.
10392   if (offsetMBB) {
10393     BuildMI(*endMBB, endMBB->begin(), DL,
10394             TII->get(X86::PHI), DestReg)
10395       .addReg(OffsetDestReg).addMBB(offsetMBB)
10396       .addReg(OverflowDestReg).addMBB(overflowMBB);
10397   }
10398
10399   // Erase the pseudo instruction
10400   MI->eraseFromParent();
10401
10402   return endMBB;
10403 }
10404
10405 MachineBasicBlock *
10406 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10407                                                  MachineInstr *MI,
10408                                                  MachineBasicBlock *MBB) const {
10409   // Emit code to save XMM registers to the stack. The ABI says that the
10410   // number of registers to save is given in %al, so it's theoretically
10411   // possible to do an indirect jump trick to avoid saving all of them,
10412   // however this code takes a simpler approach and just executes all
10413   // of the stores if %al is non-zero. It's less code, and it's probably
10414   // easier on the hardware branch predictor, and stores aren't all that
10415   // expensive anyway.
10416
10417   // Create the new basic blocks. One block contains all the XMM stores,
10418   // and one block is the final destination regardless of whether any
10419   // stores were performed.
10420   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10421   MachineFunction *F = MBB->getParent();
10422   MachineFunction::iterator MBBIter = MBB;
10423   ++MBBIter;
10424   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10425   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10426   F->insert(MBBIter, XMMSaveMBB);
10427   F->insert(MBBIter, EndMBB);
10428
10429   // Transfer the remainder of MBB and its successor edges to EndMBB.
10430   EndMBB->splice(EndMBB->begin(), MBB,
10431                  llvm::next(MachineBasicBlock::iterator(MI)),
10432                  MBB->end());
10433   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10434
10435   // The original block will now fall through to the XMM save block.
10436   MBB->addSuccessor(XMMSaveMBB);
10437   // The XMMSaveMBB will fall through to the end block.
10438   XMMSaveMBB->addSuccessor(EndMBB);
10439
10440   // Now add the instructions.
10441   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10442   DebugLoc DL = MI->getDebugLoc();
10443
10444   unsigned CountReg = MI->getOperand(0).getReg();
10445   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10446   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10447
10448   if (!Subtarget->isTargetWin64()) {
10449     // If %al is 0, branch around the XMM save block.
10450     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10451     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10452     MBB->addSuccessor(EndMBB);
10453   }
10454
10455   // In the XMM save block, save all the XMM argument registers.
10456   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10457     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10458     MachineMemOperand *MMO =
10459       F->getMachineMemOperand(
10460           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10461         MachineMemOperand::MOStore,
10462         /*Size=*/16, /*Align=*/16);
10463     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10464       .addFrameIndex(RegSaveFrameIndex)
10465       .addImm(/*Scale=*/1)
10466       .addReg(/*IndexReg=*/0)
10467       .addImm(/*Disp=*/Offset)
10468       .addReg(/*Segment=*/0)
10469       .addReg(MI->getOperand(i).getReg())
10470       .addMemOperand(MMO);
10471   }
10472
10473   MI->eraseFromParent();   // The pseudo instruction is gone now.
10474
10475   return EndMBB;
10476 }
10477
10478 MachineBasicBlock *
10479 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10480                                      MachineBasicBlock *BB) const {
10481   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10482   DebugLoc DL = MI->getDebugLoc();
10483
10484   // To "insert" a SELECT_CC instruction, we actually have to insert the
10485   // diamond control-flow pattern.  The incoming instruction knows the
10486   // destination vreg to set, the condition code register to branch on, the
10487   // true/false values to select between, and a branch opcode to use.
10488   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10489   MachineFunction::iterator It = BB;
10490   ++It;
10491
10492   //  thisMBB:
10493   //  ...
10494   //   TrueVal = ...
10495   //   cmpTY ccX, r1, r2
10496   //   bCC copy1MBB
10497   //   fallthrough --> copy0MBB
10498   MachineBasicBlock *thisMBB = BB;
10499   MachineFunction *F = BB->getParent();
10500   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10501   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10502   F->insert(It, copy0MBB);
10503   F->insert(It, sinkMBB);
10504
10505   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10506   // live into the sink and copy blocks.
10507   const MachineFunction *MF = BB->getParent();
10508   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10509   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10510
10511   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10512     const MachineOperand &MO = MI->getOperand(I);
10513     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10514     unsigned Reg = MO.getReg();
10515     if (Reg != X86::EFLAGS) continue;
10516     copy0MBB->addLiveIn(Reg);
10517     sinkMBB->addLiveIn(Reg);
10518   }
10519
10520   // Transfer the remainder of BB and its successor edges to sinkMBB.
10521   sinkMBB->splice(sinkMBB->begin(), BB,
10522                   llvm::next(MachineBasicBlock::iterator(MI)),
10523                   BB->end());
10524   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10525
10526   // Add the true and fallthrough blocks as its successors.
10527   BB->addSuccessor(copy0MBB);
10528   BB->addSuccessor(sinkMBB);
10529
10530   // Create the conditional branch instruction.
10531   unsigned Opc =
10532     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10533   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10534
10535   //  copy0MBB:
10536   //   %FalseValue = ...
10537   //   # fallthrough to sinkMBB
10538   copy0MBB->addSuccessor(sinkMBB);
10539
10540   //  sinkMBB:
10541   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10542   //  ...
10543   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10544           TII->get(X86::PHI), MI->getOperand(0).getReg())
10545     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10546     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10547
10548   MI->eraseFromParent();   // The pseudo instruction is gone now.
10549   return sinkMBB;
10550 }
10551
10552 MachineBasicBlock *
10553 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10554                                           MachineBasicBlock *BB) const {
10555   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10556   DebugLoc DL = MI->getDebugLoc();
10557
10558   assert(!Subtarget->isTargetEnvMacho());
10559
10560   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10561   // non-trivial part is impdef of ESP.
10562
10563   if (Subtarget->isTargetWin64()) {
10564     if (Subtarget->isTargetCygMing()) {
10565       // ___chkstk(Mingw64):
10566       // Clobbers R10, R11, RAX and EFLAGS.
10567       // Updates RSP.
10568       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10569         .addExternalSymbol("___chkstk")
10570         .addReg(X86::RAX, RegState::Implicit)
10571         .addReg(X86::RSP, RegState::Implicit)
10572         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10573         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10574         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10575     } else {
10576       // __chkstk(MSVCRT): does not update stack pointer.
10577       // Clobbers R10, R11 and EFLAGS.
10578       // FIXME: RAX(allocated size) might be reused and not killed.
10579       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10580         .addExternalSymbol("__chkstk")
10581         .addReg(X86::RAX, RegState::Implicit)
10582         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10583       // RAX has the offset to subtracted from RSP.
10584       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10585         .addReg(X86::RSP)
10586         .addReg(X86::RAX);
10587     }
10588   } else {
10589     const char *StackProbeSymbol =
10590       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10591
10592     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10593       .addExternalSymbol(StackProbeSymbol)
10594       .addReg(X86::EAX, RegState::Implicit)
10595       .addReg(X86::ESP, RegState::Implicit)
10596       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10597       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10598       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10599   }
10600
10601   MI->eraseFromParent();   // The pseudo instruction is gone now.
10602   return BB;
10603 }
10604
10605 MachineBasicBlock *
10606 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10607                                       MachineBasicBlock *BB) const {
10608   // This is pretty easy.  We're taking the value that we received from
10609   // our load from the relocation, sticking it in either RDI (x86-64)
10610   // or EAX and doing an indirect call.  The return value will then
10611   // be in the normal return register.
10612   const X86InstrInfo *TII
10613     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10614   DebugLoc DL = MI->getDebugLoc();
10615   MachineFunction *F = BB->getParent();
10616
10617   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10618   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10619
10620   if (Subtarget->is64Bit()) {
10621     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10622                                       TII->get(X86::MOV64rm), X86::RDI)
10623     .addReg(X86::RIP)
10624     .addImm(0).addReg(0)
10625     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10626                       MI->getOperand(3).getTargetFlags())
10627     .addReg(0);
10628     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10629     addDirectMem(MIB, X86::RDI);
10630   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10631     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10632                                       TII->get(X86::MOV32rm), X86::EAX)
10633     .addReg(0)
10634     .addImm(0).addReg(0)
10635     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10636                       MI->getOperand(3).getTargetFlags())
10637     .addReg(0);
10638     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10639     addDirectMem(MIB, X86::EAX);
10640   } else {
10641     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10642                                       TII->get(X86::MOV32rm), X86::EAX)
10643     .addReg(TII->getGlobalBaseReg(F))
10644     .addImm(0).addReg(0)
10645     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10646                       MI->getOperand(3).getTargetFlags())
10647     .addReg(0);
10648     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10649     addDirectMem(MIB, X86::EAX);
10650   }
10651
10652   MI->eraseFromParent(); // The pseudo instruction is gone now.
10653   return BB;
10654 }
10655
10656 MachineBasicBlock *
10657 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10658                                                MachineBasicBlock *BB) const {
10659   switch (MI->getOpcode()) {
10660   default: assert(false && "Unexpected instr type to insert");
10661   case X86::TAILJMPd64:
10662   case X86::TAILJMPr64:
10663   case X86::TAILJMPm64:
10664     assert(!"TAILJMP64 would not be touched here.");
10665   case X86::TCRETURNdi64:
10666   case X86::TCRETURNri64:
10667   case X86::TCRETURNmi64:
10668     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10669     // On AMD64, additional defs should be added before register allocation.
10670     if (!Subtarget->isTargetWin64()) {
10671       MI->addRegisterDefined(X86::RSI);
10672       MI->addRegisterDefined(X86::RDI);
10673       MI->addRegisterDefined(X86::XMM6);
10674       MI->addRegisterDefined(X86::XMM7);
10675       MI->addRegisterDefined(X86::XMM8);
10676       MI->addRegisterDefined(X86::XMM9);
10677       MI->addRegisterDefined(X86::XMM10);
10678       MI->addRegisterDefined(X86::XMM11);
10679       MI->addRegisterDefined(X86::XMM12);
10680       MI->addRegisterDefined(X86::XMM13);
10681       MI->addRegisterDefined(X86::XMM14);
10682       MI->addRegisterDefined(X86::XMM15);
10683     }
10684     return BB;
10685   case X86::WIN_ALLOCA:
10686     return EmitLoweredWinAlloca(MI, BB);
10687   case X86::TLSCall_32:
10688   case X86::TLSCall_64:
10689     return EmitLoweredTLSCall(MI, BB);
10690   case X86::CMOV_GR8:
10691   case X86::CMOV_FR32:
10692   case X86::CMOV_FR64:
10693   case X86::CMOV_V4F32:
10694   case X86::CMOV_V2F64:
10695   case X86::CMOV_V2I64:
10696   case X86::CMOV_GR16:
10697   case X86::CMOV_GR32:
10698   case X86::CMOV_RFP32:
10699   case X86::CMOV_RFP64:
10700   case X86::CMOV_RFP80:
10701     return EmitLoweredSelect(MI, BB);
10702
10703   case X86::FP32_TO_INT16_IN_MEM:
10704   case X86::FP32_TO_INT32_IN_MEM:
10705   case X86::FP32_TO_INT64_IN_MEM:
10706   case X86::FP64_TO_INT16_IN_MEM:
10707   case X86::FP64_TO_INT32_IN_MEM:
10708   case X86::FP64_TO_INT64_IN_MEM:
10709   case X86::FP80_TO_INT16_IN_MEM:
10710   case X86::FP80_TO_INT32_IN_MEM:
10711   case X86::FP80_TO_INT64_IN_MEM: {
10712     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10713     DebugLoc DL = MI->getDebugLoc();
10714
10715     // Change the floating point control register to use "round towards zero"
10716     // mode when truncating to an integer value.
10717     MachineFunction *F = BB->getParent();
10718     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10719     addFrameReference(BuildMI(*BB, MI, DL,
10720                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10721
10722     // Load the old value of the high byte of the control word...
10723     unsigned OldCW =
10724       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10725     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10726                       CWFrameIdx);
10727
10728     // Set the high part to be round to zero...
10729     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10730       .addImm(0xC7F);
10731
10732     // Reload the modified control word now...
10733     addFrameReference(BuildMI(*BB, MI, DL,
10734                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10735
10736     // Restore the memory image of control word to original value
10737     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10738       .addReg(OldCW);
10739
10740     // Get the X86 opcode to use.
10741     unsigned Opc;
10742     switch (MI->getOpcode()) {
10743     default: llvm_unreachable("illegal opcode!");
10744     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10745     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10746     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10747     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10748     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10749     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10750     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10751     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10752     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10753     }
10754
10755     X86AddressMode AM;
10756     MachineOperand &Op = MI->getOperand(0);
10757     if (Op.isReg()) {
10758       AM.BaseType = X86AddressMode::RegBase;
10759       AM.Base.Reg = Op.getReg();
10760     } else {
10761       AM.BaseType = X86AddressMode::FrameIndexBase;
10762       AM.Base.FrameIndex = Op.getIndex();
10763     }
10764     Op = MI->getOperand(1);
10765     if (Op.isImm())
10766       AM.Scale = Op.getImm();
10767     Op = MI->getOperand(2);
10768     if (Op.isImm())
10769       AM.IndexReg = Op.getImm();
10770     Op = MI->getOperand(3);
10771     if (Op.isGlobal()) {
10772       AM.GV = Op.getGlobal();
10773     } else {
10774       AM.Disp = Op.getImm();
10775     }
10776     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10777                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10778
10779     // Reload the original control word now.
10780     addFrameReference(BuildMI(*BB, MI, DL,
10781                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10782
10783     MI->eraseFromParent();   // The pseudo instruction is gone now.
10784     return BB;
10785   }
10786     // String/text processing lowering.
10787   case X86::PCMPISTRM128REG:
10788   case X86::VPCMPISTRM128REG:
10789     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10790   case X86::PCMPISTRM128MEM:
10791   case X86::VPCMPISTRM128MEM:
10792     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10793   case X86::PCMPESTRM128REG:
10794   case X86::VPCMPESTRM128REG:
10795     return EmitPCMP(MI, BB, 5, false /* in mem */);
10796   case X86::PCMPESTRM128MEM:
10797   case X86::VPCMPESTRM128MEM:
10798     return EmitPCMP(MI, BB, 5, true /* in mem */);
10799
10800     // Thread synchronization.
10801   case X86::MONITOR:
10802     return EmitMonitor(MI, BB);
10803   case X86::MWAIT:
10804     return EmitMwait(MI, BB);
10805
10806     // Atomic Lowering.
10807   case X86::ATOMAND32:
10808     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10809                                                X86::AND32ri, X86::MOV32rm,
10810                                                X86::LCMPXCHG32,
10811                                                X86::NOT32r, X86::EAX,
10812                                                X86::GR32RegisterClass);
10813   case X86::ATOMOR32:
10814     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10815                                                X86::OR32ri, X86::MOV32rm,
10816                                                X86::LCMPXCHG32,
10817                                                X86::NOT32r, X86::EAX,
10818                                                X86::GR32RegisterClass);
10819   case X86::ATOMXOR32:
10820     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10821                                                X86::XOR32ri, X86::MOV32rm,
10822                                                X86::LCMPXCHG32,
10823                                                X86::NOT32r, X86::EAX,
10824                                                X86::GR32RegisterClass);
10825   case X86::ATOMNAND32:
10826     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10827                                                X86::AND32ri, X86::MOV32rm,
10828                                                X86::LCMPXCHG32,
10829                                                X86::NOT32r, X86::EAX,
10830                                                X86::GR32RegisterClass, true);
10831   case X86::ATOMMIN32:
10832     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10833   case X86::ATOMMAX32:
10834     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10835   case X86::ATOMUMIN32:
10836     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10837   case X86::ATOMUMAX32:
10838     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10839
10840   case X86::ATOMAND16:
10841     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10842                                                X86::AND16ri, X86::MOV16rm,
10843                                                X86::LCMPXCHG16,
10844                                                X86::NOT16r, X86::AX,
10845                                                X86::GR16RegisterClass);
10846   case X86::ATOMOR16:
10847     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10848                                                X86::OR16ri, X86::MOV16rm,
10849                                                X86::LCMPXCHG16,
10850                                                X86::NOT16r, X86::AX,
10851                                                X86::GR16RegisterClass);
10852   case X86::ATOMXOR16:
10853     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10854                                                X86::XOR16ri, X86::MOV16rm,
10855                                                X86::LCMPXCHG16,
10856                                                X86::NOT16r, X86::AX,
10857                                                X86::GR16RegisterClass);
10858   case X86::ATOMNAND16:
10859     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10860                                                X86::AND16ri, X86::MOV16rm,
10861                                                X86::LCMPXCHG16,
10862                                                X86::NOT16r, X86::AX,
10863                                                X86::GR16RegisterClass, true);
10864   case X86::ATOMMIN16:
10865     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10866   case X86::ATOMMAX16:
10867     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10868   case X86::ATOMUMIN16:
10869     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10870   case X86::ATOMUMAX16:
10871     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10872
10873   case X86::ATOMAND8:
10874     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10875                                                X86::AND8ri, X86::MOV8rm,
10876                                                X86::LCMPXCHG8,
10877                                                X86::NOT8r, X86::AL,
10878                                                X86::GR8RegisterClass);
10879   case X86::ATOMOR8:
10880     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10881                                                X86::OR8ri, X86::MOV8rm,
10882                                                X86::LCMPXCHG8,
10883                                                X86::NOT8r, X86::AL,
10884                                                X86::GR8RegisterClass);
10885   case X86::ATOMXOR8:
10886     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10887                                                X86::XOR8ri, X86::MOV8rm,
10888                                                X86::LCMPXCHG8,
10889                                                X86::NOT8r, X86::AL,
10890                                                X86::GR8RegisterClass);
10891   case X86::ATOMNAND8:
10892     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10893                                                X86::AND8ri, X86::MOV8rm,
10894                                                X86::LCMPXCHG8,
10895                                                X86::NOT8r, X86::AL,
10896                                                X86::GR8RegisterClass, true);
10897   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10898   // This group is for 64-bit host.
10899   case X86::ATOMAND64:
10900     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10901                                                X86::AND64ri32, X86::MOV64rm,
10902                                                X86::LCMPXCHG64,
10903                                                X86::NOT64r, X86::RAX,
10904                                                X86::GR64RegisterClass);
10905   case X86::ATOMOR64:
10906     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10907                                                X86::OR64ri32, X86::MOV64rm,
10908                                                X86::LCMPXCHG64,
10909                                                X86::NOT64r, X86::RAX,
10910                                                X86::GR64RegisterClass);
10911   case X86::ATOMXOR64:
10912     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10913                                                X86::XOR64ri32, X86::MOV64rm,
10914                                                X86::LCMPXCHG64,
10915                                                X86::NOT64r, X86::RAX,
10916                                                X86::GR64RegisterClass);
10917   case X86::ATOMNAND64:
10918     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10919                                                X86::AND64ri32, X86::MOV64rm,
10920                                                X86::LCMPXCHG64,
10921                                                X86::NOT64r, X86::RAX,
10922                                                X86::GR64RegisterClass, true);
10923   case X86::ATOMMIN64:
10924     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10925   case X86::ATOMMAX64:
10926     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10927   case X86::ATOMUMIN64:
10928     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10929   case X86::ATOMUMAX64:
10930     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10931
10932   // This group does 64-bit operations on a 32-bit host.
10933   case X86::ATOMAND6432:
10934     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10935                                                X86::AND32rr, X86::AND32rr,
10936                                                X86::AND32ri, X86::AND32ri,
10937                                                false);
10938   case X86::ATOMOR6432:
10939     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10940                                                X86::OR32rr, X86::OR32rr,
10941                                                X86::OR32ri, X86::OR32ri,
10942                                                false);
10943   case X86::ATOMXOR6432:
10944     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10945                                                X86::XOR32rr, X86::XOR32rr,
10946                                                X86::XOR32ri, X86::XOR32ri,
10947                                                false);
10948   case X86::ATOMNAND6432:
10949     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10950                                                X86::AND32rr, X86::AND32rr,
10951                                                X86::AND32ri, X86::AND32ri,
10952                                                true);
10953   case X86::ATOMADD6432:
10954     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10955                                                X86::ADD32rr, X86::ADC32rr,
10956                                                X86::ADD32ri, X86::ADC32ri,
10957                                                false);
10958   case X86::ATOMSUB6432:
10959     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10960                                                X86::SUB32rr, X86::SBB32rr,
10961                                                X86::SUB32ri, X86::SBB32ri,
10962                                                false);
10963   case X86::ATOMSWAP6432:
10964     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10965                                                X86::MOV32rr, X86::MOV32rr,
10966                                                X86::MOV32ri, X86::MOV32ri,
10967                                                false);
10968   case X86::VASTART_SAVE_XMM_REGS:
10969     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10970
10971   case X86::VAARG_64:
10972     return EmitVAARG64WithCustomInserter(MI, BB);
10973   }
10974 }
10975
10976 //===----------------------------------------------------------------------===//
10977 //                           X86 Optimization Hooks
10978 //===----------------------------------------------------------------------===//
10979
10980 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10981                                                        const APInt &Mask,
10982                                                        APInt &KnownZero,
10983                                                        APInt &KnownOne,
10984                                                        const SelectionDAG &DAG,
10985                                                        unsigned Depth) const {
10986   unsigned Opc = Op.getOpcode();
10987   assert((Opc >= ISD::BUILTIN_OP_END ||
10988           Opc == ISD::INTRINSIC_WO_CHAIN ||
10989           Opc == ISD::INTRINSIC_W_CHAIN ||
10990           Opc == ISD::INTRINSIC_VOID) &&
10991          "Should use MaskedValueIsZero if you don't know whether Op"
10992          " is a target node!");
10993
10994   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10995   switch (Opc) {
10996   default: break;
10997   case X86ISD::ADD:
10998   case X86ISD::SUB:
10999   case X86ISD::ADC:
11000   case X86ISD::SBB:
11001   case X86ISD::SMUL:
11002   case X86ISD::UMUL:
11003   case X86ISD::INC:
11004   case X86ISD::DEC:
11005   case X86ISD::OR:
11006   case X86ISD::XOR:
11007   case X86ISD::AND:
11008     // These nodes' second result is a boolean.
11009     if (Op.getResNo() == 0)
11010       break;
11011     // Fallthrough
11012   case X86ISD::SETCC:
11013     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11014                                        Mask.getBitWidth() - 1);
11015     break;
11016   }
11017 }
11018
11019 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11020                                                          unsigned Depth) const {
11021   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11022   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11023     return Op.getValueType().getScalarType().getSizeInBits();
11024
11025   // Fallback case.
11026   return 1;
11027 }
11028
11029 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11030 /// node is a GlobalAddress + offset.
11031 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11032                                        const GlobalValue* &GA,
11033                                        int64_t &Offset) const {
11034   if (N->getOpcode() == X86ISD::Wrapper) {
11035     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11036       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11037       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11038       return true;
11039     }
11040   }
11041   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11042 }
11043
11044 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11045 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11046 /// if the load addresses are consecutive, non-overlapping, and in the right
11047 /// order.
11048 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11049                                      TargetLowering::DAGCombinerInfo &DCI) {
11050   DebugLoc dl = N->getDebugLoc();
11051   EVT VT = N->getValueType(0);
11052
11053   if (VT.getSizeInBits() != 128)
11054     return SDValue();
11055
11056   // Don't create instructions with illegal types after legalize types has run.
11057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11058   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11059     return SDValue();
11060
11061   SmallVector<SDValue, 16> Elts;
11062   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11063     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11064
11065   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11066 }
11067
11068 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11069 /// generation and convert it from being a bunch of shuffles and extracts
11070 /// to a simple store and scalar loads to extract the elements.
11071 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11072                                                 const TargetLowering &TLI) {
11073   SDValue InputVector = N->getOperand(0);
11074
11075   // Only operate on vectors of 4 elements, where the alternative shuffling
11076   // gets to be more expensive.
11077   if (InputVector.getValueType() != MVT::v4i32)
11078     return SDValue();
11079
11080   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11081   // single use which is a sign-extend or zero-extend, and all elements are
11082   // used.
11083   SmallVector<SDNode *, 4> Uses;
11084   unsigned ExtractedElements = 0;
11085   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11086        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11087     if (UI.getUse().getResNo() != InputVector.getResNo())
11088       return SDValue();
11089
11090     SDNode *Extract = *UI;
11091     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11092       return SDValue();
11093
11094     if (Extract->getValueType(0) != MVT::i32)
11095       return SDValue();
11096     if (!Extract->hasOneUse())
11097       return SDValue();
11098     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11099         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11100       return SDValue();
11101     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11102       return SDValue();
11103
11104     // Record which element was extracted.
11105     ExtractedElements |=
11106       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11107
11108     Uses.push_back(Extract);
11109   }
11110
11111   // If not all the elements were used, this may not be worthwhile.
11112   if (ExtractedElements != 15)
11113     return SDValue();
11114
11115   // Ok, we've now decided to do the transformation.
11116   DebugLoc dl = InputVector.getDebugLoc();
11117
11118   // Store the value to a temporary stack slot.
11119   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11120   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11121                             MachinePointerInfo(), false, false, 0);
11122
11123   // Replace each use (extract) with a load of the appropriate element.
11124   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11125        UE = Uses.end(); UI != UE; ++UI) {
11126     SDNode *Extract = *UI;
11127
11128     // cOMpute the element's address.
11129     SDValue Idx = Extract->getOperand(1);
11130     unsigned EltSize =
11131         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11132     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11133     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11134
11135     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11136                                      StackPtr, OffsetVal);
11137
11138     // Load the scalar.
11139     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11140                                      ScalarAddr, MachinePointerInfo(),
11141                                      false, false, 0);
11142
11143     // Replace the exact with the load.
11144     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11145   }
11146
11147   // The replacement was made in place; don't return anything.
11148   return SDValue();
11149 }
11150
11151 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11152 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11153                                     const X86Subtarget *Subtarget) {
11154   DebugLoc DL = N->getDebugLoc();
11155   SDValue Cond = N->getOperand(0);
11156   // Get the LHS/RHS of the select.
11157   SDValue LHS = N->getOperand(1);
11158   SDValue RHS = N->getOperand(2);
11159
11160   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11161   // instructions match the semantics of the common C idiom x<y?x:y but not
11162   // x<=y?x:y, because of how they handle negative zero (which can be
11163   // ignored in unsafe-math mode).
11164   if (Subtarget->hasSSE2() &&
11165       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11166       Cond.getOpcode() == ISD::SETCC) {
11167     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11168
11169     unsigned Opcode = 0;
11170     // Check for x CC y ? x : y.
11171     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11172         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11173       switch (CC) {
11174       default: break;
11175       case ISD::SETULT:
11176         // Converting this to a min would handle NaNs incorrectly, and swapping
11177         // the operands would cause it to handle comparisons between positive
11178         // and negative zero incorrectly.
11179         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11180           if (!UnsafeFPMath &&
11181               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11182             break;
11183           std::swap(LHS, RHS);
11184         }
11185         Opcode = X86ISD::FMIN;
11186         break;
11187       case ISD::SETOLE:
11188         // Converting this to a min would handle comparisons between positive
11189         // and negative zero incorrectly.
11190         if (!UnsafeFPMath &&
11191             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11192           break;
11193         Opcode = X86ISD::FMIN;
11194         break;
11195       case ISD::SETULE:
11196         // Converting this to a min would handle both negative zeros and NaNs
11197         // incorrectly, but we can swap the operands to fix both.
11198         std::swap(LHS, RHS);
11199       case ISD::SETOLT:
11200       case ISD::SETLT:
11201       case ISD::SETLE:
11202         Opcode = X86ISD::FMIN;
11203         break;
11204
11205       case ISD::SETOGE:
11206         // Converting this to a max would handle comparisons between positive
11207         // and negative zero incorrectly.
11208         if (!UnsafeFPMath &&
11209             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11210           break;
11211         Opcode = X86ISD::FMAX;
11212         break;
11213       case ISD::SETUGT:
11214         // Converting this to a max would handle NaNs incorrectly, and swapping
11215         // the operands would cause it to handle comparisons between positive
11216         // and negative zero incorrectly.
11217         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11218           if (!UnsafeFPMath &&
11219               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11220             break;
11221           std::swap(LHS, RHS);
11222         }
11223         Opcode = X86ISD::FMAX;
11224         break;
11225       case ISD::SETUGE:
11226         // Converting this to a max would handle both negative zeros and NaNs
11227         // incorrectly, but we can swap the operands to fix both.
11228         std::swap(LHS, RHS);
11229       case ISD::SETOGT:
11230       case ISD::SETGT:
11231       case ISD::SETGE:
11232         Opcode = X86ISD::FMAX;
11233         break;
11234       }
11235     // Check for x CC y ? y : x -- a min/max with reversed arms.
11236     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11237                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11238       switch (CC) {
11239       default: break;
11240       case ISD::SETOGE:
11241         // Converting this to a min would handle comparisons between positive
11242         // and negative zero incorrectly, and swapping the operands would
11243         // cause it to handle NaNs incorrectly.
11244         if (!UnsafeFPMath &&
11245             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11246           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11247             break;
11248           std::swap(LHS, RHS);
11249         }
11250         Opcode = X86ISD::FMIN;
11251         break;
11252       case ISD::SETUGT:
11253         // Converting this to a min would handle NaNs incorrectly.
11254         if (!UnsafeFPMath &&
11255             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11256           break;
11257         Opcode = X86ISD::FMIN;
11258         break;
11259       case ISD::SETUGE:
11260         // Converting this to a min would handle both negative zeros and NaNs
11261         // incorrectly, but we can swap the operands to fix both.
11262         std::swap(LHS, RHS);
11263       case ISD::SETOGT:
11264       case ISD::SETGT:
11265       case ISD::SETGE:
11266         Opcode = X86ISD::FMIN;
11267         break;
11268
11269       case ISD::SETULT:
11270         // Converting this to a max would handle NaNs incorrectly.
11271         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11272           break;
11273         Opcode = X86ISD::FMAX;
11274         break;
11275       case ISD::SETOLE:
11276         // Converting this to a max would handle comparisons between positive
11277         // and negative zero incorrectly, and swapping the operands would
11278         // cause it to handle NaNs incorrectly.
11279         if (!UnsafeFPMath &&
11280             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11281           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11282             break;
11283           std::swap(LHS, RHS);
11284         }
11285         Opcode = X86ISD::FMAX;
11286         break;
11287       case ISD::SETULE:
11288         // Converting this to a max would handle both negative zeros and NaNs
11289         // incorrectly, but we can swap the operands to fix both.
11290         std::swap(LHS, RHS);
11291       case ISD::SETOLT:
11292       case ISD::SETLT:
11293       case ISD::SETLE:
11294         Opcode = X86ISD::FMAX;
11295         break;
11296       }
11297     }
11298
11299     if (Opcode)
11300       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11301   }
11302
11303   // If this is a select between two integer constants, try to do some
11304   // optimizations.
11305   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11306     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11307       // Don't do this for crazy integer types.
11308       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11309         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11310         // so that TrueC (the true value) is larger than FalseC.
11311         bool NeedsCondInvert = false;
11312
11313         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11314             // Efficiently invertible.
11315             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11316              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11317               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11318           NeedsCondInvert = true;
11319           std::swap(TrueC, FalseC);
11320         }
11321
11322         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11323         if (FalseC->getAPIntValue() == 0 &&
11324             TrueC->getAPIntValue().isPowerOf2()) {
11325           if (NeedsCondInvert) // Invert the condition if needed.
11326             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11327                                DAG.getConstant(1, Cond.getValueType()));
11328
11329           // Zero extend the condition if needed.
11330           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11331
11332           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11333           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11334                              DAG.getConstant(ShAmt, MVT::i8));
11335         }
11336
11337         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11338         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11339           if (NeedsCondInvert) // Invert the condition if needed.
11340             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11341                                DAG.getConstant(1, Cond.getValueType()));
11342
11343           // Zero extend the condition if needed.
11344           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11345                              FalseC->getValueType(0), Cond);
11346           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11347                              SDValue(FalseC, 0));
11348         }
11349
11350         // Optimize cases that will turn into an LEA instruction.  This requires
11351         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11352         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11353           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11354           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11355
11356           bool isFastMultiplier = false;
11357           if (Diff < 10) {
11358             switch ((unsigned char)Diff) {
11359               default: break;
11360               case 1:  // result = add base, cond
11361               case 2:  // result = lea base(    , cond*2)
11362               case 3:  // result = lea base(cond, cond*2)
11363               case 4:  // result = lea base(    , cond*4)
11364               case 5:  // result = lea base(cond, cond*4)
11365               case 8:  // result = lea base(    , cond*8)
11366               case 9:  // result = lea base(cond, cond*8)
11367                 isFastMultiplier = true;
11368                 break;
11369             }
11370           }
11371
11372           if (isFastMultiplier) {
11373             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11374             if (NeedsCondInvert) // Invert the condition if needed.
11375               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11376                                  DAG.getConstant(1, Cond.getValueType()));
11377
11378             // Zero extend the condition if needed.
11379             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11380                                Cond);
11381             // Scale the condition by the difference.
11382             if (Diff != 1)
11383               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11384                                  DAG.getConstant(Diff, Cond.getValueType()));
11385
11386             // Add the base if non-zero.
11387             if (FalseC->getAPIntValue() != 0)
11388               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11389                                  SDValue(FalseC, 0));
11390             return Cond;
11391           }
11392         }
11393       }
11394   }
11395
11396   return SDValue();
11397 }
11398
11399 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11400 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11401                                   TargetLowering::DAGCombinerInfo &DCI) {
11402   DebugLoc DL = N->getDebugLoc();
11403
11404   // If the flag operand isn't dead, don't touch this CMOV.
11405   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11406     return SDValue();
11407
11408   SDValue FalseOp = N->getOperand(0);
11409   SDValue TrueOp = N->getOperand(1);
11410   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11411   SDValue Cond = N->getOperand(3);
11412   if (CC == X86::COND_E || CC == X86::COND_NE) {
11413     switch (Cond.getOpcode()) {
11414     default: break;
11415     case X86ISD::BSR:
11416     case X86ISD::BSF:
11417       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11418       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11419         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11420     }
11421   }
11422
11423   // If this is a select between two integer constants, try to do some
11424   // optimizations.  Note that the operands are ordered the opposite of SELECT
11425   // operands.
11426   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11427     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11428       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11429       // larger than FalseC (the false value).
11430       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11431         CC = X86::GetOppositeBranchCondition(CC);
11432         std::swap(TrueC, FalseC);
11433       }
11434
11435       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11436       // This is efficient for any integer data type (including i8/i16) and
11437       // shift amount.
11438       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11439         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11440                            DAG.getConstant(CC, MVT::i8), Cond);
11441
11442         // Zero extend the condition if needed.
11443         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11444
11445         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11446         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11447                            DAG.getConstant(ShAmt, MVT::i8));
11448         if (N->getNumValues() == 2)  // Dead flag value?
11449           return DCI.CombineTo(N, Cond, SDValue());
11450         return Cond;
11451       }
11452
11453       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11454       // for any integer data type, including i8/i16.
11455       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11456         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11457                            DAG.getConstant(CC, MVT::i8), Cond);
11458
11459         // Zero extend the condition if needed.
11460         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11461                            FalseC->getValueType(0), Cond);
11462         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11463                            SDValue(FalseC, 0));
11464
11465         if (N->getNumValues() == 2)  // Dead flag value?
11466           return DCI.CombineTo(N, Cond, SDValue());
11467         return Cond;
11468       }
11469
11470       // Optimize cases that will turn into an LEA instruction.  This requires
11471       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11472       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11473         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11474         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11475
11476         bool isFastMultiplier = false;
11477         if (Diff < 10) {
11478           switch ((unsigned char)Diff) {
11479           default: break;
11480           case 1:  // result = add base, cond
11481           case 2:  // result = lea base(    , cond*2)
11482           case 3:  // result = lea base(cond, cond*2)
11483           case 4:  // result = lea base(    , cond*4)
11484           case 5:  // result = lea base(cond, cond*4)
11485           case 8:  // result = lea base(    , cond*8)
11486           case 9:  // result = lea base(cond, cond*8)
11487             isFastMultiplier = true;
11488             break;
11489           }
11490         }
11491
11492         if (isFastMultiplier) {
11493           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11494           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11495                              DAG.getConstant(CC, MVT::i8), Cond);
11496           // Zero extend the condition if needed.
11497           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11498                              Cond);
11499           // Scale the condition by the difference.
11500           if (Diff != 1)
11501             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11502                                DAG.getConstant(Diff, Cond.getValueType()));
11503
11504           // Add the base if non-zero.
11505           if (FalseC->getAPIntValue() != 0)
11506             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11507                                SDValue(FalseC, 0));
11508           if (N->getNumValues() == 2)  // Dead flag value?
11509             return DCI.CombineTo(N, Cond, SDValue());
11510           return Cond;
11511         }
11512       }
11513     }
11514   }
11515   return SDValue();
11516 }
11517
11518
11519 /// PerformMulCombine - Optimize a single multiply with constant into two
11520 /// in order to implement it with two cheaper instructions, e.g.
11521 /// LEA + SHL, LEA + LEA.
11522 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11523                                  TargetLowering::DAGCombinerInfo &DCI) {
11524   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11525     return SDValue();
11526
11527   EVT VT = N->getValueType(0);
11528   if (VT != MVT::i64)
11529     return SDValue();
11530
11531   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11532   if (!C)
11533     return SDValue();
11534   uint64_t MulAmt = C->getZExtValue();
11535   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11536     return SDValue();
11537
11538   uint64_t MulAmt1 = 0;
11539   uint64_t MulAmt2 = 0;
11540   if ((MulAmt % 9) == 0) {
11541     MulAmt1 = 9;
11542     MulAmt2 = MulAmt / 9;
11543   } else if ((MulAmt % 5) == 0) {
11544     MulAmt1 = 5;
11545     MulAmt2 = MulAmt / 5;
11546   } else if ((MulAmt % 3) == 0) {
11547     MulAmt1 = 3;
11548     MulAmt2 = MulAmt / 3;
11549   }
11550   if (MulAmt2 &&
11551       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11552     DebugLoc DL = N->getDebugLoc();
11553
11554     if (isPowerOf2_64(MulAmt2) &&
11555         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11556       // If second multiplifer is pow2, issue it first. We want the multiply by
11557       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11558       // is an add.
11559       std::swap(MulAmt1, MulAmt2);
11560
11561     SDValue NewMul;
11562     if (isPowerOf2_64(MulAmt1))
11563       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11564                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11565     else
11566       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11567                            DAG.getConstant(MulAmt1, VT));
11568
11569     if (isPowerOf2_64(MulAmt2))
11570       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11571                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11572     else
11573       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11574                            DAG.getConstant(MulAmt2, VT));
11575
11576     // Do not add new nodes to DAG combiner worklist.
11577     DCI.CombineTo(N, NewMul, false);
11578   }
11579   return SDValue();
11580 }
11581
11582 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11583   SDValue N0 = N->getOperand(0);
11584   SDValue N1 = N->getOperand(1);
11585   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11586   EVT VT = N0.getValueType();
11587
11588   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11589   // since the result of setcc_c is all zero's or all ones.
11590   if (N1C && N0.getOpcode() == ISD::AND &&
11591       N0.getOperand(1).getOpcode() == ISD::Constant) {
11592     SDValue N00 = N0.getOperand(0);
11593     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11594         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11595           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11596          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11597       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11598       APInt ShAmt = N1C->getAPIntValue();
11599       Mask = Mask.shl(ShAmt);
11600       if (Mask != 0)
11601         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11602                            N00, DAG.getConstant(Mask, VT));
11603     }
11604   }
11605
11606   return SDValue();
11607 }
11608
11609 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11610 ///                       when possible.
11611 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11612                                    const X86Subtarget *Subtarget) {
11613   EVT VT = N->getValueType(0);
11614   if (!VT.isVector() && VT.isInteger() &&
11615       N->getOpcode() == ISD::SHL)
11616     return PerformSHLCombine(N, DAG);
11617
11618   // On X86 with SSE2 support, we can transform this to a vector shift if
11619   // all elements are shifted by the same amount.  We can't do this in legalize
11620   // because the a constant vector is typically transformed to a constant pool
11621   // so we have no knowledge of the shift amount.
11622   if (!Subtarget->hasSSE2())
11623     return SDValue();
11624
11625   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11626     return SDValue();
11627
11628   SDValue ShAmtOp = N->getOperand(1);
11629   EVT EltVT = VT.getVectorElementType();
11630   DebugLoc DL = N->getDebugLoc();
11631   SDValue BaseShAmt = SDValue();
11632   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11633     unsigned NumElts = VT.getVectorNumElements();
11634     unsigned i = 0;
11635     for (; i != NumElts; ++i) {
11636       SDValue Arg = ShAmtOp.getOperand(i);
11637       if (Arg.getOpcode() == ISD::UNDEF) continue;
11638       BaseShAmt = Arg;
11639       break;
11640     }
11641     for (; i != NumElts; ++i) {
11642       SDValue Arg = ShAmtOp.getOperand(i);
11643       if (Arg.getOpcode() == ISD::UNDEF) continue;
11644       if (Arg != BaseShAmt) {
11645         return SDValue();
11646       }
11647     }
11648   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11649              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11650     SDValue InVec = ShAmtOp.getOperand(0);
11651     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11652       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11653       unsigned i = 0;
11654       for (; i != NumElts; ++i) {
11655         SDValue Arg = InVec.getOperand(i);
11656         if (Arg.getOpcode() == ISD::UNDEF) continue;
11657         BaseShAmt = Arg;
11658         break;
11659       }
11660     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11661        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11662          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11663          if (C->getZExtValue() == SplatIdx)
11664            BaseShAmt = InVec.getOperand(1);
11665        }
11666     }
11667     if (BaseShAmt.getNode() == 0)
11668       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11669                               DAG.getIntPtrConstant(0));
11670   } else
11671     return SDValue();
11672
11673   // The shift amount is an i32.
11674   if (EltVT.bitsGT(MVT::i32))
11675     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11676   else if (EltVT.bitsLT(MVT::i32))
11677     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11678
11679   // The shift amount is identical so we can do a vector shift.
11680   SDValue  ValOp = N->getOperand(0);
11681   switch (N->getOpcode()) {
11682   default:
11683     llvm_unreachable("Unknown shift opcode!");
11684     break;
11685   case ISD::SHL:
11686     if (VT == MVT::v2i64)
11687       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11688                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11689                          ValOp, BaseShAmt);
11690     if (VT == MVT::v4i32)
11691       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11692                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11693                          ValOp, BaseShAmt);
11694     if (VT == MVT::v8i16)
11695       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11696                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11697                          ValOp, BaseShAmt);
11698     break;
11699   case ISD::SRA:
11700     if (VT == MVT::v4i32)
11701       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11702                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11703                          ValOp, BaseShAmt);
11704     if (VT == MVT::v8i16)
11705       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11706                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11707                          ValOp, BaseShAmt);
11708     break;
11709   case ISD::SRL:
11710     if (VT == MVT::v2i64)
11711       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11712                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11713                          ValOp, BaseShAmt);
11714     if (VT == MVT::v4i32)
11715       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11716                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11717                          ValOp, BaseShAmt);
11718     if (VT ==  MVT::v8i16)
11719       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11720                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11721                          ValOp, BaseShAmt);
11722     break;
11723   }
11724   return SDValue();
11725 }
11726
11727
11728 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11729 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11730 // and friends.  Likewise for OR -> CMPNEQSS.
11731 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11732                             TargetLowering::DAGCombinerInfo &DCI,
11733                             const X86Subtarget *Subtarget) {
11734   unsigned opcode;
11735
11736   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11737   // we're requiring SSE2 for both.
11738   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11739     SDValue N0 = N->getOperand(0);
11740     SDValue N1 = N->getOperand(1);
11741     SDValue CMP0 = N0->getOperand(1);
11742     SDValue CMP1 = N1->getOperand(1);
11743     DebugLoc DL = N->getDebugLoc();
11744
11745     // The SETCCs should both refer to the same CMP.
11746     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11747       return SDValue();
11748
11749     SDValue CMP00 = CMP0->getOperand(0);
11750     SDValue CMP01 = CMP0->getOperand(1);
11751     EVT     VT    = CMP00.getValueType();
11752
11753     if (VT == MVT::f32 || VT == MVT::f64) {
11754       bool ExpectingFlags = false;
11755       // Check for any users that want flags:
11756       for (SDNode::use_iterator UI = N->use_begin(),
11757              UE = N->use_end();
11758            !ExpectingFlags && UI != UE; ++UI)
11759         switch (UI->getOpcode()) {
11760         default:
11761         case ISD::BR_CC:
11762         case ISD::BRCOND:
11763         case ISD::SELECT:
11764           ExpectingFlags = true;
11765           break;
11766         case ISD::CopyToReg:
11767         case ISD::SIGN_EXTEND:
11768         case ISD::ZERO_EXTEND:
11769         case ISD::ANY_EXTEND:
11770           break;
11771         }
11772
11773       if (!ExpectingFlags) {
11774         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11775         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11776
11777         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11778           X86::CondCode tmp = cc0;
11779           cc0 = cc1;
11780           cc1 = tmp;
11781         }
11782
11783         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11784             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11785           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11786           X86ISD::NodeType NTOperator = is64BitFP ?
11787             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11788           // FIXME: need symbolic constants for these magic numbers.
11789           // See X86ATTInstPrinter.cpp:printSSECC().
11790           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11791           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11792                                               DAG.getConstant(x86cc, MVT::i8));
11793           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11794                                               OnesOrZeroesF);
11795           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11796                                       DAG.getConstant(1, MVT::i32));
11797           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11798           return OneBitOfTruth;
11799         }
11800       }
11801     }
11802   }
11803   return SDValue();
11804 }
11805
11806 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11807                                  TargetLowering::DAGCombinerInfo &DCI,
11808                                  const X86Subtarget *Subtarget) {
11809   if (DCI.isBeforeLegalizeOps())
11810     return SDValue();
11811
11812   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11813   if (R.getNode())
11814     return R;
11815
11816   // Want to form PANDN nodes, in the hopes of then easily combining them with
11817   // OR and AND nodes to form PBLEND/PSIGN.
11818   EVT VT = N->getValueType(0);
11819   if (VT != MVT::v2i64)
11820     return SDValue();
11821
11822   SDValue N0 = N->getOperand(0);
11823   SDValue N1 = N->getOperand(1);
11824   DebugLoc DL = N->getDebugLoc();
11825
11826   // Check LHS for vnot
11827   if (N0.getOpcode() == ISD::XOR &&
11828       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11829     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11830
11831   // Check RHS for vnot
11832   if (N1.getOpcode() == ISD::XOR &&
11833       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11834     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11835
11836   return SDValue();
11837 }
11838
11839 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11840                                 TargetLowering::DAGCombinerInfo &DCI,
11841                                 const X86Subtarget *Subtarget) {
11842   if (DCI.isBeforeLegalizeOps())
11843     return SDValue();
11844
11845   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11846   if (R.getNode())
11847     return R;
11848
11849   EVT VT = N->getValueType(0);
11850   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11851     return SDValue();
11852
11853   SDValue N0 = N->getOperand(0);
11854   SDValue N1 = N->getOperand(1);
11855
11856   // look for psign/blend
11857   if (Subtarget->hasSSSE3()) {
11858     if (VT == MVT::v2i64) {
11859       // Canonicalize pandn to RHS
11860       if (N0.getOpcode() == X86ISD::PANDN)
11861         std::swap(N0, N1);
11862       // or (and (m, x), (pandn m, y))
11863       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11864         SDValue Mask = N1.getOperand(0);
11865         SDValue X    = N1.getOperand(1);
11866         SDValue Y;
11867         if (N0.getOperand(0) == Mask)
11868           Y = N0.getOperand(1);
11869         if (N0.getOperand(1) == Mask)
11870           Y = N0.getOperand(0);
11871
11872         // Check to see if the mask appeared in both the AND and PANDN and
11873         if (!Y.getNode())
11874           return SDValue();
11875
11876         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11877         if (Mask.getOpcode() != ISD::BITCAST ||
11878             X.getOpcode() != ISD::BITCAST ||
11879             Y.getOpcode() != ISD::BITCAST)
11880           return SDValue();
11881
11882         // Look through mask bitcast.
11883         Mask = Mask.getOperand(0);
11884         EVT MaskVT = Mask.getValueType();
11885
11886         // Validate that the Mask operand is a vector sra node.  The sra node
11887         // will be an intrinsic.
11888         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11889           return SDValue();
11890
11891         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11892         // there is no psrai.b
11893         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11894         case Intrinsic::x86_sse2_psrai_w:
11895         case Intrinsic::x86_sse2_psrai_d:
11896           break;
11897         default: return SDValue();
11898         }
11899
11900         // Check that the SRA is all signbits.
11901         SDValue SraC = Mask.getOperand(2);
11902         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11903         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11904         if ((SraAmt + 1) != EltBits)
11905           return SDValue();
11906
11907         DebugLoc DL = N->getDebugLoc();
11908
11909         // Now we know we at least have a plendvb with the mask val.  See if
11910         // we can form a psignb/w/d.
11911         // psign = x.type == y.type == mask.type && y = sub(0, x);
11912         X = X.getOperand(0);
11913         Y = Y.getOperand(0);
11914         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11915             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11916             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11917           unsigned Opc = 0;
11918           switch (EltBits) {
11919           case 8: Opc = X86ISD::PSIGNB; break;
11920           case 16: Opc = X86ISD::PSIGNW; break;
11921           case 32: Opc = X86ISD::PSIGND; break;
11922           default: break;
11923           }
11924           if (Opc) {
11925             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11926             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11927           }
11928         }
11929         // PBLENDVB only available on SSE 4.1
11930         if (!Subtarget->hasSSE41())
11931           return SDValue();
11932
11933         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11934         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11935         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11936         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11937         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11938       }
11939     }
11940   }
11941
11942   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11943   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11944     std::swap(N0, N1);
11945   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11946     return SDValue();
11947   if (!N0.hasOneUse() || !N1.hasOneUse())
11948     return SDValue();
11949
11950   SDValue ShAmt0 = N0.getOperand(1);
11951   if (ShAmt0.getValueType() != MVT::i8)
11952     return SDValue();
11953   SDValue ShAmt1 = N1.getOperand(1);
11954   if (ShAmt1.getValueType() != MVT::i8)
11955     return SDValue();
11956   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11957     ShAmt0 = ShAmt0.getOperand(0);
11958   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11959     ShAmt1 = ShAmt1.getOperand(0);
11960
11961   DebugLoc DL = N->getDebugLoc();
11962   unsigned Opc = X86ISD::SHLD;
11963   SDValue Op0 = N0.getOperand(0);
11964   SDValue Op1 = N1.getOperand(0);
11965   if (ShAmt0.getOpcode() == ISD::SUB) {
11966     Opc = X86ISD::SHRD;
11967     std::swap(Op0, Op1);
11968     std::swap(ShAmt0, ShAmt1);
11969   }
11970
11971   unsigned Bits = VT.getSizeInBits();
11972   if (ShAmt1.getOpcode() == ISD::SUB) {
11973     SDValue Sum = ShAmt1.getOperand(0);
11974     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11975       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11976       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11977         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11978       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11979         return DAG.getNode(Opc, DL, VT,
11980                            Op0, Op1,
11981                            DAG.getNode(ISD::TRUNCATE, DL,
11982                                        MVT::i8, ShAmt0));
11983     }
11984   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11985     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11986     if (ShAmt0C &&
11987         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11988       return DAG.getNode(Opc, DL, VT,
11989                          N0.getOperand(0), N1.getOperand(0),
11990                          DAG.getNode(ISD::TRUNCATE, DL,
11991                                        MVT::i8, ShAmt0));
11992   }
11993
11994   return SDValue();
11995 }
11996
11997 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11998 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11999                                    const X86Subtarget *Subtarget) {
12000   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12001   // the FP state in cases where an emms may be missing.
12002   // A preferable solution to the general problem is to figure out the right
12003   // places to insert EMMS.  This qualifies as a quick hack.
12004
12005   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12006   StoreSDNode *St = cast<StoreSDNode>(N);
12007   EVT VT = St->getValue().getValueType();
12008   if (VT.getSizeInBits() != 64)
12009     return SDValue();
12010
12011   const Function *F = DAG.getMachineFunction().getFunction();
12012   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12013   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12014     && Subtarget->hasSSE2();
12015   if ((VT.isVector() ||
12016        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12017       isa<LoadSDNode>(St->getValue()) &&
12018       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12019       St->getChain().hasOneUse() && !St->isVolatile()) {
12020     SDNode* LdVal = St->getValue().getNode();
12021     LoadSDNode *Ld = 0;
12022     int TokenFactorIndex = -1;
12023     SmallVector<SDValue, 8> Ops;
12024     SDNode* ChainVal = St->getChain().getNode();
12025     // Must be a store of a load.  We currently handle two cases:  the load
12026     // is a direct child, and it's under an intervening TokenFactor.  It is
12027     // possible to dig deeper under nested TokenFactors.
12028     if (ChainVal == LdVal)
12029       Ld = cast<LoadSDNode>(St->getChain());
12030     else if (St->getValue().hasOneUse() &&
12031              ChainVal->getOpcode() == ISD::TokenFactor) {
12032       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12033         if (ChainVal->getOperand(i).getNode() == LdVal) {
12034           TokenFactorIndex = i;
12035           Ld = cast<LoadSDNode>(St->getValue());
12036         } else
12037           Ops.push_back(ChainVal->getOperand(i));
12038       }
12039     }
12040
12041     if (!Ld || !ISD::isNormalLoad(Ld))
12042       return SDValue();
12043
12044     // If this is not the MMX case, i.e. we are just turning i64 load/store
12045     // into f64 load/store, avoid the transformation if there are multiple
12046     // uses of the loaded value.
12047     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12048       return SDValue();
12049
12050     DebugLoc LdDL = Ld->getDebugLoc();
12051     DebugLoc StDL = N->getDebugLoc();
12052     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12053     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12054     // pair instead.
12055     if (Subtarget->is64Bit() || F64IsLegal) {
12056       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12057       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12058                                   Ld->getPointerInfo(), Ld->isVolatile(),
12059                                   Ld->isNonTemporal(), Ld->getAlignment());
12060       SDValue NewChain = NewLd.getValue(1);
12061       if (TokenFactorIndex != -1) {
12062         Ops.push_back(NewChain);
12063         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12064                                Ops.size());
12065       }
12066       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12067                           St->getPointerInfo(),
12068                           St->isVolatile(), St->isNonTemporal(),
12069                           St->getAlignment());
12070     }
12071
12072     // Otherwise, lower to two pairs of 32-bit loads / stores.
12073     SDValue LoAddr = Ld->getBasePtr();
12074     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12075                                  DAG.getConstant(4, MVT::i32));
12076
12077     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12078                                Ld->getPointerInfo(),
12079                                Ld->isVolatile(), Ld->isNonTemporal(),
12080                                Ld->getAlignment());
12081     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12082                                Ld->getPointerInfo().getWithOffset(4),
12083                                Ld->isVolatile(), Ld->isNonTemporal(),
12084                                MinAlign(Ld->getAlignment(), 4));
12085
12086     SDValue NewChain = LoLd.getValue(1);
12087     if (TokenFactorIndex != -1) {
12088       Ops.push_back(LoLd);
12089       Ops.push_back(HiLd);
12090       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12091                              Ops.size());
12092     }
12093
12094     LoAddr = St->getBasePtr();
12095     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12096                          DAG.getConstant(4, MVT::i32));
12097
12098     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12099                                 St->getPointerInfo(),
12100                                 St->isVolatile(), St->isNonTemporal(),
12101                                 St->getAlignment());
12102     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12103                                 St->getPointerInfo().getWithOffset(4),
12104                                 St->isVolatile(),
12105                                 St->isNonTemporal(),
12106                                 MinAlign(St->getAlignment(), 4));
12107     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12108   }
12109   return SDValue();
12110 }
12111
12112 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12113 /// X86ISD::FXOR nodes.
12114 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12115   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12116   // F[X]OR(0.0, x) -> x
12117   // F[X]OR(x, 0.0) -> x
12118   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12119     if (C->getValueAPF().isPosZero())
12120       return N->getOperand(1);
12121   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12122     if (C->getValueAPF().isPosZero())
12123       return N->getOperand(0);
12124   return SDValue();
12125 }
12126
12127 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12128 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12129   // FAND(0.0, x) -> 0.0
12130   // FAND(x, 0.0) -> 0.0
12131   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12132     if (C->getValueAPF().isPosZero())
12133       return N->getOperand(0);
12134   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12135     if (C->getValueAPF().isPosZero())
12136       return N->getOperand(1);
12137   return SDValue();
12138 }
12139
12140 static SDValue PerformBTCombine(SDNode *N,
12141                                 SelectionDAG &DAG,
12142                                 TargetLowering::DAGCombinerInfo &DCI) {
12143   // BT ignores high bits in the bit index operand.
12144   SDValue Op1 = N->getOperand(1);
12145   if (Op1.hasOneUse()) {
12146     unsigned BitWidth = Op1.getValueSizeInBits();
12147     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12148     APInt KnownZero, KnownOne;
12149     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12150                                           !DCI.isBeforeLegalizeOps());
12151     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12152     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12153         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12154       DCI.CommitTargetLoweringOpt(TLO);
12155   }
12156   return SDValue();
12157 }
12158
12159 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12160   SDValue Op = N->getOperand(0);
12161   if (Op.getOpcode() == ISD::BITCAST)
12162     Op = Op.getOperand(0);
12163   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12164   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12165       VT.getVectorElementType().getSizeInBits() ==
12166       OpVT.getVectorElementType().getSizeInBits()) {
12167     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12168   }
12169   return SDValue();
12170 }
12171
12172 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12173   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12174   //           (and (i32 x86isd::setcc_carry), 1)
12175   // This eliminates the zext. This transformation is necessary because
12176   // ISD::SETCC is always legalized to i8.
12177   DebugLoc dl = N->getDebugLoc();
12178   SDValue N0 = N->getOperand(0);
12179   EVT VT = N->getValueType(0);
12180   if (N0.getOpcode() == ISD::AND &&
12181       N0.hasOneUse() &&
12182       N0.getOperand(0).hasOneUse()) {
12183     SDValue N00 = N0.getOperand(0);
12184     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12185       return SDValue();
12186     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12187     if (!C || C->getZExtValue() != 1)
12188       return SDValue();
12189     return DAG.getNode(ISD::AND, dl, VT,
12190                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12191                                    N00.getOperand(0), N00.getOperand(1)),
12192                        DAG.getConstant(1, VT));
12193   }
12194
12195   return SDValue();
12196 }
12197
12198 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12199 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12200   unsigned X86CC = N->getConstantOperandVal(0);
12201   SDValue EFLAG = N->getOperand(1);
12202   DebugLoc DL = N->getDebugLoc();
12203
12204   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12205   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12206   // cases.
12207   if (X86CC == X86::COND_B)
12208     return DAG.getNode(ISD::AND, DL, MVT::i8,
12209                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12210                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12211                        DAG.getConstant(1, MVT::i8));
12212
12213   return SDValue();
12214 }
12215
12216 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12217                                         const X86TargetLowering *XTLI) {
12218   SDValue Op0 = N->getOperand(0);
12219   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12220   // a 32-bit target where SSE doesn't support i64->FP operations.
12221   if (Op0.getOpcode() == ISD::LOAD) {
12222     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12223     EVT VT = Ld->getValueType(0);
12224     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12225         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12226         !XTLI->getSubtarget()->is64Bit() &&
12227         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12228       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12229                                           Ld->getChain(), Op0, DAG);
12230       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12231       return FILDChain;
12232     }
12233   }
12234   return SDValue();
12235 }
12236
12237 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12238 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12239                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12240   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12241   // the result is either zero or one (depending on the input carry bit).
12242   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12243   if (X86::isZeroNode(N->getOperand(0)) &&
12244       X86::isZeroNode(N->getOperand(1)) &&
12245       // We don't have a good way to replace an EFLAGS use, so only do this when
12246       // dead right now.
12247       SDValue(N, 1).use_empty()) {
12248     DebugLoc DL = N->getDebugLoc();
12249     EVT VT = N->getValueType(0);
12250     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12251     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12252                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12253                                            DAG.getConstant(X86::COND_B,MVT::i8),
12254                                            N->getOperand(2)),
12255                                DAG.getConstant(1, VT));
12256     return DCI.CombineTo(N, Res1, CarryOut);
12257   }
12258
12259   return SDValue();
12260 }
12261
12262 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12263 //      (add Y, (setne X, 0)) -> sbb -1, Y
12264 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12265 //      (sub (setne X, 0), Y) -> adc -1, Y
12266 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12267   DebugLoc DL = N->getDebugLoc();
12268
12269   // Look through ZExts.
12270   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12271   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12272     return SDValue();
12273
12274   SDValue SetCC = Ext.getOperand(0);
12275   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12276     return SDValue();
12277
12278   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12279   if (CC != X86::COND_E && CC != X86::COND_NE)
12280     return SDValue();
12281
12282   SDValue Cmp = SetCC.getOperand(1);
12283   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12284       !X86::isZeroNode(Cmp.getOperand(1)) ||
12285       !Cmp.getOperand(0).getValueType().isInteger())
12286     return SDValue();
12287
12288   SDValue CmpOp0 = Cmp.getOperand(0);
12289   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12290                                DAG.getConstant(1, CmpOp0.getValueType()));
12291
12292   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12293   if (CC == X86::COND_NE)
12294     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12295                        DL, OtherVal.getValueType(), OtherVal,
12296                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12297   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12298                      DL, OtherVal.getValueType(), OtherVal,
12299                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12300 }
12301
12302 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12303                                              DAGCombinerInfo &DCI) const {
12304   SelectionDAG &DAG = DCI.DAG;
12305   switch (N->getOpcode()) {
12306   default: break;
12307   case ISD::EXTRACT_VECTOR_ELT:
12308     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12309   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12310   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12311   case ISD::ADD:
12312   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12313   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12314   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12315   case ISD::SHL:
12316   case ISD::SRA:
12317   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12318   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12319   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12320   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12321   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12322   case X86ISD::FXOR:
12323   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12324   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12325   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12326   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12327   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12328   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12329   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12330   case X86ISD::SHUFPD:
12331   case X86ISD::PALIGN:
12332   case X86ISD::PUNPCKHBW:
12333   case X86ISD::PUNPCKHWD:
12334   case X86ISD::PUNPCKHDQ:
12335   case X86ISD::PUNPCKHQDQ:
12336   case X86ISD::UNPCKHPS:
12337   case X86ISD::UNPCKHPD:
12338   case X86ISD::PUNPCKLBW:
12339   case X86ISD::PUNPCKLWD:
12340   case X86ISD::PUNPCKLDQ:
12341   case X86ISD::PUNPCKLQDQ:
12342   case X86ISD::UNPCKLPS:
12343   case X86ISD::UNPCKLPD:
12344   case X86ISD::VUNPCKLPS:
12345   case X86ISD::VUNPCKLPD:
12346   case X86ISD::VUNPCKLPSY:
12347   case X86ISD::VUNPCKLPDY:
12348   case X86ISD::MOVHLPS:
12349   case X86ISD::MOVLHPS:
12350   case X86ISD::PSHUFD:
12351   case X86ISD::PSHUFHW:
12352   case X86ISD::PSHUFLW:
12353   case X86ISD::MOVSS:
12354   case X86ISD::MOVSD:
12355   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12356   }
12357
12358   return SDValue();
12359 }
12360
12361 /// isTypeDesirableForOp - Return true if the target has native support for
12362 /// the specified value type and it is 'desirable' to use the type for the
12363 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12364 /// instruction encodings are longer and some i16 instructions are slow.
12365 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12366   if (!isTypeLegal(VT))
12367     return false;
12368   if (VT != MVT::i16)
12369     return true;
12370
12371   switch (Opc) {
12372   default:
12373     return true;
12374   case ISD::LOAD:
12375   case ISD::SIGN_EXTEND:
12376   case ISD::ZERO_EXTEND:
12377   case ISD::ANY_EXTEND:
12378   case ISD::SHL:
12379   case ISD::SRL:
12380   case ISD::SUB:
12381   case ISD::ADD:
12382   case ISD::MUL:
12383   case ISD::AND:
12384   case ISD::OR:
12385   case ISD::XOR:
12386     return false;
12387   }
12388 }
12389
12390 /// IsDesirableToPromoteOp - This method query the target whether it is
12391 /// beneficial for dag combiner to promote the specified node. If true, it
12392 /// should return the desired promotion type by reference.
12393 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12394   EVT VT = Op.getValueType();
12395   if (VT != MVT::i16)
12396     return false;
12397
12398   bool Promote = false;
12399   bool Commute = false;
12400   switch (Op.getOpcode()) {
12401   default: break;
12402   case ISD::LOAD: {
12403     LoadSDNode *LD = cast<LoadSDNode>(Op);
12404     // If the non-extending load has a single use and it's not live out, then it
12405     // might be folded.
12406     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12407                                                      Op.hasOneUse()*/) {
12408       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12409              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12410         // The only case where we'd want to promote LOAD (rather then it being
12411         // promoted as an operand is when it's only use is liveout.
12412         if (UI->getOpcode() != ISD::CopyToReg)
12413           return false;
12414       }
12415     }
12416     Promote = true;
12417     break;
12418   }
12419   case ISD::SIGN_EXTEND:
12420   case ISD::ZERO_EXTEND:
12421   case ISD::ANY_EXTEND:
12422     Promote = true;
12423     break;
12424   case ISD::SHL:
12425   case ISD::SRL: {
12426     SDValue N0 = Op.getOperand(0);
12427     // Look out for (store (shl (load), x)).
12428     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12429       return false;
12430     Promote = true;
12431     break;
12432   }
12433   case ISD::ADD:
12434   case ISD::MUL:
12435   case ISD::AND:
12436   case ISD::OR:
12437   case ISD::XOR:
12438     Commute = true;
12439     // fallthrough
12440   case ISD::SUB: {
12441     SDValue N0 = Op.getOperand(0);
12442     SDValue N1 = Op.getOperand(1);
12443     if (!Commute && MayFoldLoad(N1))
12444       return false;
12445     // Avoid disabling potential load folding opportunities.
12446     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12447       return false;
12448     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12449       return false;
12450     Promote = true;
12451   }
12452   }
12453
12454   PVT = MVT::i32;
12455   return Promote;
12456 }
12457
12458 //===----------------------------------------------------------------------===//
12459 //                           X86 Inline Assembly Support
12460 //===----------------------------------------------------------------------===//
12461
12462 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12463   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12464
12465   std::string AsmStr = IA->getAsmString();
12466
12467   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12468   SmallVector<StringRef, 4> AsmPieces;
12469   SplitString(AsmStr, AsmPieces, ";\n");
12470
12471   switch (AsmPieces.size()) {
12472   default: return false;
12473   case 1:
12474     AsmStr = AsmPieces[0];
12475     AsmPieces.clear();
12476     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12477
12478     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12479     // we will turn this bswap into something that will be lowered to logical ops
12480     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12481     // so don't worry about this.
12482     // bswap $0
12483     if (AsmPieces.size() == 2 &&
12484         (AsmPieces[0] == "bswap" ||
12485          AsmPieces[0] == "bswapq" ||
12486          AsmPieces[0] == "bswapl") &&
12487         (AsmPieces[1] == "$0" ||
12488          AsmPieces[1] == "${0:q}")) {
12489       // No need to check constraints, nothing other than the equivalent of
12490       // "=r,0" would be valid here.
12491       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12492       if (!Ty || Ty->getBitWidth() % 16 != 0)
12493         return false;
12494       return IntrinsicLowering::LowerToByteSwap(CI);
12495     }
12496     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12497     if (CI->getType()->isIntegerTy(16) &&
12498         AsmPieces.size() == 3 &&
12499         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12500         AsmPieces[1] == "$$8," &&
12501         AsmPieces[2] == "${0:w}" &&
12502         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12503       AsmPieces.clear();
12504       const std::string &ConstraintsStr = IA->getConstraintString();
12505       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12506       std::sort(AsmPieces.begin(), AsmPieces.end());
12507       if (AsmPieces.size() == 4 &&
12508           AsmPieces[0] == "~{cc}" &&
12509           AsmPieces[1] == "~{dirflag}" &&
12510           AsmPieces[2] == "~{flags}" &&
12511           AsmPieces[3] == "~{fpsr}") {
12512         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12513         if (!Ty || Ty->getBitWidth() % 16 != 0)
12514           return false;
12515         return IntrinsicLowering::LowerToByteSwap(CI);
12516       }
12517     }
12518     break;
12519   case 3:
12520     if (CI->getType()->isIntegerTy(32) &&
12521         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12522       SmallVector<StringRef, 4> Words;
12523       SplitString(AsmPieces[0], Words, " \t,");
12524       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12525           Words[2] == "${0:w}") {
12526         Words.clear();
12527         SplitString(AsmPieces[1], Words, " \t,");
12528         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12529             Words[2] == "$0") {
12530           Words.clear();
12531           SplitString(AsmPieces[2], Words, " \t,");
12532           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12533               Words[2] == "${0:w}") {
12534             AsmPieces.clear();
12535             const std::string &ConstraintsStr = IA->getConstraintString();
12536             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12537             std::sort(AsmPieces.begin(), AsmPieces.end());
12538             if (AsmPieces.size() == 4 &&
12539                 AsmPieces[0] == "~{cc}" &&
12540                 AsmPieces[1] == "~{dirflag}" &&
12541                 AsmPieces[2] == "~{flags}" &&
12542                 AsmPieces[3] == "~{fpsr}") {
12543               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12544               if (!Ty || Ty->getBitWidth() % 16 != 0)
12545                 return false;
12546               return IntrinsicLowering::LowerToByteSwap(CI);
12547             }
12548           }
12549         }
12550       }
12551     }
12552
12553     if (CI->getType()->isIntegerTy(64)) {
12554       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12555       if (Constraints.size() >= 2 &&
12556           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12557           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12558         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12559         SmallVector<StringRef, 4> Words;
12560         SplitString(AsmPieces[0], Words, " \t");
12561         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12562           Words.clear();
12563           SplitString(AsmPieces[1], Words, " \t");
12564           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12565             Words.clear();
12566             SplitString(AsmPieces[2], Words, " \t,");
12567             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12568                 Words[2] == "%edx") {
12569               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12570               if (!Ty || Ty->getBitWidth() % 16 != 0)
12571                 return false;
12572               return IntrinsicLowering::LowerToByteSwap(CI);
12573             }
12574           }
12575         }
12576       }
12577     }
12578     break;
12579   }
12580   return false;
12581 }
12582
12583
12584
12585 /// getConstraintType - Given a constraint letter, return the type of
12586 /// constraint it is for this target.
12587 X86TargetLowering::ConstraintType
12588 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12589   if (Constraint.size() == 1) {
12590     switch (Constraint[0]) {
12591     case 'R':
12592     case 'q':
12593     case 'Q':
12594     case 'f':
12595     case 't':
12596     case 'u':
12597     case 'y':
12598     case 'x':
12599     case 'Y':
12600       return C_RegisterClass;
12601     case 'a':
12602     case 'b':
12603     case 'c':
12604     case 'd':
12605     case 'S':
12606     case 'D':
12607     case 'A':
12608       return C_Register;
12609     case 'I':
12610     case 'J':
12611     case 'K':
12612     case 'L':
12613     case 'M':
12614     case 'N':
12615     case 'G':
12616     case 'C':
12617     case 'e':
12618     case 'Z':
12619       return C_Other;
12620     default:
12621       break;
12622     }
12623   }
12624   return TargetLowering::getConstraintType(Constraint);
12625 }
12626
12627 /// Examine constraint type and operand type and determine a weight value.
12628 /// This object must already have been set up with the operand type
12629 /// and the current alternative constraint selected.
12630 TargetLowering::ConstraintWeight
12631   X86TargetLowering::getSingleConstraintMatchWeight(
12632     AsmOperandInfo &info, const char *constraint) const {
12633   ConstraintWeight weight = CW_Invalid;
12634   Value *CallOperandVal = info.CallOperandVal;
12635     // If we don't have a value, we can't do a match,
12636     // but allow it at the lowest weight.
12637   if (CallOperandVal == NULL)
12638     return CW_Default;
12639   const Type *type = CallOperandVal->getType();
12640   // Look at the constraint type.
12641   switch (*constraint) {
12642   default:
12643     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12644   case 'R':
12645   case 'q':
12646   case 'Q':
12647   case 'a':
12648   case 'b':
12649   case 'c':
12650   case 'd':
12651   case 'S':
12652   case 'D':
12653   case 'A':
12654     if (CallOperandVal->getType()->isIntegerTy())
12655       weight = CW_SpecificReg;
12656     break;
12657   case 'f':
12658   case 't':
12659   case 'u':
12660       if (type->isFloatingPointTy())
12661         weight = CW_SpecificReg;
12662       break;
12663   case 'y':
12664       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12665         weight = CW_SpecificReg;
12666       break;
12667   case 'x':
12668   case 'Y':
12669     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12670       weight = CW_Register;
12671     break;
12672   case 'I':
12673     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12674       if (C->getZExtValue() <= 31)
12675         weight = CW_Constant;
12676     }
12677     break;
12678   case 'J':
12679     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12680       if (C->getZExtValue() <= 63)
12681         weight = CW_Constant;
12682     }
12683     break;
12684   case 'K':
12685     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12686       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12687         weight = CW_Constant;
12688     }
12689     break;
12690   case 'L':
12691     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12692       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12693         weight = CW_Constant;
12694     }
12695     break;
12696   case 'M':
12697     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12698       if (C->getZExtValue() <= 3)
12699         weight = CW_Constant;
12700     }
12701     break;
12702   case 'N':
12703     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12704       if (C->getZExtValue() <= 0xff)
12705         weight = CW_Constant;
12706     }
12707     break;
12708   case 'G':
12709   case 'C':
12710     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12711       weight = CW_Constant;
12712     }
12713     break;
12714   case 'e':
12715     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12716       if ((C->getSExtValue() >= -0x80000000LL) &&
12717           (C->getSExtValue() <= 0x7fffffffLL))
12718         weight = CW_Constant;
12719     }
12720     break;
12721   case 'Z':
12722     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12723       if (C->getZExtValue() <= 0xffffffff)
12724         weight = CW_Constant;
12725     }
12726     break;
12727   }
12728   return weight;
12729 }
12730
12731 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12732 /// with another that has more specific requirements based on the type of the
12733 /// corresponding operand.
12734 const char *X86TargetLowering::
12735 LowerXConstraint(EVT ConstraintVT) const {
12736   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12737   // 'f' like normal targets.
12738   if (ConstraintVT.isFloatingPoint()) {
12739     if (Subtarget->hasXMMInt())
12740       return "Y";
12741     if (Subtarget->hasXMM())
12742       return "x";
12743   }
12744
12745   return TargetLowering::LowerXConstraint(ConstraintVT);
12746 }
12747
12748 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12749 /// vector.  If it is invalid, don't add anything to Ops.
12750 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12751                                                      std::string &Constraint,
12752                                                      std::vector<SDValue>&Ops,
12753                                                      SelectionDAG &DAG) const {
12754   SDValue Result(0, 0);
12755
12756   // Only support length 1 constraints for now.
12757   if (Constraint.length() > 1) return;
12758
12759   char ConstraintLetter = Constraint[0];
12760   switch (ConstraintLetter) {
12761   default: break;
12762   case 'I':
12763     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12764       if (C->getZExtValue() <= 31) {
12765         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12766         break;
12767       }
12768     }
12769     return;
12770   case 'J':
12771     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12772       if (C->getZExtValue() <= 63) {
12773         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12774         break;
12775       }
12776     }
12777     return;
12778   case 'K':
12779     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12780       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12781         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12782         break;
12783       }
12784     }
12785     return;
12786   case 'N':
12787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12788       if (C->getZExtValue() <= 255) {
12789         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12790         break;
12791       }
12792     }
12793     return;
12794   case 'e': {
12795     // 32-bit signed value
12796     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12797       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12798                                            C->getSExtValue())) {
12799         // Widen to 64 bits here to get it sign extended.
12800         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12801         break;
12802       }
12803     // FIXME gcc accepts some relocatable values here too, but only in certain
12804     // memory models; it's complicated.
12805     }
12806     return;
12807   }
12808   case 'Z': {
12809     // 32-bit unsigned value
12810     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12811       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12812                                            C->getZExtValue())) {
12813         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12814         break;
12815       }
12816     }
12817     // FIXME gcc accepts some relocatable values here too, but only in certain
12818     // memory models; it's complicated.
12819     return;
12820   }
12821   case 'i': {
12822     // Literal immediates are always ok.
12823     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12824       // Widen to 64 bits here to get it sign extended.
12825       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12826       break;
12827     }
12828
12829     // In any sort of PIC mode addresses need to be computed at runtime by
12830     // adding in a register or some sort of table lookup.  These can't
12831     // be used as immediates.
12832     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12833       return;
12834
12835     // If we are in non-pic codegen mode, we allow the address of a global (with
12836     // an optional displacement) to be used with 'i'.
12837     GlobalAddressSDNode *GA = 0;
12838     int64_t Offset = 0;
12839
12840     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12841     while (1) {
12842       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12843         Offset += GA->getOffset();
12844         break;
12845       } else if (Op.getOpcode() == ISD::ADD) {
12846         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12847           Offset += C->getZExtValue();
12848           Op = Op.getOperand(0);
12849           continue;
12850         }
12851       } else if (Op.getOpcode() == ISD::SUB) {
12852         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12853           Offset += -C->getZExtValue();
12854           Op = Op.getOperand(0);
12855           continue;
12856         }
12857       }
12858
12859       // Otherwise, this isn't something we can handle, reject it.
12860       return;
12861     }
12862
12863     const GlobalValue *GV = GA->getGlobal();
12864     // If we require an extra load to get this address, as in PIC mode, we
12865     // can't accept it.
12866     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12867                                                         getTargetMachine())))
12868       return;
12869
12870     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12871                                         GA->getValueType(0), Offset);
12872     break;
12873   }
12874   }
12875
12876   if (Result.getNode()) {
12877     Ops.push_back(Result);
12878     return;
12879   }
12880   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12881 }
12882
12883 std::vector<unsigned> X86TargetLowering::
12884 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12885                                   EVT VT) const {
12886   if (Constraint.size() == 1) {
12887     // FIXME: not handling fp-stack yet!
12888     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12889     default: break;  // Unknown constraint letter
12890     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12891       if (Subtarget->is64Bit()) {
12892         if (VT == MVT::i32)
12893           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12894                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12895                                        X86::R10D,X86::R11D,X86::R12D,
12896                                        X86::R13D,X86::R14D,X86::R15D,
12897                                        X86::EBP, X86::ESP, 0);
12898         else if (VT == MVT::i16)
12899           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12900                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12901                                        X86::R10W,X86::R11W,X86::R12W,
12902                                        X86::R13W,X86::R14W,X86::R15W,
12903                                        X86::BP,  X86::SP, 0);
12904         else if (VT == MVT::i8)
12905           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12906                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12907                                        X86::R10B,X86::R11B,X86::R12B,
12908                                        X86::R13B,X86::R14B,X86::R15B,
12909                                        X86::BPL, X86::SPL, 0);
12910
12911         else if (VT == MVT::i64)
12912           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12913                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12914                                        X86::R10, X86::R11, X86::R12,
12915                                        X86::R13, X86::R14, X86::R15,
12916                                        X86::RBP, X86::RSP, 0);
12917
12918         break;
12919       }
12920       // 32-bit fallthrough
12921     case 'Q':   // Q_REGS
12922       if (VT == MVT::i32)
12923         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12924       else if (VT == MVT::i16)
12925         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12926       else if (VT == MVT::i8)
12927         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12928       else if (VT == MVT::i64)
12929         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12930       break;
12931     }
12932   }
12933
12934   return std::vector<unsigned>();
12935 }
12936
12937 std::pair<unsigned, const TargetRegisterClass*>
12938 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12939                                                 EVT VT) const {
12940   // First, see if this is a constraint that directly corresponds to an LLVM
12941   // register class.
12942   if (Constraint.size() == 1) {
12943     // GCC Constraint Letters
12944     switch (Constraint[0]) {
12945     default: break;
12946     case 'r':   // GENERAL_REGS
12947     case 'l':   // INDEX_REGS
12948       if (VT == MVT::i8)
12949         return std::make_pair(0U, X86::GR8RegisterClass);
12950       if (VT == MVT::i16)
12951         return std::make_pair(0U, X86::GR16RegisterClass);
12952       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12953         return std::make_pair(0U, X86::GR32RegisterClass);
12954       return std::make_pair(0U, X86::GR64RegisterClass);
12955     case 'R':   // LEGACY_REGS
12956       if (VT == MVT::i8)
12957         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12958       if (VT == MVT::i16)
12959         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12960       if (VT == MVT::i32 || !Subtarget->is64Bit())
12961         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12962       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12963     case 'f':  // FP Stack registers.
12964       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12965       // value to the correct fpstack register class.
12966       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12967         return std::make_pair(0U, X86::RFP32RegisterClass);
12968       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12969         return std::make_pair(0U, X86::RFP64RegisterClass);
12970       return std::make_pair(0U, X86::RFP80RegisterClass);
12971     case 'y':   // MMX_REGS if MMX allowed.
12972       if (!Subtarget->hasMMX()) break;
12973       return std::make_pair(0U, X86::VR64RegisterClass);
12974     case 'Y':   // SSE_REGS if SSE2 allowed
12975       if (!Subtarget->hasXMMInt()) break;
12976       // FALL THROUGH.
12977     case 'x':   // SSE_REGS if SSE1 allowed
12978       if (!Subtarget->hasXMM()) break;
12979
12980       switch (VT.getSimpleVT().SimpleTy) {
12981       default: break;
12982       // Scalar SSE types.
12983       case MVT::f32:
12984       case MVT::i32:
12985         return std::make_pair(0U, X86::FR32RegisterClass);
12986       case MVT::f64:
12987       case MVT::i64:
12988         return std::make_pair(0U, X86::FR64RegisterClass);
12989       // Vector types.
12990       case MVT::v16i8:
12991       case MVT::v8i16:
12992       case MVT::v4i32:
12993       case MVT::v2i64:
12994       case MVT::v4f32:
12995       case MVT::v2f64:
12996         return std::make_pair(0U, X86::VR128RegisterClass);
12997       }
12998       break;
12999     }
13000   }
13001
13002   // Use the default implementation in TargetLowering to convert the register
13003   // constraint into a member of a register class.
13004   std::pair<unsigned, const TargetRegisterClass*> Res;
13005   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13006
13007   // Not found as a standard register?
13008   if (Res.second == 0) {
13009     // Map st(0) -> st(7) -> ST0
13010     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13011         tolower(Constraint[1]) == 's' &&
13012         tolower(Constraint[2]) == 't' &&
13013         Constraint[3] == '(' &&
13014         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13015         Constraint[5] == ')' &&
13016         Constraint[6] == '}') {
13017
13018       Res.first = X86::ST0+Constraint[4]-'0';
13019       Res.second = X86::RFP80RegisterClass;
13020       return Res;
13021     }
13022
13023     // GCC allows "st(0)" to be called just plain "st".
13024     if (StringRef("{st}").equals_lower(Constraint)) {
13025       Res.first = X86::ST0;
13026       Res.second = X86::RFP80RegisterClass;
13027       return Res;
13028     }
13029
13030     // flags -> EFLAGS
13031     if (StringRef("{flags}").equals_lower(Constraint)) {
13032       Res.first = X86::EFLAGS;
13033       Res.second = X86::CCRRegisterClass;
13034       return Res;
13035     }
13036
13037     // 'A' means EAX + EDX.
13038     if (Constraint == "A") {
13039       Res.first = X86::EAX;
13040       Res.second = X86::GR32_ADRegisterClass;
13041       return Res;
13042     }
13043     return Res;
13044   }
13045
13046   // Otherwise, check to see if this is a register class of the wrong value
13047   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13048   // turn into {ax},{dx}.
13049   if (Res.second->hasType(VT))
13050     return Res;   // Correct type already, nothing to do.
13051
13052   // All of the single-register GCC register classes map their values onto
13053   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13054   // really want an 8-bit or 32-bit register, map to the appropriate register
13055   // class and return the appropriate register.
13056   if (Res.second == X86::GR16RegisterClass) {
13057     if (VT == MVT::i8) {
13058       unsigned DestReg = 0;
13059       switch (Res.first) {
13060       default: break;
13061       case X86::AX: DestReg = X86::AL; break;
13062       case X86::DX: DestReg = X86::DL; break;
13063       case X86::CX: DestReg = X86::CL; break;
13064       case X86::BX: DestReg = X86::BL; break;
13065       }
13066       if (DestReg) {
13067         Res.first = DestReg;
13068         Res.second = X86::GR8RegisterClass;
13069       }
13070     } else if (VT == MVT::i32) {
13071       unsigned DestReg = 0;
13072       switch (Res.first) {
13073       default: break;
13074       case X86::AX: DestReg = X86::EAX; break;
13075       case X86::DX: DestReg = X86::EDX; break;
13076       case X86::CX: DestReg = X86::ECX; break;
13077       case X86::BX: DestReg = X86::EBX; break;
13078       case X86::SI: DestReg = X86::ESI; break;
13079       case X86::DI: DestReg = X86::EDI; break;
13080       case X86::BP: DestReg = X86::EBP; break;
13081       case X86::SP: DestReg = X86::ESP; break;
13082       }
13083       if (DestReg) {
13084         Res.first = DestReg;
13085         Res.second = X86::GR32RegisterClass;
13086       }
13087     } else if (VT == MVT::i64) {
13088       unsigned DestReg = 0;
13089       switch (Res.first) {
13090       default: break;
13091       case X86::AX: DestReg = X86::RAX; break;
13092       case X86::DX: DestReg = X86::RDX; break;
13093       case X86::CX: DestReg = X86::RCX; break;
13094       case X86::BX: DestReg = X86::RBX; break;
13095       case X86::SI: DestReg = X86::RSI; break;
13096       case X86::DI: DestReg = X86::RDI; break;
13097       case X86::BP: DestReg = X86::RBP; break;
13098       case X86::SP: DestReg = X86::RSP; break;
13099       }
13100       if (DestReg) {
13101         Res.first = DestReg;
13102         Res.second = X86::GR64RegisterClass;
13103       }
13104     }
13105   } else if (Res.second == X86::FR32RegisterClass ||
13106              Res.second == X86::FR64RegisterClass ||
13107              Res.second == X86::VR128RegisterClass) {
13108     // Handle references to XMM physical registers that got mapped into the
13109     // wrong class.  This can happen with constraints like {xmm0} where the
13110     // target independent register mapper will just pick the first match it can
13111     // find, ignoring the required type.
13112     if (VT == MVT::f32)
13113       Res.second = X86::FR32RegisterClass;
13114     else if (VT == MVT::f64)
13115       Res.second = X86::FR64RegisterClass;
13116     else if (X86::VR128RegisterClass->hasType(VT))
13117       Res.second = X86::VR128RegisterClass;
13118   }
13119
13120   return Res;
13121 }