85c6f4923510935175adc5258f3a35663cd924f3
[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   EVT ElVT = VT.getVectorElementType();
89   int Factor = VT.getSizeInBits()/128;
90   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
91                                   VT.getVectorNumElements()/Factor);
92
93   // Extract from UNDEF is UNDEF.
94   if (Vec.getOpcode() == ISD::UNDEF)
95     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
96
97   if (isa<ConstantSDNode>(Idx)) {
98     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
99
100     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
101     // we can match to VEXTRACTF128.
102     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
103
104     // This is the index of the first element of the 128-bit chunk
105     // we want.
106     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107                                  * ElemsPerChunk);
108
109     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
110     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
111                                  VecIdx);
112
113     return Result;
114   }
115
116   return SDValue();
117 }
118
119 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
120 /// sets things up to match to an AVX VINSERTF128 instruction or a
121 /// simple superregister reference.  Idx is an index in the 128 bits
122 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
123 /// lowering INSERT_VECTOR_ELT operations easier.
124 static SDValue Insert128BitVector(SDValue Result,
125                                   SDValue Vec,
126                                   SDValue Idx,
127                                   SelectionDAG &DAG,
128                                   DebugLoc dl) {
129   if (isa<ConstantSDNode>(Idx)) {
130     EVT VT = Vec.getValueType();
131     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
132
133     EVT ElVT = VT.getVectorElementType();
134     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
135     EVT ResultVT = Result.getValueType();
136
137     // Insert the relevant 128 bits.
138     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
139
140     // This is the index of the first element of the 128-bit chunk
141     // we want.
142     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143                                  * ElemsPerChunk);
144
145     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
146     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
147                          VecIdx);
148     return Result;
149   }
150
151   return SDValue();
152 }
153
154 /// Given two vectors, concat them.
155 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
156   DebugLoc dl = Lower.getDebugLoc();
157
158   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
159
160   EVT VT = EVT::getVectorVT(*DAG.getContext(),
161                             Lower.getValueType().getVectorElementType(),
162                             Lower.getValueType().getVectorNumElements() * 2);
163
164   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
165   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
166
167   // Insert the upper subvector.
168   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
169                                    DAG.getConstant(
170                                      // This is half the length of the result
171                                      // vector.  Start inserting the upper 128
172                                      // bits here.
173                                      Lower.getValueType().getVectorNumElements(),
174                                      MVT::i32),
175                                    DAG, dl);
176
177   // Insert the lower subvector.
178   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
179   return Vec;
180 }
181
182 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
183   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
184   bool is64Bit = Subtarget->is64Bit();
185
186   if (Subtarget->isTargetEnvMacho()) {
187     if (is64Bit)
188       return new X8664_MachoTargetObjectFile();
189     return new TargetLoweringObjectFileMachO();
190   }
191
192   if (Subtarget->isTargetELF())
193     return new TargetLoweringObjectFileELF();
194   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(TM)) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasXMMInt();
203   X86ScalarSSEf32 = Subtarget->hasXMM();
204   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
205
206   RegInfo = TM.getRegisterInfo();
207   TD = getTargetData();
208
209   // Set up the TargetLowering object.
210   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
211
212   // X86 is weird, it always uses i8 for shift amounts and setcc results.
213   setBooleanContents(ZeroOrOneBooleanContent);
214
215   // For 64-bit since we have so many registers use the ILP scheduler, for
216   // 32-bit code use the register pressure specific scheduling.
217   if (Subtarget->is64Bit())
218     setSchedulingPreference(Sched::ILP);
219   else
220     setSchedulingPreference(Sched::RegPressure);
221   setStackPointerRegisterToSaveRestore(X86StackPtr);
222
223   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
224     // Setup Windows compiler runtime calls.
225     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
226     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
227     setLibcallName(RTLIB::SREM_I64, "_allrem");
228     setLibcallName(RTLIB::UREM_I64, "_aullrem");
229     setLibcallName(RTLIB::MUL_I64, "_allmul");
230     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
231     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
232     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
233     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
234     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
235     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
236     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
237     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
238     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
239   }
240
241   if (Subtarget->isTargetDarwin()) {
242     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
243     setUseUnderscoreSetJmp(false);
244     setUseUnderscoreLongJmp(false);
245   } else if (Subtarget->isTargetMingw()) {
246     // MS runtime is weird: it exports _setjmp, but longjmp!
247     setUseUnderscoreSetJmp(true);
248     setUseUnderscoreLongJmp(false);
249   } else {
250     setUseUnderscoreSetJmp(true);
251     setUseUnderscoreLongJmp(true);
252   }
253
254   // Set up the register classes.
255   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
256   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
257   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
258   if (Subtarget->is64Bit())
259     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
260
261   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
262
263   // We don't accept any truncstore of integer registers.
264   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
265   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
266   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
267   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
268   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
269   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
270
271   // SETOEQ and SETUNE require checking two conditions.
272   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
273   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
274   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
275   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
276   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
277   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
278
279   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
280   // operation.
281   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
282   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
283   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
284
285   if (Subtarget->is64Bit()) {
286     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
287     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
288   } else if (!UseSoftFloat) {
289     // We have an algorithm for SSE2->double, and we turn this into a
290     // 64-bit FILD followed by conditional FADD for other targets.
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
292     // We have an algorithm for SSE2, and we turn this into a 64-bit
293     // FILD for other targets.
294     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
295   }
296
297   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
298   // this operation.
299   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
300   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
301
302   if (!UseSoftFloat) {
303     // SSE has no i16 to fp conversion, only i32
304     if (X86ScalarSSEf32) {
305       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
306       // f32 and f64 cases are Legal, f80 case is not
307       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
308     } else {
309       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
311     }
312   } else {
313     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
314     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
315   }
316
317   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
318   // are Legal, f80 is custom lowered.
319   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
320   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
321
322   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
323   // this operation.
324   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
325   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
326
327   if (X86ScalarSSEf32) {
328     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
329     // f32 and f64 cases are Legal, f80 case is not
330     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
331   } else {
332     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
334   }
335
336   // Handle FP_TO_UINT by promoting the destination to a larger signed
337   // conversion.
338   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
339   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
340   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
341
342   if (Subtarget->is64Bit()) {
343     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
344     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
345   } else if (!UseSoftFloat) {
346     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
347       // Expand FP_TO_UINT into a select.
348       // FIXME: We would like to use a Custom expander here eventually to do
349       // the optimal thing for SSE vs. the default expansion in the legalizer.
350       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
351     else
352       // With SSE3 we can use fisttpll to convert to a signed i64; without
353       // SSE, we're stuck with a fistpll.
354       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
355   }
356
357   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
358   if (!X86ScalarSSEf64) {
359     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
360     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
361     if (Subtarget->is64Bit()) {
362       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
363       // Without SSE, i64->f64 goes through memory.
364       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
365     }
366   }
367
368   // Scalar integer divide and remainder are lowered to use operations that
369   // produce two results, to match the available instructions. This exposes
370   // the two-result form to trivial CSE, which is able to combine x/y and x%y
371   // into a single instruction.
372   //
373   // Scalar integer multiply-high is also lowered to use two-result
374   // operations, to match the available instructions. However, plain multiply
375   // (low) operations are left as Legal, as there are single-result
376   // instructions for this in x86. Using the two-result multiply instructions
377   // when both high and low results are needed must be arranged by dagcombine.
378   for (unsigned i = 0, e = 4; i != e; ++i) {
379     MVT VT = IntVTs[i];
380     setOperationAction(ISD::MULHS, VT, Expand);
381     setOperationAction(ISD::MULHU, VT, Expand);
382     setOperationAction(ISD::SDIV, VT, Expand);
383     setOperationAction(ISD::UDIV, VT, Expand);
384     setOperationAction(ISD::SREM, VT, Expand);
385     setOperationAction(ISD::UREM, VT, Expand);
386
387     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
388     setOperationAction(ISD::ADDC, VT, Custom);
389     setOperationAction(ISD::ADDE, VT, Custom);
390     setOperationAction(ISD::SUBC, VT, Custom);
391     setOperationAction(ISD::SUBE, VT, Custom);
392   }
393
394   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
395   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
396   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
397   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
398   if (Subtarget->is64Bit())
399     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
400   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
401   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
402   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
403   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
404   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
405   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
406   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
407   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
408
409   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
410   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
411   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
412   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
413   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
414   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
418   }
419
420   if (Subtarget->hasPOPCNT()) {
421     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
422   } else {
423     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
424     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
425     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
426     if (Subtarget->is64Bit())
427       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
428   }
429
430   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
431   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
432
433   // These should be promoted to a larger select which is supported.
434   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
435   // X86 wants to expand cmov itself.
436   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
437   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
439   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
440   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
443   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
448   if (Subtarget->is64Bit()) {
449     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
450     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
451   }
452   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
453
454   // Darwin ABI issue.
455   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
456   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
457   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
458   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
459   if (Subtarget->is64Bit())
460     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
461   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
462   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
463   if (Subtarget->is64Bit()) {
464     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
465     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
466     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
467     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
468     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
469   }
470   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
471   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
472   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
473   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
474   if (Subtarget->is64Bit()) {
475     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
476     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
477     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
478   }
479
480   if (Subtarget->hasXMM())
481     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
482
483   // We may not have a libcall for MEMBARRIER so we should lower this.
484   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
485
486   // On X86 and X86-64, atomic operations are lowered to locked instructions.
487   // Locked instructions, in turn, have implicit fence semantics (all memory
488   // operations are flushed before issuing the locked instruction, and they
489   // are not buffered), so we can fold away the common pattern of
490   // fence-atomic-fence.
491   setShouldFoldAtomicFences(true);
492
493   // Expand certain atomics
494   for (unsigned i = 0, e = 4; i != e; ++i) {
495     MVT VT = IntVTs[i];
496     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
497     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
498   }
499
500   if (!Subtarget->is64Bit()) {
501     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
508   }
509
510   // FIXME - use subtarget debug flags
511   if (!Subtarget->isTargetDarwin() &&
512       !Subtarget->isTargetELF() &&
513       !Subtarget->isTargetCygMing()) {
514     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
515   }
516
517   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
518   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
519   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
520   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
521   if (Subtarget->is64Bit()) {
522     setExceptionPointerRegister(X86::RAX);
523     setExceptionSelectorRegister(X86::RDX);
524   } else {
525     setExceptionPointerRegister(X86::EAX);
526     setExceptionSelectorRegister(X86::EDX);
527   }
528   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
529   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
530
531   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
532
533   setOperationAction(ISD::TRAP, MVT::Other, Legal);
534
535   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
536   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
537   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
538   if (Subtarget->is64Bit()) {
539     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
540     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
541   } else {
542     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
543     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
544   }
545
546   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
547   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
548   setOperationAction(ISD::DYNAMIC_STACKALLOC,
549                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
550                      (Subtarget->isTargetCOFF()
551                       && !Subtarget->isTargetEnvMacho()
552                       ? Custom : Expand));
553
554   if (!UseSoftFloat && X86ScalarSSEf64) {
555     // f32 and f64 use SSE.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
558     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
559
560     // Use ANDPD to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f64, Custom);
562     setOperationAction(ISD::FABS , MVT::f32, Custom);
563
564     // Use XORP to simulate FNEG.
565     setOperationAction(ISD::FNEG , MVT::f64, Custom);
566     setOperationAction(ISD::FNEG , MVT::f32, Custom);
567
568     // Use ANDPD and ORPD to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // Lower this to FGETSIGNx86 plus an AND.
573     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
574     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
575
576     // We don't support sin/cos/fmod
577     setOperationAction(ISD::FSIN , MVT::f64, Expand);
578     setOperationAction(ISD::FCOS , MVT::f64, Expand);
579     setOperationAction(ISD::FSIN , MVT::f32, Expand);
580     setOperationAction(ISD::FCOS , MVT::f32, Expand);
581
582     // Expand FP immediates into loads from the stack, except for the special
583     // cases we handle.
584     addLegalFPImmediate(APFloat(+0.0)); // xorpd
585     addLegalFPImmediate(APFloat(+0.0f)); // xorps
586   } else if (!UseSoftFloat && X86ScalarSSEf32) {
587     // Use SSE for f32, x87 for f64.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
590     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
591
592     // Use ANDPS to simulate FABS.
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f32, Custom);
597
598     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
599
600     // Use ANDPS and ORPS to simulate FCOPYSIGN.
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603
604     // We don't support sin/cos/fmod
605     setOperationAction(ISD::FSIN , MVT::f32, Expand);
606     setOperationAction(ISD::FCOS , MVT::f32, Expand);
607
608     // Special cases we handle for FP constants.
609     addLegalFPImmediate(APFloat(+0.0f)); // xorps
610     addLegalFPImmediate(APFloat(+0.0)); // FLD0
611     addLegalFPImmediate(APFloat(+1.0)); // FLD1
612     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
613     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
614
615     if (!UnsafeFPMath) {
616       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
617       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
618     }
619   } else if (!UseSoftFloat) {
620     // f32 and f64 in x87.
621     // Set up the FP register classes.
622     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
623     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
624
625     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
626     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
627     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
629
630     if (!UnsafeFPMath) {
631       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633     }
634     addLegalFPImmediate(APFloat(+0.0)); // FLD0
635     addLegalFPImmediate(APFloat(+1.0)); // FLD1
636     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
637     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
638     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
639     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
640     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
641     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
642   }
643
644   // We don't support FMA.
645   setOperationAction(ISD::FMA, MVT::f64, Expand);
646   setOperationAction(ISD::FMA, MVT::f32, Expand);
647
648   // Long double always uses X87.
649   if (!UseSoftFloat) {
650     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
651     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
652     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
653     {
654       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
655       addLegalFPImmediate(TmpFlt);  // FLD0
656       TmpFlt.changeSign();
657       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
658
659       bool ignored;
660       APFloat TmpFlt2(+1.0);
661       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
662                       &ignored);
663       addLegalFPImmediate(TmpFlt2);  // FLD1
664       TmpFlt2.changeSign();
665       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
666     }
667
668     if (!UnsafeFPMath) {
669       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
670       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
671     }
672
673     setOperationAction(ISD::FMA, MVT::f80, Expand);
674   }
675
676   // Always use a library call for pow.
677   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
679   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
680
681   setOperationAction(ISD::FLOG, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
683   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP, MVT::f80, Expand);
685   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
686
687   // First set operation action for all vector types to either promote
688   // (for widening) or expand (for scalarization). Then we will selectively
689   // turn on ones that can be effectively codegen'd.
690   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
691        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
692     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
707     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
710     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
742     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
746     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
747          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
748       setTruncStoreAction((MVT::SimpleValueType)VT,
749                           (MVT::SimpleValueType)InnerVT, Expand);
750     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
752     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!UseSoftFloat && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
765   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
767   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
768   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
769   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
770   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
771   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
772   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
773   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
774   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
775   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
776   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
777   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
778   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
779   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
783   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
784   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
785   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
786   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
788   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
792   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
793
794   if (!UseSoftFloat && Subtarget->hasXMM()) {
795     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
796
797     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
802     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
803     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
804     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
805     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
806     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
807     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
808     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
809   }
810
811   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
812     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
813
814     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
815     // registers cannot be used even for integer operations.
816     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
819     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
820
821     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
822     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
823     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
824     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
826     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
827     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
828     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
829     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
830     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
831     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
835     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
836     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
837
838     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
841     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
842
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
848
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
853     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
854
855     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
856     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
857       EVT VT = (MVT::SimpleValueType)i;
858       // Do not attempt to custom lower non-power-of-2 vectors
859       if (!isPowerOf2_32(VT.getVectorNumElements()))
860         continue;
861       // Do not attempt to custom lower non-128-bit vectors
862       if (!VT.is128BitVector())
863         continue;
864       setOperationAction(ISD::BUILD_VECTOR,
865                          VT.getSimpleVT().SimpleTy, Custom);
866       setOperationAction(ISD::VECTOR_SHUFFLE,
867                          VT.getSimpleVT().SimpleTy, Custom);
868       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
869                          VT.getSimpleVT().SimpleTy, Custom);
870     }
871
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
873     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
875     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
876     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
877     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
878
879     if (Subtarget->is64Bit()) {
880       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
881       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
882     }
883
884     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
885     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
886       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
887       EVT VT = SVT;
888
889       // Do not attempt to promote non-128-bit vectors
890       if (!VT.is128BitVector())
891         continue;
892
893       setOperationAction(ISD::AND,    SVT, Promote);
894       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
895       setOperationAction(ISD::OR,     SVT, Promote);
896       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
897       setOperationAction(ISD::XOR,    SVT, Promote);
898       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
899       setOperationAction(ISD::LOAD,   SVT, Promote);
900       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
901       setOperationAction(ISD::SELECT, SVT, Promote);
902       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
903     }
904
905     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
906
907     // Custom lower v2i64 and v2f64 selects.
908     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
909     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
910     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
911     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
912
913     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
914     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
915   }
916
917   if (Subtarget->hasSSE41()) {
918     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
923     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
924     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
925     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
926     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
927     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
928
929     // FIXME: Do we need to handle scalar-to-vector here?
930     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
931
932     // Can turn SHL into an integer multiply.
933     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
934     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
935
936     // i8 and i16 vectors are custom , because the source register and source
937     // source memory operand types are not the same width.  f32 vectors are
938     // custom since the immediate controlling the insert encodes additional
939     // information.
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
944
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
949
950     if (Subtarget->is64Bit()) {
951       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
952       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
953     }
954   }
955
956   if (Subtarget->hasSSE2()) {
957     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
958     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
959     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
960
961     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
962     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
963     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
964
965     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
966     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
967   }
968
969   if (Subtarget->hasSSE42())
970     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
971
972   if (!UseSoftFloat && Subtarget->hasAVX()) {
973     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
974     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
976     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
977     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
978     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
979
980     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
982     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
983
984     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
988     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
989     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
990
991     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
995     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
996     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
997
998     // Custom lower several nodes for 256-bit types.
999     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1000                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1001       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1002       EVT VT = SVT;
1003
1004       // Extract subvector is special because the value type
1005       // (result) is 128-bit but the source is 256-bit wide.
1006       if (VT.is128BitVector())
1007         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1008
1009       // Do not attempt to custom lower other non-256-bit vectors
1010       if (!VT.is256BitVector())
1011         continue;
1012
1013       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1014       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1015       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1016       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1017       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1018       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1019     }
1020
1021     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1022     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1023       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1024       EVT VT = SVT;
1025
1026       // Do not attempt to promote non-256-bit vectors
1027       if (!VT.is256BitVector())
1028         continue;
1029
1030       setOperationAction(ISD::AND,    SVT, Promote);
1031       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1032       setOperationAction(ISD::OR,     SVT, Promote);
1033       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1034       setOperationAction(ISD::XOR,    SVT, Promote);
1035       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1036       setOperationAction(ISD::LOAD,   SVT, Promote);
1037       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1038       setOperationAction(ISD::SELECT, SVT, Promote);
1039       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1040     }
1041   }
1042
1043   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1044   // of this type with custom code.
1045   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1046          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1047     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1048   }
1049
1050   // We want to custom lower some of our intrinsics.
1051   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1052
1053
1054   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1055   // handle type legalization for these operations here.
1056   //
1057   // FIXME: We really should do custom legalization for addition and
1058   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1059   // than generic legalization for 64-bit multiplication-with-overflow, though.
1060   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1061     // Add/Sub/Mul with overflow operations are custom lowered.
1062     MVT VT = IntVTs[i];
1063     setOperationAction(ISD::SADDO, VT, Custom);
1064     setOperationAction(ISD::UADDO, VT, Custom);
1065     setOperationAction(ISD::SSUBO, VT, Custom);
1066     setOperationAction(ISD::USUBO, VT, Custom);
1067     setOperationAction(ISD::SMULO, VT, Custom);
1068     setOperationAction(ISD::UMULO, VT, Custom);
1069   }
1070
1071   // There are no 8-bit 3-address imul/mul instructions
1072   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1073   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1074
1075   if (!Subtarget->is64Bit()) {
1076     // These libcalls are not available in 32-bit.
1077     setLibcallName(RTLIB::SHL_I128, 0);
1078     setLibcallName(RTLIB::SRL_I128, 0);
1079     setLibcallName(RTLIB::SRA_I128, 0);
1080   }
1081
1082   // We have target-specific dag combine patterns for the following nodes:
1083   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1084   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1085   setTargetDAGCombine(ISD::BUILD_VECTOR);
1086   setTargetDAGCombine(ISD::SELECT);
1087   setTargetDAGCombine(ISD::SHL);
1088   setTargetDAGCombine(ISD::SRA);
1089   setTargetDAGCombine(ISD::SRL);
1090   setTargetDAGCombine(ISD::OR);
1091   setTargetDAGCombine(ISD::AND);
1092   setTargetDAGCombine(ISD::ADD);
1093   setTargetDAGCombine(ISD::SUB);
1094   setTargetDAGCombine(ISD::STORE);
1095   setTargetDAGCombine(ISD::ZERO_EXTEND);
1096   setTargetDAGCombine(ISD::SINT_TO_FP);
1097   if (Subtarget->is64Bit())
1098     setTargetDAGCombine(ISD::MUL);
1099
1100   computeRegisterProperties();
1101
1102   // On Darwin, -Os means optimize for size without hurting performance,
1103   // do not reduce the limit.
1104   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1105   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1106   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1107   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1108   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1109   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1110   setPrefLoopAlignment(16);
1111   benefitFromCodePlacementOpt = true;
1112
1113   setPrefFunctionAlignment(4);
1114 }
1115
1116
1117 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1118   return MVT::i8;
1119 }
1120
1121
1122 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1123 /// the desired ByVal argument alignment.
1124 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1125   if (MaxAlign == 16)
1126     return;
1127   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1128     if (VTy->getBitWidth() == 128)
1129       MaxAlign = 16;
1130   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1131     unsigned EltAlign = 0;
1132     getMaxByValAlign(ATy->getElementType(), EltAlign);
1133     if (EltAlign > MaxAlign)
1134       MaxAlign = EltAlign;
1135   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1136     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1137       unsigned EltAlign = 0;
1138       getMaxByValAlign(STy->getElementType(i), EltAlign);
1139       if (EltAlign > MaxAlign)
1140         MaxAlign = EltAlign;
1141       if (MaxAlign == 16)
1142         break;
1143     }
1144   }
1145   return;
1146 }
1147
1148 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1149 /// function arguments in the caller parameter area. For X86, aggregates
1150 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1151 /// are at 4-byte boundaries.
1152 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1153   if (Subtarget->is64Bit()) {
1154     // Max of 8 and alignment of type.
1155     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1156     if (TyAlign > 8)
1157       return TyAlign;
1158     return 8;
1159   }
1160
1161   unsigned Align = 4;
1162   if (Subtarget->hasXMM())
1163     getMaxByValAlign(Ty, Align);
1164   return Align;
1165 }
1166
1167 /// getOptimalMemOpType - Returns the target specific optimal type for load
1168 /// and store operations as a result of memset, memcpy, and memmove
1169 /// lowering. If DstAlign is zero that means it's safe to destination
1170 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1171 /// means there isn't a need to check it against alignment requirement,
1172 /// probably because the source does not need to be loaded. If
1173 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1174 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1175 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1176 /// constant so it does not need to be loaded.
1177 /// It returns EVT::Other if the type should be determined using generic
1178 /// target-independent logic.
1179 EVT
1180 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1181                                        unsigned DstAlign, unsigned SrcAlign,
1182                                        bool NonScalarIntSafe,
1183                                        bool MemcpyStrSrc,
1184                                        MachineFunction &MF) const {
1185   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1186   // linux.  This is because the stack realignment code can't handle certain
1187   // cases like PR2962.  This should be removed when PR2962 is fixed.
1188   const Function *F = MF.getFunction();
1189   if (NonScalarIntSafe &&
1190       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1191     if (Size >= 16 &&
1192         (Subtarget->isUnalignedMemAccessFast() ||
1193          ((DstAlign == 0 || DstAlign >= 16) &&
1194           (SrcAlign == 0 || SrcAlign >= 16))) &&
1195         Subtarget->getStackAlignment() >= 16) {
1196       if (Subtarget->hasSSE2())
1197         return MVT::v4i32;
1198       if (Subtarget->hasSSE1())
1199         return MVT::v4f32;
1200     } else if (!MemcpyStrSrc && Size >= 8 &&
1201                !Subtarget->is64Bit() &&
1202                Subtarget->getStackAlignment() >= 8 &&
1203                Subtarget->hasXMMInt()) {
1204       // Do not use f64 to lower memcpy if source is string constant. It's
1205       // better to use i32 to avoid the loads.
1206       return MVT::f64;
1207     }
1208   }
1209   if (Subtarget->is64Bit() && Size >= 8)
1210     return MVT::i64;
1211   return MVT::i32;
1212 }
1213
1214 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1215 /// current function.  The returned value is a member of the
1216 /// MachineJumpTableInfo::JTEntryKind enum.
1217 unsigned X86TargetLowering::getJumpTableEncoding() const {
1218   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1219   // symbol.
1220   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1221       Subtarget->isPICStyleGOT())
1222     return MachineJumpTableInfo::EK_Custom32;
1223
1224   // Otherwise, use the normal jump table encoding heuristics.
1225   return TargetLowering::getJumpTableEncoding();
1226 }
1227
1228 const MCExpr *
1229 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1230                                              const MachineBasicBlock *MBB,
1231                                              unsigned uid,MCContext &Ctx) const{
1232   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1233          Subtarget->isPICStyleGOT());
1234   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1235   // entries.
1236   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1237                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1238 }
1239
1240 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1241 /// jumptable.
1242 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1243                                                     SelectionDAG &DAG) const {
1244   if (!Subtarget->is64Bit())
1245     // This doesn't have DebugLoc associated with it, but is not really the
1246     // same as a Register.
1247     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1248   return Table;
1249 }
1250
1251 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1252 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1253 /// MCExpr.
1254 const MCExpr *X86TargetLowering::
1255 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1256                              MCContext &Ctx) const {
1257   // X86-64 uses RIP relative addressing based on the jump table label.
1258   if (Subtarget->isPICStyleRIPRel())
1259     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1260
1261   // Otherwise, the reference is relative to the PIC base.
1262   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1263 }
1264
1265 // FIXME: Why this routine is here? Move to RegInfo!
1266 std::pair<const TargetRegisterClass*, uint8_t>
1267 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1268   const TargetRegisterClass *RRC = 0;
1269   uint8_t Cost = 1;
1270   switch (VT.getSimpleVT().SimpleTy) {
1271   default:
1272     return TargetLowering::findRepresentativeClass(VT);
1273   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1274     RRC = (Subtarget->is64Bit()
1275            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1276     break;
1277   case MVT::x86mmx:
1278     RRC = X86::VR64RegisterClass;
1279     break;
1280   case MVT::f32: case MVT::f64:
1281   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1282   case MVT::v4f32: case MVT::v2f64:
1283   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1284   case MVT::v4f64:
1285     RRC = X86::VR128RegisterClass;
1286     break;
1287   }
1288   return std::make_pair(RRC, Cost);
1289 }
1290
1291 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1292                                                unsigned &Offset) const {
1293   if (!Subtarget->isTargetLinux())
1294     return false;
1295
1296   if (Subtarget->is64Bit()) {
1297     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1298     Offset = 0x28;
1299     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1300       AddressSpace = 256;
1301     else
1302       AddressSpace = 257;
1303   } else {
1304     // %gs:0x14 on i386
1305     Offset = 0x14;
1306     AddressSpace = 256;
1307   }
1308   return true;
1309 }
1310
1311
1312 //===----------------------------------------------------------------------===//
1313 //               Return Value Calling Convention Implementation
1314 //===----------------------------------------------------------------------===//
1315
1316 #include "X86GenCallingConv.inc"
1317
1318 bool
1319 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1320                                   MachineFunction &MF, bool isVarArg,
1321                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1322                         LLVMContext &Context) const {
1323   SmallVector<CCValAssign, 16> RVLocs;
1324   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1325                  RVLocs, Context);
1326   return CCInfo.CheckReturn(Outs, RetCC_X86);
1327 }
1328
1329 SDValue
1330 X86TargetLowering::LowerReturn(SDValue Chain,
1331                                CallingConv::ID CallConv, bool isVarArg,
1332                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1333                                const SmallVectorImpl<SDValue> &OutVals,
1334                                DebugLoc dl, SelectionDAG &DAG) const {
1335   MachineFunction &MF = DAG.getMachineFunction();
1336   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1337
1338   SmallVector<CCValAssign, 16> RVLocs;
1339   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1340                  RVLocs, *DAG.getContext());
1341   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1342
1343   // Add the regs to the liveout set for the function.
1344   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1345   for (unsigned i = 0; i != RVLocs.size(); ++i)
1346     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1347       MRI.addLiveOut(RVLocs[i].getLocReg());
1348
1349   SDValue Flag;
1350
1351   SmallVector<SDValue, 6> RetOps;
1352   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1353   // Operand #1 = Bytes To Pop
1354   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1355                    MVT::i16));
1356
1357   // Copy the result values into the output registers.
1358   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1359     CCValAssign &VA = RVLocs[i];
1360     assert(VA.isRegLoc() && "Can only return in registers!");
1361     SDValue ValToCopy = OutVals[i];
1362     EVT ValVT = ValToCopy.getValueType();
1363
1364     // If this is x86-64, and we disabled SSE, we can't return FP values,
1365     // or SSE or MMX vectors.
1366     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1367          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1368           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1369       report_fatal_error("SSE register return with SSE disabled");
1370     }
1371     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1372     // llvm-gcc has never done it right and no one has noticed, so this
1373     // should be OK for now.
1374     if (ValVT == MVT::f64 &&
1375         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1376       report_fatal_error("SSE2 register return with SSE2 disabled");
1377
1378     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1379     // the RET instruction and handled by the FP Stackifier.
1380     if (VA.getLocReg() == X86::ST0 ||
1381         VA.getLocReg() == X86::ST1) {
1382       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1383       // change the value to the FP stack register class.
1384       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1385         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1386       RetOps.push_back(ValToCopy);
1387       // Don't emit a copytoreg.
1388       continue;
1389     }
1390
1391     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1392     // which is returned in RAX / RDX.
1393     if (Subtarget->is64Bit()) {
1394       if (ValVT == MVT::x86mmx) {
1395         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1396           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1397           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1398                                   ValToCopy);
1399           // If we don't have SSE2 available, convert to v4f32 so the generated
1400           // register is legal.
1401           if (!Subtarget->hasSSE2())
1402             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1403         }
1404       }
1405     }
1406
1407     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1408     Flag = Chain.getValue(1);
1409   }
1410
1411   // The x86-64 ABI for returning structs by value requires that we copy
1412   // the sret argument into %rax for the return. We saved the argument into
1413   // a virtual register in the entry block, so now we copy the value out
1414   // and into %rax.
1415   if (Subtarget->is64Bit() &&
1416       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1417     MachineFunction &MF = DAG.getMachineFunction();
1418     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1419     unsigned Reg = FuncInfo->getSRetReturnReg();
1420     assert(Reg &&
1421            "SRetReturnReg should have been set in LowerFormalArguments().");
1422     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1423
1424     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1425     Flag = Chain.getValue(1);
1426
1427     // RAX now acts like a return value.
1428     MRI.addLiveOut(X86::RAX);
1429   }
1430
1431   RetOps[0] = Chain;  // Update chain.
1432
1433   // Add the flag if we have it.
1434   if (Flag.getNode())
1435     RetOps.push_back(Flag);
1436
1437   return DAG.getNode(X86ISD::RET_FLAG, dl,
1438                      MVT::Other, &RetOps[0], RetOps.size());
1439 }
1440
1441 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1442   if (N->getNumValues() != 1)
1443     return false;
1444   if (!N->hasNUsesOfValue(1, 0))
1445     return false;
1446
1447   SDNode *Copy = *N->use_begin();
1448   if (Copy->getOpcode() != ISD::CopyToReg &&
1449       Copy->getOpcode() != ISD::FP_EXTEND)
1450     return false;
1451
1452   bool HasRet = false;
1453   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1454        UI != UE; ++UI) {
1455     if (UI->getOpcode() != X86ISD::RET_FLAG)
1456       return false;
1457     HasRet = true;
1458   }
1459
1460   return HasRet;
1461 }
1462
1463 EVT
1464 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1465                                             ISD::NodeType ExtendKind) const {
1466   MVT ReturnMVT;
1467   // TODO: Is this also valid on 32-bit?
1468   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1469     ReturnMVT = MVT::i8;
1470   else
1471     ReturnMVT = MVT::i32;
1472
1473   EVT MinVT = getRegisterType(Context, ReturnMVT);
1474   return VT.bitsLT(MinVT) ? MinVT : VT;
1475 }
1476
1477 /// LowerCallResult - Lower the result values of a call into the
1478 /// appropriate copies out of appropriate physical registers.
1479 ///
1480 SDValue
1481 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1482                                    CallingConv::ID CallConv, bool isVarArg,
1483                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1484                                    DebugLoc dl, SelectionDAG &DAG,
1485                                    SmallVectorImpl<SDValue> &InVals) const {
1486
1487   // Assign locations to each value returned by this call.
1488   SmallVector<CCValAssign, 16> RVLocs;
1489   bool Is64Bit = Subtarget->is64Bit();
1490   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1491                  getTargetMachine(), RVLocs, *DAG.getContext());
1492   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1493
1494   // Copy all of the result registers out of their specified physreg.
1495   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1496     CCValAssign &VA = RVLocs[i];
1497     EVT CopyVT = VA.getValVT();
1498
1499     // If this is x86-64, and we disabled SSE, we can't return FP values
1500     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1501         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1502       report_fatal_error("SSE register return with SSE disabled");
1503     }
1504
1505     SDValue Val;
1506
1507     // If this is a call to a function that returns an fp value on the floating
1508     // point stack, we must guarantee the the value is popped from the stack, so
1509     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1510     // if the return value is not used. We use the FpPOP_RETVAL instruction
1511     // instead.
1512     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1513       // If we prefer to use the value in xmm registers, copy it out as f80 and
1514       // use a truncate to move it from fp stack reg to xmm reg.
1515       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1516       SDValue Ops[] = { Chain, InFlag };
1517       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1518                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1519       Val = Chain.getValue(0);
1520
1521       // Round the f80 to the right size, which also moves it to the appropriate
1522       // xmm register.
1523       if (CopyVT != VA.getValVT())
1524         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1525                           // This truncation won't change the value.
1526                           DAG.getIntPtrConstant(1));
1527     } else {
1528       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1529                                  CopyVT, InFlag).getValue(1);
1530       Val = Chain.getValue(0);
1531     }
1532     InFlag = Chain.getValue(2);
1533     InVals.push_back(Val);
1534   }
1535
1536   return Chain;
1537 }
1538
1539
1540 //===----------------------------------------------------------------------===//
1541 //                C & StdCall & Fast Calling Convention implementation
1542 //===----------------------------------------------------------------------===//
1543 //  StdCall calling convention seems to be standard for many Windows' API
1544 //  routines and around. It differs from C calling convention just a little:
1545 //  callee should clean up the stack, not caller. Symbols should be also
1546 //  decorated in some fancy way :) It doesn't support any vector arguments.
1547 //  For info on fast calling convention see Fast Calling Convention (tail call)
1548 //  implementation LowerX86_32FastCCCallTo.
1549
1550 /// CallIsStructReturn - Determines whether a call uses struct return
1551 /// semantics.
1552 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1553   if (Outs.empty())
1554     return false;
1555
1556   return Outs[0].Flags.isSRet();
1557 }
1558
1559 /// ArgsAreStructReturn - Determines whether a function uses struct
1560 /// return semantics.
1561 static bool
1562 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1563   if (Ins.empty())
1564     return false;
1565
1566   return Ins[0].Flags.isSRet();
1567 }
1568
1569 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1570 /// by "Src" to address "Dst" with size and alignment information specified by
1571 /// the specific parameter attribute. The copy will be passed as a byval
1572 /// function parameter.
1573 static SDValue
1574 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1575                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1576                           DebugLoc dl) {
1577   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1578
1579   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1580                        /*isVolatile*/false, /*AlwaysInline=*/true,
1581                        MachinePointerInfo(), MachinePointerInfo());
1582 }
1583
1584 /// IsTailCallConvention - Return true if the calling convention is one that
1585 /// supports tail call optimization.
1586 static bool IsTailCallConvention(CallingConv::ID CC) {
1587   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1588 }
1589
1590 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1591   if (!CI->isTailCall())
1592     return false;
1593
1594   CallSite CS(CI);
1595   CallingConv::ID CalleeCC = CS.getCallingConv();
1596   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1597     return false;
1598
1599   return true;
1600 }
1601
1602 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1603 /// a tailcall target by changing its ABI.
1604 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1605   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1606 }
1607
1608 SDValue
1609 X86TargetLowering::LowerMemArgument(SDValue Chain,
1610                                     CallingConv::ID CallConv,
1611                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1612                                     DebugLoc dl, SelectionDAG &DAG,
1613                                     const CCValAssign &VA,
1614                                     MachineFrameInfo *MFI,
1615                                     unsigned i) const {
1616   // Create the nodes corresponding to a load from this parameter slot.
1617   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1618   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1619   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1620   EVT ValVT;
1621
1622   // If value is passed by pointer we have address passed instead of the value
1623   // itself.
1624   if (VA.getLocInfo() == CCValAssign::Indirect)
1625     ValVT = VA.getLocVT();
1626   else
1627     ValVT = VA.getValVT();
1628
1629   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1630   // changed with more analysis.
1631   // In case of tail call optimization mark all arguments mutable. Since they
1632   // could be overwritten by lowering of arguments in case of a tail call.
1633   if (Flags.isByVal()) {
1634     unsigned Bytes = Flags.getByValSize();
1635     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1636     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1637     return DAG.getFrameIndex(FI, getPointerTy());
1638   } else {
1639     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1640                                     VA.getLocMemOffset(), isImmutable);
1641     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1642     return DAG.getLoad(ValVT, dl, Chain, FIN,
1643                        MachinePointerInfo::getFixedStack(FI),
1644                        false, false, 0);
1645   }
1646 }
1647
1648 SDValue
1649 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1650                                         CallingConv::ID CallConv,
1651                                         bool isVarArg,
1652                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1653                                         DebugLoc dl,
1654                                         SelectionDAG &DAG,
1655                                         SmallVectorImpl<SDValue> &InVals)
1656                                           const {
1657   MachineFunction &MF = DAG.getMachineFunction();
1658   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1659
1660   const Function* Fn = MF.getFunction();
1661   if (Fn->hasExternalLinkage() &&
1662       Subtarget->isTargetCygMing() &&
1663       Fn->getName() == "main")
1664     FuncInfo->setForceFramePointer(true);
1665
1666   MachineFrameInfo *MFI = MF.getFrameInfo();
1667   bool Is64Bit = Subtarget->is64Bit();
1668   bool IsWin64 = Subtarget->isTargetWin64();
1669
1670   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1671          "Var args not supported with calling convention fastcc or ghc");
1672
1673   // Assign locations to all of the incoming arguments.
1674   SmallVector<CCValAssign, 16> ArgLocs;
1675   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1676                  ArgLocs, *DAG.getContext());
1677
1678   // Allocate shadow area for Win64
1679   if (IsWin64) {
1680     CCInfo.AllocateStack(32, 8);
1681   }
1682
1683   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1684
1685   unsigned LastVal = ~0U;
1686   SDValue ArgValue;
1687   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1688     CCValAssign &VA = ArgLocs[i];
1689     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1690     // places.
1691     assert(VA.getValNo() != LastVal &&
1692            "Don't support value assigned to multiple locs yet");
1693     LastVal = VA.getValNo();
1694
1695     if (VA.isRegLoc()) {
1696       EVT RegVT = VA.getLocVT();
1697       TargetRegisterClass *RC = NULL;
1698       if (RegVT == MVT::i32)
1699         RC = X86::GR32RegisterClass;
1700       else if (Is64Bit && RegVT == MVT::i64)
1701         RC = X86::GR64RegisterClass;
1702       else if (RegVT == MVT::f32)
1703         RC = X86::FR32RegisterClass;
1704       else if (RegVT == MVT::f64)
1705         RC = X86::FR64RegisterClass;
1706       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1707         RC = X86::VR256RegisterClass;
1708       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1709         RC = X86::VR128RegisterClass;
1710       else if (RegVT == MVT::x86mmx)
1711         RC = X86::VR64RegisterClass;
1712       else
1713         llvm_unreachable("Unknown argument type!");
1714
1715       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1716       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1717
1718       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1719       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1720       // right size.
1721       if (VA.getLocInfo() == CCValAssign::SExt)
1722         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1723                                DAG.getValueType(VA.getValVT()));
1724       else if (VA.getLocInfo() == CCValAssign::ZExt)
1725         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1726                                DAG.getValueType(VA.getValVT()));
1727       else if (VA.getLocInfo() == CCValAssign::BCvt)
1728         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1729
1730       if (VA.isExtInLoc()) {
1731         // Handle MMX values passed in XMM regs.
1732         if (RegVT.isVector()) {
1733           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1734                                  ArgValue);
1735         } else
1736           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1737       }
1738     } else {
1739       assert(VA.isMemLoc());
1740       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1741     }
1742
1743     // If value is passed via pointer - do a load.
1744     if (VA.getLocInfo() == CCValAssign::Indirect)
1745       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1746                              MachinePointerInfo(), false, false, 0);
1747
1748     InVals.push_back(ArgValue);
1749   }
1750
1751   // The x86-64 ABI for returning structs by value requires that we copy
1752   // the sret argument into %rax for the return. Save the argument into
1753   // a virtual register so that we can access it from the return points.
1754   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1755     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1756     unsigned Reg = FuncInfo->getSRetReturnReg();
1757     if (!Reg) {
1758       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1759       FuncInfo->setSRetReturnReg(Reg);
1760     }
1761     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1762     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1763   }
1764
1765   unsigned StackSize = CCInfo.getNextStackOffset();
1766   // Align stack specially for tail calls.
1767   if (FuncIsMadeTailCallSafe(CallConv))
1768     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1769
1770   // If the function takes variable number of arguments, make a frame index for
1771   // the start of the first vararg value... for expansion of llvm.va_start.
1772   if (isVarArg) {
1773     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1774                     CallConv != CallingConv::X86_ThisCall)) {
1775       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1776     }
1777     if (Is64Bit) {
1778       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1779
1780       // FIXME: We should really autogenerate these arrays
1781       static const unsigned GPR64ArgRegsWin64[] = {
1782         X86::RCX, X86::RDX, X86::R8,  X86::R9
1783       };
1784       static const unsigned GPR64ArgRegs64Bit[] = {
1785         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1786       };
1787       static const unsigned XMMArgRegs64Bit[] = {
1788         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1789         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1790       };
1791       const unsigned *GPR64ArgRegs;
1792       unsigned NumXMMRegs = 0;
1793
1794       if (IsWin64) {
1795         // The XMM registers which might contain var arg parameters are shadowed
1796         // in their paired GPR.  So we only need to save the GPR to their home
1797         // slots.
1798         TotalNumIntRegs = 4;
1799         GPR64ArgRegs = GPR64ArgRegsWin64;
1800       } else {
1801         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1802         GPR64ArgRegs = GPR64ArgRegs64Bit;
1803
1804         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1805       }
1806       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1807                                                        TotalNumIntRegs);
1808
1809       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1810       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1811              "SSE register cannot be used when SSE is disabled!");
1812       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1813              "SSE register cannot be used when SSE is disabled!");
1814       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1815         // Kernel mode asks for SSE to be disabled, so don't push them
1816         // on the stack.
1817         TotalNumXMMRegs = 0;
1818
1819       if (IsWin64) {
1820         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1821         // Get to the caller-allocated home save location.  Add 8 to account
1822         // for the return address.
1823         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1824         FuncInfo->setRegSaveFrameIndex(
1825           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1826         // Fixup to set vararg frame on shadow area (4 x i64).
1827         if (NumIntRegs < 4)
1828           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1829       } else {
1830         // For X86-64, if there are vararg parameters that are passed via
1831         // registers, then we must store them to their spots on the stack so they
1832         // may be loaded by deferencing the result of va_next.
1833         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1834         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1835         FuncInfo->setRegSaveFrameIndex(
1836           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1837                                false));
1838       }
1839
1840       // Store the integer parameter registers.
1841       SmallVector<SDValue, 8> MemOps;
1842       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1843                                         getPointerTy());
1844       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1845       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1846         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1847                                   DAG.getIntPtrConstant(Offset));
1848         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1849                                      X86::GR64RegisterClass);
1850         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1851         SDValue Store =
1852           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1853                        MachinePointerInfo::getFixedStack(
1854                          FuncInfo->getRegSaveFrameIndex(), Offset),
1855                        false, false, 0);
1856         MemOps.push_back(Store);
1857         Offset += 8;
1858       }
1859
1860       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1861         // Now store the XMM (fp + vector) parameter registers.
1862         SmallVector<SDValue, 11> SaveXMMOps;
1863         SaveXMMOps.push_back(Chain);
1864
1865         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1866         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1867         SaveXMMOps.push_back(ALVal);
1868
1869         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1870                                FuncInfo->getRegSaveFrameIndex()));
1871         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1872                                FuncInfo->getVarArgsFPOffset()));
1873
1874         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1875           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1876                                        X86::VR128RegisterClass);
1877           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1878           SaveXMMOps.push_back(Val);
1879         }
1880         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1881                                      MVT::Other,
1882                                      &SaveXMMOps[0], SaveXMMOps.size()));
1883       }
1884
1885       if (!MemOps.empty())
1886         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1887                             &MemOps[0], MemOps.size());
1888     }
1889   }
1890
1891   // Some CCs need callee pop.
1892   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1893     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1894   } else {
1895     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1896     // If this is an sret function, the return should pop the hidden pointer.
1897     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1898       FuncInfo->setBytesToPopOnReturn(4);
1899   }
1900
1901   if (!Is64Bit) {
1902     // RegSaveFrameIndex is X86-64 only.
1903     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1904     if (CallConv == CallingConv::X86_FastCall ||
1905         CallConv == CallingConv::X86_ThisCall)
1906       // fastcc functions can't have varargs.
1907       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1908   }
1909
1910   return Chain;
1911 }
1912
1913 SDValue
1914 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1915                                     SDValue StackPtr, SDValue Arg,
1916                                     DebugLoc dl, SelectionDAG &DAG,
1917                                     const CCValAssign &VA,
1918                                     ISD::ArgFlagsTy Flags) const {
1919   unsigned LocMemOffset = VA.getLocMemOffset();
1920   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1921   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1922   if (Flags.isByVal())
1923     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1924
1925   return DAG.getStore(Chain, dl, Arg, PtrOff,
1926                       MachinePointerInfo::getStack(LocMemOffset),
1927                       false, false, 0);
1928 }
1929
1930 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1931 /// optimization is performed and it is required.
1932 SDValue
1933 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1934                                            SDValue &OutRetAddr, SDValue Chain,
1935                                            bool IsTailCall, bool Is64Bit,
1936                                            int FPDiff, DebugLoc dl) const {
1937   // Adjust the Return address stack slot.
1938   EVT VT = getPointerTy();
1939   OutRetAddr = getReturnAddressFrameIndex(DAG);
1940
1941   // Load the "old" Return address.
1942   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1943                            false, false, 0);
1944   return SDValue(OutRetAddr.getNode(), 1);
1945 }
1946
1947 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1948 /// optimization is performed and it is required (FPDiff!=0).
1949 static SDValue
1950 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1951                          SDValue Chain, SDValue RetAddrFrIdx,
1952                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1953   // Store the return address to the appropriate stack slot.
1954   if (!FPDiff) return Chain;
1955   // Calculate the new stack slot for the return address.
1956   int SlotSize = Is64Bit ? 8 : 4;
1957   int NewReturnAddrFI =
1958     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1959   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1960   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1961   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1962                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1963                        false, false, 0);
1964   return Chain;
1965 }
1966
1967 SDValue
1968 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1969                              CallingConv::ID CallConv, bool isVarArg,
1970                              bool &isTailCall,
1971                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1972                              const SmallVectorImpl<SDValue> &OutVals,
1973                              const SmallVectorImpl<ISD::InputArg> &Ins,
1974                              DebugLoc dl, SelectionDAG &DAG,
1975                              SmallVectorImpl<SDValue> &InVals) const {
1976   MachineFunction &MF = DAG.getMachineFunction();
1977   bool Is64Bit        = Subtarget->is64Bit();
1978   bool IsWin64        = Subtarget->isTargetWin64();
1979   bool IsStructRet    = CallIsStructReturn(Outs);
1980   bool IsSibcall      = false;
1981
1982   if (isTailCall) {
1983     // Check if it's really possible to do a tail call.
1984     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1985                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1986                                                    Outs, OutVals, Ins, DAG);
1987
1988     // Sibcalls are automatically detected tailcalls which do not require
1989     // ABI changes.
1990     if (!GuaranteedTailCallOpt && isTailCall)
1991       IsSibcall = true;
1992
1993     if (isTailCall)
1994       ++NumTailCalls;
1995   }
1996
1997   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1998          "Var args not supported with calling convention fastcc or ghc");
1999
2000   // Analyze operands of the call, assigning locations to each operand.
2001   SmallVector<CCValAssign, 16> ArgLocs;
2002   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2003                  ArgLocs, *DAG.getContext());
2004
2005   // Allocate shadow area for Win64
2006   if (IsWin64) {
2007     CCInfo.AllocateStack(32, 8);
2008   }
2009
2010   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2011
2012   // Get a count of how many bytes are to be pushed on the stack.
2013   unsigned NumBytes = CCInfo.getNextStackOffset();
2014   if (IsSibcall)
2015     // This is a sibcall. The memory operands are available in caller's
2016     // own caller's stack.
2017     NumBytes = 0;
2018   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2019     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2020
2021   int FPDiff = 0;
2022   if (isTailCall && !IsSibcall) {
2023     // Lower arguments at fp - stackoffset + fpdiff.
2024     unsigned NumBytesCallerPushed =
2025       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2026     FPDiff = NumBytesCallerPushed - NumBytes;
2027
2028     // Set the delta of movement of the returnaddr stackslot.
2029     // But only set if delta is greater than previous delta.
2030     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2031       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2032   }
2033
2034   if (!IsSibcall)
2035     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2036
2037   SDValue RetAddrFrIdx;
2038   // Load return address for tail calls.
2039   if (isTailCall && FPDiff)
2040     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2041                                     Is64Bit, FPDiff, dl);
2042
2043   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2044   SmallVector<SDValue, 8> MemOpChains;
2045   SDValue StackPtr;
2046
2047   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2048   // of tail call optimization arguments are handle later.
2049   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2050     CCValAssign &VA = ArgLocs[i];
2051     EVT RegVT = VA.getLocVT();
2052     SDValue Arg = OutVals[i];
2053     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2054     bool isByVal = Flags.isByVal();
2055
2056     // Promote the value if needed.
2057     switch (VA.getLocInfo()) {
2058     default: llvm_unreachable("Unknown loc info!");
2059     case CCValAssign::Full: break;
2060     case CCValAssign::SExt:
2061       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2062       break;
2063     case CCValAssign::ZExt:
2064       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2065       break;
2066     case CCValAssign::AExt:
2067       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2068         // Special case: passing MMX values in XMM registers.
2069         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2070         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2071         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2072       } else
2073         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2074       break;
2075     case CCValAssign::BCvt:
2076       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2077       break;
2078     case CCValAssign::Indirect: {
2079       // Store the argument.
2080       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2081       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2082       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2083                            MachinePointerInfo::getFixedStack(FI),
2084                            false, false, 0);
2085       Arg = SpillSlot;
2086       break;
2087     }
2088     }
2089
2090     if (VA.isRegLoc()) {
2091       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2092       if (isVarArg && IsWin64) {
2093         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2094         // shadow reg if callee is a varargs function.
2095         unsigned ShadowReg = 0;
2096         switch (VA.getLocReg()) {
2097         case X86::XMM0: ShadowReg = X86::RCX; break;
2098         case X86::XMM1: ShadowReg = X86::RDX; break;
2099         case X86::XMM2: ShadowReg = X86::R8; break;
2100         case X86::XMM3: ShadowReg = X86::R9; break;
2101         }
2102         if (ShadowReg)
2103           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2104       }
2105     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2106       assert(VA.isMemLoc());
2107       if (StackPtr.getNode() == 0)
2108         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2109       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2110                                              dl, DAG, VA, Flags));
2111     }
2112   }
2113
2114   if (!MemOpChains.empty())
2115     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2116                         &MemOpChains[0], MemOpChains.size());
2117
2118   // Build a sequence of copy-to-reg nodes chained together with token chain
2119   // and flag operands which copy the outgoing args into registers.
2120   SDValue InFlag;
2121   // Tail call byval lowering might overwrite argument registers so in case of
2122   // tail call optimization the copies to registers are lowered later.
2123   if (!isTailCall)
2124     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2125       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2126                                RegsToPass[i].second, InFlag);
2127       InFlag = Chain.getValue(1);
2128     }
2129
2130   if (Subtarget->isPICStyleGOT()) {
2131     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2132     // GOT pointer.
2133     if (!isTailCall) {
2134       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2135                                DAG.getNode(X86ISD::GlobalBaseReg,
2136                                            DebugLoc(), getPointerTy()),
2137                                InFlag);
2138       InFlag = Chain.getValue(1);
2139     } else {
2140       // If we are tail calling and generating PIC/GOT style code load the
2141       // address of the callee into ECX. The value in ecx is used as target of
2142       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2143       // for tail calls on PIC/GOT architectures. Normally we would just put the
2144       // address of GOT into ebx and then call target@PLT. But for tail calls
2145       // ebx would be restored (since ebx is callee saved) before jumping to the
2146       // target@PLT.
2147
2148       // Note: The actual moving to ECX is done further down.
2149       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2150       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2151           !G->getGlobal()->hasProtectedVisibility())
2152         Callee = LowerGlobalAddress(Callee, DAG);
2153       else if (isa<ExternalSymbolSDNode>(Callee))
2154         Callee = LowerExternalSymbol(Callee, DAG);
2155     }
2156   }
2157
2158   if (Is64Bit && isVarArg && !IsWin64) {
2159     // From AMD64 ABI document:
2160     // For calls that may call functions that use varargs or stdargs
2161     // (prototype-less calls or calls to functions containing ellipsis (...) in
2162     // the declaration) %al is used as hidden argument to specify the number
2163     // of SSE registers used. The contents of %al do not need to match exactly
2164     // the number of registers, but must be an ubound on the number of SSE
2165     // registers used and is in the range 0 - 8 inclusive.
2166
2167     // Count the number of XMM registers allocated.
2168     static const unsigned XMMArgRegs[] = {
2169       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2170       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2171     };
2172     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2173     assert((Subtarget->hasXMM() || !NumXMMRegs)
2174            && "SSE registers cannot be used when SSE is disabled");
2175
2176     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2177                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2178     InFlag = Chain.getValue(1);
2179   }
2180
2181
2182   // For tail calls lower the arguments to the 'real' stack slot.
2183   if (isTailCall) {
2184     // Force all the incoming stack arguments to be loaded from the stack
2185     // before any new outgoing arguments are stored to the stack, because the
2186     // outgoing stack slots may alias the incoming argument stack slots, and
2187     // the alias isn't otherwise explicit. This is slightly more conservative
2188     // than necessary, because it means that each store effectively depends
2189     // on every argument instead of just those arguments it would clobber.
2190     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2191
2192     SmallVector<SDValue, 8> MemOpChains2;
2193     SDValue FIN;
2194     int FI = 0;
2195     // Do not flag preceding copytoreg stuff together with the following stuff.
2196     InFlag = SDValue();
2197     if (GuaranteedTailCallOpt) {
2198       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2199         CCValAssign &VA = ArgLocs[i];
2200         if (VA.isRegLoc())
2201           continue;
2202         assert(VA.isMemLoc());
2203         SDValue Arg = OutVals[i];
2204         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2205         // Create frame index.
2206         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2207         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2208         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2209         FIN = DAG.getFrameIndex(FI, getPointerTy());
2210
2211         if (Flags.isByVal()) {
2212           // Copy relative to framepointer.
2213           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2214           if (StackPtr.getNode() == 0)
2215             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2216                                           getPointerTy());
2217           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2218
2219           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2220                                                            ArgChain,
2221                                                            Flags, DAG, dl));
2222         } else {
2223           // Store relative to framepointer.
2224           MemOpChains2.push_back(
2225             DAG.getStore(ArgChain, dl, Arg, FIN,
2226                          MachinePointerInfo::getFixedStack(FI),
2227                          false, false, 0));
2228         }
2229       }
2230     }
2231
2232     if (!MemOpChains2.empty())
2233       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2234                           &MemOpChains2[0], MemOpChains2.size());
2235
2236     // Copy arguments to their registers.
2237     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2238       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2239                                RegsToPass[i].second, InFlag);
2240       InFlag = Chain.getValue(1);
2241     }
2242     InFlag =SDValue();
2243
2244     // Store the return address to the appropriate stack slot.
2245     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2246                                      FPDiff, dl);
2247   }
2248
2249   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2250     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2251     // In the 64-bit large code model, we have to make all calls
2252     // through a register, since the call instruction's 32-bit
2253     // pc-relative offset may not be large enough to hold the whole
2254     // address.
2255   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2256     // If the callee is a GlobalAddress node (quite common, every direct call
2257     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2258     // it.
2259
2260     // We should use extra load for direct calls to dllimported functions in
2261     // non-JIT mode.
2262     const GlobalValue *GV = G->getGlobal();
2263     if (!GV->hasDLLImportLinkage()) {
2264       unsigned char OpFlags = 0;
2265       bool ExtraLoad = false;
2266       unsigned WrapperKind = ISD::DELETED_NODE;
2267
2268       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2269       // external symbols most go through the PLT in PIC mode.  If the symbol
2270       // has hidden or protected visibility, or if it is static or local, then
2271       // we don't need to use the PLT - we can directly call it.
2272       if (Subtarget->isTargetELF() &&
2273           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2274           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2275         OpFlags = X86II::MO_PLT;
2276       } else if (Subtarget->isPICStyleStubAny() &&
2277                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2278                  (!Subtarget->getTargetTriple().isMacOSX() ||
2279                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2280         // PC-relative references to external symbols should go through $stub,
2281         // unless we're building with the leopard linker or later, which
2282         // automatically synthesizes these stubs.
2283         OpFlags = X86II::MO_DARWIN_STUB;
2284       } else if (Subtarget->isPICStyleRIPRel() &&
2285                  isa<Function>(GV) &&
2286                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2287         // If the function is marked as non-lazy, generate an indirect call
2288         // which loads from the GOT directly. This avoids runtime overhead
2289         // at the cost of eager binding (and one extra byte of encoding).
2290         OpFlags = X86II::MO_GOTPCREL;
2291         WrapperKind = X86ISD::WrapperRIP;
2292         ExtraLoad = true;
2293       }
2294
2295       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2296                                           G->getOffset(), OpFlags);
2297
2298       // Add a wrapper if needed.
2299       if (WrapperKind != ISD::DELETED_NODE)
2300         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2301       // Add extra indirection if needed.
2302       if (ExtraLoad)
2303         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2304                              MachinePointerInfo::getGOT(),
2305                              false, false, 0);
2306     }
2307   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2308     unsigned char OpFlags = 0;
2309
2310     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2311     // external symbols should go through the PLT.
2312     if (Subtarget->isTargetELF() &&
2313         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2314       OpFlags = X86II::MO_PLT;
2315     } else if (Subtarget->isPICStyleStubAny() &&
2316                (!Subtarget->getTargetTriple().isMacOSX() ||
2317                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2318       // PC-relative references to external symbols should go through $stub,
2319       // unless we're building with the leopard linker or later, which
2320       // automatically synthesizes these stubs.
2321       OpFlags = X86II::MO_DARWIN_STUB;
2322     }
2323
2324     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2325                                          OpFlags);
2326   }
2327
2328   // Returns a chain & a flag for retval copy to use.
2329   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2330   SmallVector<SDValue, 8> Ops;
2331
2332   if (!IsSibcall && isTailCall) {
2333     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2334                            DAG.getIntPtrConstant(0, true), InFlag);
2335     InFlag = Chain.getValue(1);
2336   }
2337
2338   Ops.push_back(Chain);
2339   Ops.push_back(Callee);
2340
2341   if (isTailCall)
2342     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2343
2344   // Add argument registers to the end of the list so that they are known live
2345   // into the call.
2346   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2347     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2348                                   RegsToPass[i].second.getValueType()));
2349
2350   // Add an implicit use GOT pointer in EBX.
2351   if (!isTailCall && Subtarget->isPICStyleGOT())
2352     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2353
2354   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2355   if (Is64Bit && isVarArg && !IsWin64)
2356     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2357
2358   if (InFlag.getNode())
2359     Ops.push_back(InFlag);
2360
2361   if (isTailCall) {
2362     // We used to do:
2363     //// If this is the first return lowered for this function, add the regs
2364     //// to the liveout set for the function.
2365     // This isn't right, although it's probably harmless on x86; liveouts
2366     // should be computed from returns not tail calls.  Consider a void
2367     // function making a tail call to a function returning int.
2368     return DAG.getNode(X86ISD::TC_RETURN, dl,
2369                        NodeTys, &Ops[0], Ops.size());
2370   }
2371
2372   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2373   InFlag = Chain.getValue(1);
2374
2375   // Create the CALLSEQ_END node.
2376   unsigned NumBytesForCalleeToPush;
2377   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2378     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2379   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2380     // If this is a call to a struct-return function, the callee
2381     // pops the hidden struct pointer, so we have to push it back.
2382     // This is common for Darwin/X86, Linux & Mingw32 targets.
2383     NumBytesForCalleeToPush = 4;
2384   else
2385     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2386
2387   // Returns a flag for retval copy to use.
2388   if (!IsSibcall) {
2389     Chain = DAG.getCALLSEQ_END(Chain,
2390                                DAG.getIntPtrConstant(NumBytes, true),
2391                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2392                                                      true),
2393                                InFlag);
2394     InFlag = Chain.getValue(1);
2395   }
2396
2397   // Handle result values, copying them out of physregs into vregs that we
2398   // return.
2399   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2400                          Ins, dl, DAG, InVals);
2401 }
2402
2403
2404 //===----------------------------------------------------------------------===//
2405 //                Fast Calling Convention (tail call) implementation
2406 //===----------------------------------------------------------------------===//
2407
2408 //  Like std call, callee cleans arguments, convention except that ECX is
2409 //  reserved for storing the tail called function address. Only 2 registers are
2410 //  free for argument passing (inreg). Tail call optimization is performed
2411 //  provided:
2412 //                * tailcallopt is enabled
2413 //                * caller/callee are fastcc
2414 //  On X86_64 architecture with GOT-style position independent code only local
2415 //  (within module) calls are supported at the moment.
2416 //  To keep the stack aligned according to platform abi the function
2417 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2418 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2419 //  If a tail called function callee has more arguments than the caller the
2420 //  caller needs to make sure that there is room to move the RETADDR to. This is
2421 //  achieved by reserving an area the size of the argument delta right after the
2422 //  original REtADDR, but before the saved framepointer or the spilled registers
2423 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2424 //  stack layout:
2425 //    arg1
2426 //    arg2
2427 //    RETADDR
2428 //    [ new RETADDR
2429 //      move area ]
2430 //    (possible EBP)
2431 //    ESI
2432 //    EDI
2433 //    local1 ..
2434
2435 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2436 /// for a 16 byte align requirement.
2437 unsigned
2438 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2439                                                SelectionDAG& DAG) const {
2440   MachineFunction &MF = DAG.getMachineFunction();
2441   const TargetMachine &TM = MF.getTarget();
2442   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2443   unsigned StackAlignment = TFI.getStackAlignment();
2444   uint64_t AlignMask = StackAlignment - 1;
2445   int64_t Offset = StackSize;
2446   uint64_t SlotSize = TD->getPointerSize();
2447   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2448     // Number smaller than 12 so just add the difference.
2449     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2450   } else {
2451     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2452     Offset = ((~AlignMask) & Offset) + StackAlignment +
2453       (StackAlignment-SlotSize);
2454   }
2455   return Offset;
2456 }
2457
2458 /// MatchingStackOffset - Return true if the given stack call argument is
2459 /// already available in the same position (relatively) of the caller's
2460 /// incoming argument stack.
2461 static
2462 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2463                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2464                          const X86InstrInfo *TII) {
2465   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2466   int FI = INT_MAX;
2467   if (Arg.getOpcode() == ISD::CopyFromReg) {
2468     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2469     if (!TargetRegisterInfo::isVirtualRegister(VR))
2470       return false;
2471     MachineInstr *Def = MRI->getVRegDef(VR);
2472     if (!Def)
2473       return false;
2474     if (!Flags.isByVal()) {
2475       if (!TII->isLoadFromStackSlot(Def, FI))
2476         return false;
2477     } else {
2478       unsigned Opcode = Def->getOpcode();
2479       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2480           Def->getOperand(1).isFI()) {
2481         FI = Def->getOperand(1).getIndex();
2482         Bytes = Flags.getByValSize();
2483       } else
2484         return false;
2485     }
2486   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2487     if (Flags.isByVal())
2488       // ByVal argument is passed in as a pointer but it's now being
2489       // dereferenced. e.g.
2490       // define @foo(%struct.X* %A) {
2491       //   tail call @bar(%struct.X* byval %A)
2492       // }
2493       return false;
2494     SDValue Ptr = Ld->getBasePtr();
2495     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2496     if (!FINode)
2497       return false;
2498     FI = FINode->getIndex();
2499   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2500     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2501     FI = FINode->getIndex();
2502     Bytes = Flags.getByValSize();
2503   } else
2504     return false;
2505
2506   assert(FI != INT_MAX);
2507   if (!MFI->isFixedObjectIndex(FI))
2508     return false;
2509   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2510 }
2511
2512 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2513 /// for tail call optimization. Targets which want to do tail call
2514 /// optimization should implement this function.
2515 bool
2516 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2517                                                      CallingConv::ID CalleeCC,
2518                                                      bool isVarArg,
2519                                                      bool isCalleeStructRet,
2520                                                      bool isCallerStructRet,
2521                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2522                                     const SmallVectorImpl<SDValue> &OutVals,
2523                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2524                                                      SelectionDAG& DAG) const {
2525   if (!IsTailCallConvention(CalleeCC) &&
2526       CalleeCC != CallingConv::C)
2527     return false;
2528
2529   // If -tailcallopt is specified, make fastcc functions tail-callable.
2530   const MachineFunction &MF = DAG.getMachineFunction();
2531   const Function *CallerF = DAG.getMachineFunction().getFunction();
2532   CallingConv::ID CallerCC = CallerF->getCallingConv();
2533   bool CCMatch = CallerCC == CalleeCC;
2534
2535   if (GuaranteedTailCallOpt) {
2536     if (IsTailCallConvention(CalleeCC) && CCMatch)
2537       return true;
2538     return false;
2539   }
2540
2541   // Look for obvious safe cases to perform tail call optimization that do not
2542   // require ABI changes. This is what gcc calls sibcall.
2543
2544   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2545   // emit a special epilogue.
2546   if (RegInfo->needsStackRealignment(MF))
2547     return false;
2548
2549   // Also avoid sibcall optimization if either caller or callee uses struct
2550   // return semantics.
2551   if (isCalleeStructRet || isCallerStructRet)
2552     return false;
2553
2554   // An stdcall caller is expected to clean up its arguments; the callee
2555   // isn't going to do that.
2556   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2557     return false;
2558
2559   // Do not sibcall optimize vararg calls unless all arguments are passed via
2560   // registers.
2561   if (isVarArg && !Outs.empty()) {
2562
2563     // Optimizing for varargs on Win64 is unlikely to be safe without
2564     // additional testing.
2565     if (Subtarget->isTargetWin64())
2566       return false;
2567
2568     SmallVector<CCValAssign, 16> ArgLocs;
2569     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2570                    getTargetMachine(), ArgLocs, *DAG.getContext());
2571
2572     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2574       if (!ArgLocs[i].isRegLoc())
2575         return false;
2576   }
2577
2578   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2579   // Therefore if it's not used by the call it is not safe to optimize this into
2580   // a sibcall.
2581   bool Unused = false;
2582   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2583     if (!Ins[i].Used) {
2584       Unused = true;
2585       break;
2586     }
2587   }
2588   if (Unused) {
2589     SmallVector<CCValAssign, 16> RVLocs;
2590     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2591                    getTargetMachine(), RVLocs, *DAG.getContext());
2592     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2593     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2594       CCValAssign &VA = RVLocs[i];
2595       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2596         return false;
2597     }
2598   }
2599
2600   // If the calling conventions do not match, then we'd better make sure the
2601   // results are returned in the same way as what the caller expects.
2602   if (!CCMatch) {
2603     SmallVector<CCValAssign, 16> RVLocs1;
2604     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2605                     getTargetMachine(), RVLocs1, *DAG.getContext());
2606     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2607
2608     SmallVector<CCValAssign, 16> RVLocs2;
2609     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2610                     getTargetMachine(), RVLocs2, *DAG.getContext());
2611     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2612
2613     if (RVLocs1.size() != RVLocs2.size())
2614       return false;
2615     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2616       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2617         return false;
2618       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2619         return false;
2620       if (RVLocs1[i].isRegLoc()) {
2621         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2622           return false;
2623       } else {
2624         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2625           return false;
2626       }
2627     }
2628   }
2629
2630   // If the callee takes no arguments then go on to check the results of the
2631   // call.
2632   if (!Outs.empty()) {
2633     // Check if stack adjustment is needed. For now, do not do this if any
2634     // argument is passed on the stack.
2635     SmallVector<CCValAssign, 16> ArgLocs;
2636     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2637                    getTargetMachine(), ArgLocs, *DAG.getContext());
2638
2639     // Allocate shadow area for Win64
2640     if (Subtarget->isTargetWin64()) {
2641       CCInfo.AllocateStack(32, 8);
2642     }
2643
2644     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2645     if (CCInfo.getNextStackOffset()) {
2646       MachineFunction &MF = DAG.getMachineFunction();
2647       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2648         return false;
2649
2650       // Check if the arguments are already laid out in the right way as
2651       // the caller's fixed stack objects.
2652       MachineFrameInfo *MFI = MF.getFrameInfo();
2653       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2654       const X86InstrInfo *TII =
2655         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2656       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2657         CCValAssign &VA = ArgLocs[i];
2658         SDValue Arg = OutVals[i];
2659         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2660         if (VA.getLocInfo() == CCValAssign::Indirect)
2661           return false;
2662         if (!VA.isRegLoc()) {
2663           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2664                                    MFI, MRI, TII))
2665             return false;
2666         }
2667       }
2668     }
2669
2670     // If the tailcall address may be in a register, then make sure it's
2671     // possible to register allocate for it. In 32-bit, the call address can
2672     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2673     // callee-saved registers are restored. These happen to be the same
2674     // registers used to pass 'inreg' arguments so watch out for those.
2675     if (!Subtarget->is64Bit() &&
2676         !isa<GlobalAddressSDNode>(Callee) &&
2677         !isa<ExternalSymbolSDNode>(Callee)) {
2678       unsigned NumInRegs = 0;
2679       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2680         CCValAssign &VA = ArgLocs[i];
2681         if (!VA.isRegLoc())
2682           continue;
2683         unsigned Reg = VA.getLocReg();
2684         switch (Reg) {
2685         default: break;
2686         case X86::EAX: case X86::EDX: case X86::ECX:
2687           if (++NumInRegs == 3)
2688             return false;
2689           break;
2690         }
2691       }
2692     }
2693   }
2694
2695   return true;
2696 }
2697
2698 FastISel *
2699 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2700   return X86::createFastISel(funcInfo);
2701 }
2702
2703
2704 //===----------------------------------------------------------------------===//
2705 //                           Other Lowering Hooks
2706 //===----------------------------------------------------------------------===//
2707
2708 static bool MayFoldLoad(SDValue Op) {
2709   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2710 }
2711
2712 static bool MayFoldIntoStore(SDValue Op) {
2713   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2714 }
2715
2716 static bool isTargetShuffle(unsigned Opcode) {
2717   switch(Opcode) {
2718   default: return false;
2719   case X86ISD::PSHUFD:
2720   case X86ISD::PSHUFHW:
2721   case X86ISD::PSHUFLW:
2722   case X86ISD::SHUFPD:
2723   case X86ISD::PALIGN:
2724   case X86ISD::SHUFPS:
2725   case X86ISD::MOVLHPS:
2726   case X86ISD::MOVLHPD:
2727   case X86ISD::MOVHLPS:
2728   case X86ISD::MOVLPS:
2729   case X86ISD::MOVLPD:
2730   case X86ISD::MOVSHDUP:
2731   case X86ISD::MOVSLDUP:
2732   case X86ISD::MOVDDUP:
2733   case X86ISD::MOVSS:
2734   case X86ISD::MOVSD:
2735   case X86ISD::UNPCKLPS:
2736   case X86ISD::UNPCKLPD:
2737   case X86ISD::VUNPCKLPS:
2738   case X86ISD::VUNPCKLPD:
2739   case X86ISD::VUNPCKLPSY:
2740   case X86ISD::VUNPCKLPDY:
2741   case X86ISD::PUNPCKLWD:
2742   case X86ISD::PUNPCKLBW:
2743   case X86ISD::PUNPCKLDQ:
2744   case X86ISD::PUNPCKLQDQ:
2745   case X86ISD::UNPCKHPS:
2746   case X86ISD::UNPCKHPD:
2747   case X86ISD::PUNPCKHWD:
2748   case X86ISD::PUNPCKHBW:
2749   case X86ISD::PUNPCKHDQ:
2750   case X86ISD::PUNPCKHQDQ:
2751   case X86ISD::VPERMIL:
2752     return true;
2753   }
2754   return false;
2755 }
2756
2757 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2758                                                SDValue V1, SelectionDAG &DAG) {
2759   switch(Opc) {
2760   default: llvm_unreachable("Unknown x86 shuffle node");
2761   case X86ISD::MOVSHDUP:
2762   case X86ISD::MOVSLDUP:
2763   case X86ISD::MOVDDUP:
2764     return DAG.getNode(Opc, dl, VT, V1);
2765   }
2766
2767   return SDValue();
2768 }
2769
2770 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2771                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2772   switch(Opc) {
2773   default: llvm_unreachable("Unknown x86 shuffle node");
2774   case X86ISD::PSHUFD:
2775   case X86ISD::PSHUFHW:
2776   case X86ISD::PSHUFLW:
2777   case X86ISD::VPERMIL:
2778     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2779   }
2780
2781   return SDValue();
2782 }
2783
2784 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2785                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2786   switch(Opc) {
2787   default: llvm_unreachable("Unknown x86 shuffle node");
2788   case X86ISD::PALIGN:
2789   case X86ISD::SHUFPD:
2790   case X86ISD::SHUFPS:
2791     return DAG.getNode(Opc, dl, VT, V1, V2,
2792                        DAG.getConstant(TargetMask, MVT::i8));
2793   }
2794   return SDValue();
2795 }
2796
2797 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2798                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2799   switch(Opc) {
2800   default: llvm_unreachable("Unknown x86 shuffle node");
2801   case X86ISD::MOVLHPS:
2802   case X86ISD::MOVLHPD:
2803   case X86ISD::MOVHLPS:
2804   case X86ISD::MOVLPS:
2805   case X86ISD::MOVLPD:
2806   case X86ISD::MOVSS:
2807   case X86ISD::MOVSD:
2808   case X86ISD::UNPCKLPS:
2809   case X86ISD::UNPCKLPD:
2810   case X86ISD::VUNPCKLPS:
2811   case X86ISD::VUNPCKLPD:
2812   case X86ISD::VUNPCKLPSY:
2813   case X86ISD::VUNPCKLPDY:
2814   case X86ISD::PUNPCKLWD:
2815   case X86ISD::PUNPCKLBW:
2816   case X86ISD::PUNPCKLDQ:
2817   case X86ISD::PUNPCKLQDQ:
2818   case X86ISD::UNPCKHPS:
2819   case X86ISD::UNPCKHPD:
2820   case X86ISD::PUNPCKHWD:
2821   case X86ISD::PUNPCKHBW:
2822   case X86ISD::PUNPCKHDQ:
2823   case X86ISD::PUNPCKHQDQ:
2824     return DAG.getNode(Opc, dl, VT, V1, V2);
2825   }
2826   return SDValue();
2827 }
2828
2829 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2830   MachineFunction &MF = DAG.getMachineFunction();
2831   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2832   int ReturnAddrIndex = FuncInfo->getRAIndex();
2833
2834   if (ReturnAddrIndex == 0) {
2835     // Set up a frame object for the return address.
2836     uint64_t SlotSize = TD->getPointerSize();
2837     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2838                                                            false);
2839     FuncInfo->setRAIndex(ReturnAddrIndex);
2840   }
2841
2842   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2843 }
2844
2845
2846 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2847                                        bool hasSymbolicDisplacement) {
2848   // Offset should fit into 32 bit immediate field.
2849   if (!isInt<32>(Offset))
2850     return false;
2851
2852   // If we don't have a symbolic displacement - we don't have any extra
2853   // restrictions.
2854   if (!hasSymbolicDisplacement)
2855     return true;
2856
2857   // FIXME: Some tweaks might be needed for medium code model.
2858   if (M != CodeModel::Small && M != CodeModel::Kernel)
2859     return false;
2860
2861   // For small code model we assume that latest object is 16MB before end of 31
2862   // bits boundary. We may also accept pretty large negative constants knowing
2863   // that all objects are in the positive half of address space.
2864   if (M == CodeModel::Small && Offset < 16*1024*1024)
2865     return true;
2866
2867   // For kernel code model we know that all object resist in the negative half
2868   // of 32bits address space. We may not accept negative offsets, since they may
2869   // be just off and we may accept pretty large positive ones.
2870   if (M == CodeModel::Kernel && Offset > 0)
2871     return true;
2872
2873   return false;
2874 }
2875
2876 /// isCalleePop - Determines whether the callee is required to pop its
2877 /// own arguments. Callee pop is necessary to support tail calls.
2878 bool X86::isCalleePop(CallingConv::ID CallingConv,
2879                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2880   if (IsVarArg)
2881     return false;
2882
2883   switch (CallingConv) {
2884   default:
2885     return false;
2886   case CallingConv::X86_StdCall:
2887     return !is64Bit;
2888   case CallingConv::X86_FastCall:
2889     return !is64Bit;
2890   case CallingConv::X86_ThisCall:
2891     return !is64Bit;
2892   case CallingConv::Fast:
2893     return TailCallOpt;
2894   case CallingConv::GHC:
2895     return TailCallOpt;
2896   }
2897 }
2898
2899 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2900 /// specific condition code, returning the condition code and the LHS/RHS of the
2901 /// comparison to make.
2902 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2903                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2904   if (!isFP) {
2905     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2906       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2907         // X > -1   -> X == 0, jump !sign.
2908         RHS = DAG.getConstant(0, RHS.getValueType());
2909         return X86::COND_NS;
2910       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2911         // X < 0   -> X == 0, jump on sign.
2912         return X86::COND_S;
2913       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2914         // X < 1   -> X <= 0
2915         RHS = DAG.getConstant(0, RHS.getValueType());
2916         return X86::COND_LE;
2917       }
2918     }
2919
2920     switch (SetCCOpcode) {
2921     default: llvm_unreachable("Invalid integer condition!");
2922     case ISD::SETEQ:  return X86::COND_E;
2923     case ISD::SETGT:  return X86::COND_G;
2924     case ISD::SETGE:  return X86::COND_GE;
2925     case ISD::SETLT:  return X86::COND_L;
2926     case ISD::SETLE:  return X86::COND_LE;
2927     case ISD::SETNE:  return X86::COND_NE;
2928     case ISD::SETULT: return X86::COND_B;
2929     case ISD::SETUGT: return X86::COND_A;
2930     case ISD::SETULE: return X86::COND_BE;
2931     case ISD::SETUGE: return X86::COND_AE;
2932     }
2933   }
2934
2935   // First determine if it is required or is profitable to flip the operands.
2936
2937   // If LHS is a foldable load, but RHS is not, flip the condition.
2938   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2939       !ISD::isNON_EXTLoad(RHS.getNode())) {
2940     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2941     std::swap(LHS, RHS);
2942   }
2943
2944   switch (SetCCOpcode) {
2945   default: break;
2946   case ISD::SETOLT:
2947   case ISD::SETOLE:
2948   case ISD::SETUGT:
2949   case ISD::SETUGE:
2950     std::swap(LHS, RHS);
2951     break;
2952   }
2953
2954   // On a floating point condition, the flags are set as follows:
2955   // ZF  PF  CF   op
2956   //  0 | 0 | 0 | X > Y
2957   //  0 | 0 | 1 | X < Y
2958   //  1 | 0 | 0 | X == Y
2959   //  1 | 1 | 1 | unordered
2960   switch (SetCCOpcode) {
2961   default: llvm_unreachable("Condcode should be pre-legalized away");
2962   case ISD::SETUEQ:
2963   case ISD::SETEQ:   return X86::COND_E;
2964   case ISD::SETOLT:              // flipped
2965   case ISD::SETOGT:
2966   case ISD::SETGT:   return X86::COND_A;
2967   case ISD::SETOLE:              // flipped
2968   case ISD::SETOGE:
2969   case ISD::SETGE:   return X86::COND_AE;
2970   case ISD::SETUGT:              // flipped
2971   case ISD::SETULT:
2972   case ISD::SETLT:   return X86::COND_B;
2973   case ISD::SETUGE:              // flipped
2974   case ISD::SETULE:
2975   case ISD::SETLE:   return X86::COND_BE;
2976   case ISD::SETONE:
2977   case ISD::SETNE:   return X86::COND_NE;
2978   case ISD::SETUO:   return X86::COND_P;
2979   case ISD::SETO:    return X86::COND_NP;
2980   case ISD::SETOEQ:
2981   case ISD::SETUNE:  return X86::COND_INVALID;
2982   }
2983 }
2984
2985 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2986 /// code. Current x86 isa includes the following FP cmov instructions:
2987 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2988 static bool hasFPCMov(unsigned X86CC) {
2989   switch (X86CC) {
2990   default:
2991     return false;
2992   case X86::COND_B:
2993   case X86::COND_BE:
2994   case X86::COND_E:
2995   case X86::COND_P:
2996   case X86::COND_A:
2997   case X86::COND_AE:
2998   case X86::COND_NE:
2999   case X86::COND_NP:
3000     return true;
3001   }
3002 }
3003
3004 /// isFPImmLegal - Returns true if the target can instruction select the
3005 /// specified FP immediate natively. If false, the legalizer will
3006 /// materialize the FP immediate as a load from a constant pool.
3007 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3008   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3009     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3010       return true;
3011   }
3012   return false;
3013 }
3014
3015 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3016 /// the specified range (L, H].
3017 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3018   return (Val < 0) || (Val >= Low && Val < Hi);
3019 }
3020
3021 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3022 /// specified value.
3023 static bool isUndefOrEqual(int Val, int CmpVal) {
3024   if (Val < 0 || Val == CmpVal)
3025     return true;
3026   return false;
3027 }
3028
3029 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3030 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3031 /// the second operand.
3032 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3033   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3034     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3035   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3036     return (Mask[0] < 2 && Mask[1] < 2);
3037   return false;
3038 }
3039
3040 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3041   SmallVector<int, 8> M;
3042   N->getMask(M);
3043   return ::isPSHUFDMask(M, N->getValueType(0));
3044 }
3045
3046 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3047 /// is suitable for input to PSHUFHW.
3048 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3049   if (VT != MVT::v8i16)
3050     return false;
3051
3052   // Lower quadword copied in order or undef.
3053   for (int i = 0; i != 4; ++i)
3054     if (Mask[i] >= 0 && Mask[i] != i)
3055       return false;
3056
3057   // Upper quadword shuffled.
3058   for (int i = 4; i != 8; ++i)
3059     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3060       return false;
3061
3062   return true;
3063 }
3064
3065 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3066   SmallVector<int, 8> M;
3067   N->getMask(M);
3068   return ::isPSHUFHWMask(M, N->getValueType(0));
3069 }
3070
3071 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3072 /// is suitable for input to PSHUFLW.
3073 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3074   if (VT != MVT::v8i16)
3075     return false;
3076
3077   // Upper quadword copied in order.
3078   for (int i = 4; i != 8; ++i)
3079     if (Mask[i] >= 0 && Mask[i] != i)
3080       return false;
3081
3082   // Lower quadword shuffled.
3083   for (int i = 0; i != 4; ++i)
3084     if (Mask[i] >= 4)
3085       return false;
3086
3087   return true;
3088 }
3089
3090 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3091   SmallVector<int, 8> M;
3092   N->getMask(M);
3093   return ::isPSHUFLWMask(M, N->getValueType(0));
3094 }
3095
3096 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3097 /// is suitable for input to PALIGNR.
3098 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3099                           bool hasSSSE3) {
3100   int i, e = VT.getVectorNumElements();
3101
3102   // Do not handle v2i64 / v2f64 shuffles with palignr.
3103   if (e < 4 || !hasSSSE3)
3104     return false;
3105
3106   for (i = 0; i != e; ++i)
3107     if (Mask[i] >= 0)
3108       break;
3109
3110   // All undef, not a palignr.
3111   if (i == e)
3112     return false;
3113
3114   // Determine if it's ok to perform a palignr with only the LHS, since we
3115   // don't have access to the actual shuffle elements to see if RHS is undef.
3116   bool Unary = Mask[i] < (int)e;
3117   bool NeedsUnary = false;
3118
3119   int s = Mask[i] - i;
3120
3121   // Check the rest of the elements to see if they are consecutive.
3122   for (++i; i != e; ++i) {
3123     int m = Mask[i];
3124     if (m < 0)
3125       continue;
3126
3127     Unary = Unary && (m < (int)e);
3128     NeedsUnary = NeedsUnary || (m < s);
3129
3130     if (NeedsUnary && !Unary)
3131       return false;
3132     if (Unary && m != ((s+i) & (e-1)))
3133       return false;
3134     if (!Unary && m != (s+i))
3135       return false;
3136   }
3137   return true;
3138 }
3139
3140 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3141   SmallVector<int, 8> M;
3142   N->getMask(M);
3143   return ::isPALIGNRMask(M, N->getValueType(0), true);
3144 }
3145
3146 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3147 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3148 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3149   int NumElems = VT.getVectorNumElements();
3150   if (NumElems != 2 && NumElems != 4)
3151     return false;
3152
3153   int Half = NumElems / 2;
3154   for (int i = 0; i < Half; ++i)
3155     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3156       return false;
3157   for (int i = Half; i < NumElems; ++i)
3158     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3159       return false;
3160
3161   return true;
3162 }
3163
3164 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3165   SmallVector<int, 8> M;
3166   N->getMask(M);
3167   return ::isSHUFPMask(M, N->getValueType(0));
3168 }
3169
3170 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3171 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3172 /// half elements to come from vector 1 (which would equal the dest.) and
3173 /// the upper half to come from vector 2.
3174 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3175   int NumElems = VT.getVectorNumElements();
3176
3177   if (NumElems != 2 && NumElems != 4)
3178     return false;
3179
3180   int Half = NumElems / 2;
3181   for (int i = 0; i < Half; ++i)
3182     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3183       return false;
3184   for (int i = Half; i < NumElems; ++i)
3185     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3186       return false;
3187   return true;
3188 }
3189
3190 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3191   SmallVector<int, 8> M;
3192   N->getMask(M);
3193   return isCommutedSHUFPMask(M, N->getValueType(0));
3194 }
3195
3196 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3197 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3198 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3199   if (N->getValueType(0).getVectorNumElements() != 4)
3200     return false;
3201
3202   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3203   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3204          isUndefOrEqual(N->getMaskElt(1), 7) &&
3205          isUndefOrEqual(N->getMaskElt(2), 2) &&
3206          isUndefOrEqual(N->getMaskElt(3), 3);
3207 }
3208
3209 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3210 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3211 /// <2, 3, 2, 3>
3212 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3213   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3214
3215   if (NumElems != 4)
3216     return false;
3217
3218   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3219   isUndefOrEqual(N->getMaskElt(1), 3) &&
3220   isUndefOrEqual(N->getMaskElt(2), 2) &&
3221   isUndefOrEqual(N->getMaskElt(3), 3);
3222 }
3223
3224 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3225 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3226 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3227   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3228
3229   if (NumElems != 2 && NumElems != 4)
3230     return false;
3231
3232   for (unsigned i = 0; i < NumElems/2; ++i)
3233     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3234       return false;
3235
3236   for (unsigned i = NumElems/2; i < NumElems; ++i)
3237     if (!isUndefOrEqual(N->getMaskElt(i), i))
3238       return false;
3239
3240   return true;
3241 }
3242
3243 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3244 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3245 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3246   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3247
3248   if ((NumElems != 2 && NumElems != 4)
3249       || N->getValueType(0).getSizeInBits() > 128)
3250     return false;
3251
3252   for (unsigned i = 0; i < NumElems/2; ++i)
3253     if (!isUndefOrEqual(N->getMaskElt(i), i))
3254       return false;
3255
3256   for (unsigned i = 0; i < NumElems/2; ++i)
3257     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3258       return false;
3259
3260   return true;
3261 }
3262
3263 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3264 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3265 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3266                          bool V2IsSplat = false) {
3267   int NumElts = VT.getVectorNumElements();
3268   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3269     return false;
3270
3271   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3272   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3273   // sections.
3274   unsigned NumSections = VT.getSizeInBits() / 128;
3275   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3276   unsigned NumSectionElts = NumElts / NumSections;
3277
3278   unsigned Start = 0;
3279   unsigned End = NumSectionElts;
3280   for (unsigned s = 0; s < NumSections; ++s) {
3281     for (unsigned i = Start, j = s * NumSectionElts;
3282          i != End;
3283          i += 2, ++j) {
3284       int BitI  = Mask[i];
3285       int BitI1 = Mask[i+1];
3286       if (!isUndefOrEqual(BitI, j))
3287         return false;
3288       if (V2IsSplat) {
3289         if (!isUndefOrEqual(BitI1, NumElts))
3290           return false;
3291       } else {
3292         if (!isUndefOrEqual(BitI1, j + NumElts))
3293           return false;
3294       }
3295     }
3296     // Process the next 128 bits.
3297     Start += NumSectionElts;
3298     End += NumSectionElts;
3299   }
3300
3301   return true;
3302 }
3303
3304 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3305   SmallVector<int, 8> M;
3306   N->getMask(M);
3307   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3308 }
3309
3310 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3311 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3312 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3313                          bool V2IsSplat = false) {
3314   int NumElts = VT.getVectorNumElements();
3315   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3316     return false;
3317
3318   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3319     int BitI  = Mask[i];
3320     int BitI1 = Mask[i+1];
3321     if (!isUndefOrEqual(BitI, j + NumElts/2))
3322       return false;
3323     if (V2IsSplat) {
3324       if (isUndefOrEqual(BitI1, NumElts))
3325         return false;
3326     } else {
3327       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3328         return false;
3329     }
3330   }
3331   return true;
3332 }
3333
3334 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3335   SmallVector<int, 8> M;
3336   N->getMask(M);
3337   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3338 }
3339
3340 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3341 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3342 /// <0, 0, 1, 1>
3343 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3344   int NumElems = VT.getVectorNumElements();
3345   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3346     return false;
3347
3348   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3349   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3350   // sections.
3351   unsigned NumSections = VT.getSizeInBits() / 128;
3352   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3353   unsigned NumSectionElts = NumElems / NumSections;
3354
3355   for (unsigned s = 0; s < NumSections; ++s) {
3356     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3357          i != NumSectionElts * (s + 1);
3358          i += 2, ++j) {
3359       int BitI  = Mask[i];
3360       int BitI1 = Mask[i+1];
3361
3362       if (!isUndefOrEqual(BitI, j))
3363         return false;
3364       if (!isUndefOrEqual(BitI1, j))
3365         return false;
3366     }
3367   }
3368
3369   return true;
3370 }
3371
3372 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3373   SmallVector<int, 8> M;
3374   N->getMask(M);
3375   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3376 }
3377
3378 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3379 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3380 /// <2, 2, 3, 3>
3381 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3382   int NumElems = VT.getVectorNumElements();
3383   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3384     return false;
3385
3386   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3387     int BitI  = Mask[i];
3388     int BitI1 = Mask[i+1];
3389     if (!isUndefOrEqual(BitI, j))
3390       return false;
3391     if (!isUndefOrEqual(BitI1, j))
3392       return false;
3393   }
3394   return true;
3395 }
3396
3397 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3398   SmallVector<int, 8> M;
3399   N->getMask(M);
3400   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3401 }
3402
3403 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3404 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3405 /// MOVSD, and MOVD, i.e. setting the lowest element.
3406 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3407   if (VT.getVectorElementType().getSizeInBits() < 32)
3408     return false;
3409
3410   int NumElts = VT.getVectorNumElements();
3411
3412   if (!isUndefOrEqual(Mask[0], NumElts))
3413     return false;
3414
3415   for (int i = 1; i < NumElts; ++i)
3416     if (!isUndefOrEqual(Mask[i], i))
3417       return false;
3418
3419   return true;
3420 }
3421
3422 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3423   SmallVector<int, 8> M;
3424   N->getMask(M);
3425   return ::isMOVLMask(M, N->getValueType(0));
3426 }
3427
3428 /// isVPERMILMask - Return true if the specified VECTOR_SHUFFLE operand
3429 /// specifies a shuffle of elements that is suitable for input to VPERMIL*.
3430 static bool isVPERMILMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3431   unsigned NumElts = VT.getVectorNumElements();
3432   unsigned NumLanes = VT.getSizeInBits()/128;
3433
3434   // Match any permutation of 128-bit vector with 32/64-bit types
3435   if (NumLanes == 1) {
3436     if (NumElts == 4 || NumElts == 2)
3437       return true;
3438     return false;
3439   }
3440
3441   // Only match 256-bit with 32/64-bit types
3442   if (NumElts != 8 && NumElts != 4)
3443     return false;
3444
3445   // The mask on the high lane should be the same as the low. Actually,
3446   // they can differ if any of the corresponding index in a lane is undef.
3447   int LaneSize = NumElts/NumLanes;
3448   for (int i = 0; i < LaneSize; ++i) {
3449     int HighElt = i+LaneSize;
3450     if (Mask[i] < 0 || Mask[HighElt] < 0)
3451       continue;
3452
3453     if (Mask[HighElt]-Mask[i] != LaneSize)
3454       return false;
3455   }
3456
3457   return true;
3458 }
3459
3460 /// getShuffleVPERMILImmediateediate - Return the appropriate immediate to shuffle
3461 /// the specified VECTOR_MASK mask with VPERMIL* instructions.
3462 static unsigned getShuffleVPERMILImmediate(SDNode *N) {
3463   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3464   EVT VT = SVOp->getValueType(0);
3465
3466   int NumElts = VT.getVectorNumElements();
3467   int NumLanes = VT.getSizeInBits()/128;
3468
3469   unsigned Mask = 0;
3470   for (int i = 0; i < NumElts/NumLanes /* lane size */; ++i)
3471     Mask |= SVOp->getMaskElt(i) << (i*2);
3472
3473   return Mask;
3474 }
3475
3476 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3477 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3478 /// element of vector 2 and the other elements to come from vector 1 in order.
3479 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3480                                bool V2IsSplat = false, bool V2IsUndef = false) {
3481   int NumOps = VT.getVectorNumElements();
3482   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3483     return false;
3484
3485   if (!isUndefOrEqual(Mask[0], 0))
3486     return false;
3487
3488   for (int i = 1; i < NumOps; ++i)
3489     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3490           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3491           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3492       return false;
3493
3494   return true;
3495 }
3496
3497 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3498                            bool V2IsUndef = false) {
3499   SmallVector<int, 8> M;
3500   N->getMask(M);
3501   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3502 }
3503
3504 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3505 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3506 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3507   if (N->getValueType(0).getVectorNumElements() != 4)
3508     return false;
3509
3510   // Expect 1, 1, 3, 3
3511   for (unsigned i = 0; i < 2; ++i) {
3512     int Elt = N->getMaskElt(i);
3513     if (Elt >= 0 && Elt != 1)
3514       return false;
3515   }
3516
3517   bool HasHi = false;
3518   for (unsigned i = 2; i < 4; ++i) {
3519     int Elt = N->getMaskElt(i);
3520     if (Elt >= 0 && Elt != 3)
3521       return false;
3522     if (Elt == 3)
3523       HasHi = true;
3524   }
3525   // Don't use movshdup if it can be done with a shufps.
3526   // FIXME: verify that matching u, u, 3, 3 is what we want.
3527   return HasHi;
3528 }
3529
3530 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3531 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3532 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3533   if (N->getValueType(0).getVectorNumElements() != 4)
3534     return false;
3535
3536   // Expect 0, 0, 2, 2
3537   for (unsigned i = 0; i < 2; ++i)
3538     if (N->getMaskElt(i) > 0)
3539       return false;
3540
3541   bool HasHi = false;
3542   for (unsigned i = 2; i < 4; ++i) {
3543     int Elt = N->getMaskElt(i);
3544     if (Elt >= 0 && Elt != 2)
3545       return false;
3546     if (Elt == 2)
3547       HasHi = true;
3548   }
3549   // Don't use movsldup if it can be done with a shufps.
3550   return HasHi;
3551 }
3552
3553 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3554 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3555 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3556   int e = N->getValueType(0).getVectorNumElements() / 2;
3557
3558   for (int i = 0; i < e; ++i)
3559     if (!isUndefOrEqual(N->getMaskElt(i), i))
3560       return false;
3561   for (int i = 0; i < e; ++i)
3562     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3563       return false;
3564   return true;
3565 }
3566
3567 /// isVEXTRACTF128Index - Return true if the specified
3568 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3569 /// suitable for input to VEXTRACTF128.
3570 bool X86::isVEXTRACTF128Index(SDNode *N) {
3571   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3572     return false;
3573
3574   // The index should be aligned on a 128-bit boundary.
3575   uint64_t Index =
3576     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3577
3578   unsigned VL = N->getValueType(0).getVectorNumElements();
3579   unsigned VBits = N->getValueType(0).getSizeInBits();
3580   unsigned ElSize = VBits / VL;
3581   bool Result = (Index * ElSize) % 128 == 0;
3582
3583   return Result;
3584 }
3585
3586 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3587 /// operand specifies a subvector insert that is suitable for input to
3588 /// VINSERTF128.
3589 bool X86::isVINSERTF128Index(SDNode *N) {
3590   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3591     return false;
3592
3593   // The index should be aligned on a 128-bit boundary.
3594   uint64_t Index =
3595     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3596
3597   unsigned VL = N->getValueType(0).getVectorNumElements();
3598   unsigned VBits = N->getValueType(0).getSizeInBits();
3599   unsigned ElSize = VBits / VL;
3600   bool Result = (Index * ElSize) % 128 == 0;
3601
3602   return Result;
3603 }
3604
3605 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3606 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3607 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3608   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3609   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3610
3611   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3612   unsigned Mask = 0;
3613   for (int i = 0; i < NumOperands; ++i) {
3614     int Val = SVOp->getMaskElt(NumOperands-i-1);
3615     if (Val < 0) Val = 0;
3616     if (Val >= NumOperands) Val -= NumOperands;
3617     Mask |= Val;
3618     if (i != NumOperands - 1)
3619       Mask <<= Shift;
3620   }
3621   return Mask;
3622 }
3623
3624 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3625 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3626 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3627   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3628   unsigned Mask = 0;
3629   // 8 nodes, but we only care about the last 4.
3630   for (unsigned i = 7; i >= 4; --i) {
3631     int Val = SVOp->getMaskElt(i);
3632     if (Val >= 0)
3633       Mask |= (Val - 4);
3634     if (i != 4)
3635       Mask <<= 2;
3636   }
3637   return Mask;
3638 }
3639
3640 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3641 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3642 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3643   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3644   unsigned Mask = 0;
3645   // 8 nodes, but we only care about the first 4.
3646   for (int i = 3; i >= 0; --i) {
3647     int Val = SVOp->getMaskElt(i);
3648     if (Val >= 0)
3649       Mask |= Val;
3650     if (i != 0)
3651       Mask <<= 2;
3652   }
3653   return Mask;
3654 }
3655
3656 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3657 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3658 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3659   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3660   EVT VVT = N->getValueType(0);
3661   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3662   int Val = 0;
3663
3664   unsigned i, e;
3665   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3666     Val = SVOp->getMaskElt(i);
3667     if (Val >= 0)
3668       break;
3669   }
3670   return (Val - i) * EltSize;
3671 }
3672
3673 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3674 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3675 /// instructions.
3676 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3677   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3678     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3679
3680   uint64_t Index =
3681     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3682
3683   EVT VecVT = N->getOperand(0).getValueType();
3684   EVT ElVT = VecVT.getVectorElementType();
3685
3686   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3687   return Index / NumElemsPerChunk;
3688 }
3689
3690 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3691 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3692 /// instructions.
3693 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3694   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3695     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3696
3697   uint64_t Index =
3698     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3699
3700   EVT VecVT = N->getValueType(0);
3701   EVT ElVT = VecVT.getVectorElementType();
3702
3703   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3704   return Index / NumElemsPerChunk;
3705 }
3706
3707 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3708 /// constant +0.0.
3709 bool X86::isZeroNode(SDValue Elt) {
3710   return ((isa<ConstantSDNode>(Elt) &&
3711            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3712           (isa<ConstantFPSDNode>(Elt) &&
3713            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3714 }
3715
3716 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3717 /// their permute mask.
3718 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3719                                     SelectionDAG &DAG) {
3720   EVT VT = SVOp->getValueType(0);
3721   unsigned NumElems = VT.getVectorNumElements();
3722   SmallVector<int, 8> MaskVec;
3723
3724   for (unsigned i = 0; i != NumElems; ++i) {
3725     int idx = SVOp->getMaskElt(i);
3726     if (idx < 0)
3727       MaskVec.push_back(idx);
3728     else if (idx < (int)NumElems)
3729       MaskVec.push_back(idx + NumElems);
3730     else
3731       MaskVec.push_back(idx - NumElems);
3732   }
3733   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3734                               SVOp->getOperand(0), &MaskVec[0]);
3735 }
3736
3737 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3738 /// the two vector operands have swapped position.
3739 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3740   unsigned NumElems = VT.getVectorNumElements();
3741   for (unsigned i = 0; i != NumElems; ++i) {
3742     int idx = Mask[i];
3743     if (idx < 0)
3744       continue;
3745     else if (idx < (int)NumElems)
3746       Mask[i] = idx + NumElems;
3747     else
3748       Mask[i] = idx - NumElems;
3749   }
3750 }
3751
3752 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3753 /// match movhlps. The lower half elements should come from upper half of
3754 /// V1 (and in order), and the upper half elements should come from the upper
3755 /// half of V2 (and in order).
3756 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3757   if (Op->getValueType(0).getVectorNumElements() != 4)
3758     return false;
3759   for (unsigned i = 0, e = 2; i != e; ++i)
3760     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3761       return false;
3762   for (unsigned i = 2; i != 4; ++i)
3763     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3764       return false;
3765   return true;
3766 }
3767
3768 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3769 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3770 /// required.
3771 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3772   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3773     return false;
3774   N = N->getOperand(0).getNode();
3775   if (!ISD::isNON_EXTLoad(N))
3776     return false;
3777   if (LD)
3778     *LD = cast<LoadSDNode>(N);
3779   return true;
3780 }
3781
3782 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3783 /// match movlp{s|d}. The lower half elements should come from lower half of
3784 /// V1 (and in order), and the upper half elements should come from the upper
3785 /// half of V2 (and in order). And since V1 will become the source of the
3786 /// MOVLP, it must be either a vector load or a scalar load to vector.
3787 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3788                                ShuffleVectorSDNode *Op) {
3789   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3790     return false;
3791   // Is V2 is a vector load, don't do this transformation. We will try to use
3792   // load folding shufps op.
3793   if (ISD::isNON_EXTLoad(V2))
3794     return false;
3795
3796   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3797
3798   if (NumElems != 2 && NumElems != 4)
3799     return false;
3800   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3801     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3802       return false;
3803   for (unsigned i = NumElems/2; i != NumElems; ++i)
3804     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3805       return false;
3806   return true;
3807 }
3808
3809 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3810 /// all the same.
3811 static bool isSplatVector(SDNode *N) {
3812   if (N->getOpcode() != ISD::BUILD_VECTOR)
3813     return false;
3814
3815   SDValue SplatValue = N->getOperand(0);
3816   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3817     if (N->getOperand(i) != SplatValue)
3818       return false;
3819   return true;
3820 }
3821
3822 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3823 /// to an zero vector.
3824 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3825 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3826   SDValue V1 = N->getOperand(0);
3827   SDValue V2 = N->getOperand(1);
3828   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3829   for (unsigned i = 0; i != NumElems; ++i) {
3830     int Idx = N->getMaskElt(i);
3831     if (Idx >= (int)NumElems) {
3832       unsigned Opc = V2.getOpcode();
3833       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3834         continue;
3835       if (Opc != ISD::BUILD_VECTOR ||
3836           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3837         return false;
3838     } else if (Idx >= 0) {
3839       unsigned Opc = V1.getOpcode();
3840       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3841         continue;
3842       if (Opc != ISD::BUILD_VECTOR ||
3843           !X86::isZeroNode(V1.getOperand(Idx)))
3844         return false;
3845     }
3846   }
3847   return true;
3848 }
3849
3850 /// getZeroVector - Returns a vector of specified type with all zero elements.
3851 ///
3852 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3853                              DebugLoc dl) {
3854   assert(VT.isVector() && "Expected a vector type");
3855
3856   // Always build SSE zero vectors as <4 x i32> bitcasted
3857   // to their dest type. This ensures they get CSE'd.
3858   SDValue Vec;
3859   if (VT.getSizeInBits() == 128) {  // SSE
3860     if (HasSSE2) {  // SSE2
3861       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3862       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3863     } else { // SSE1
3864       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3865       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3866     }
3867   } else if (VT.getSizeInBits() == 256) { // AVX
3868     // 256-bit logic and arithmetic instructions in AVX are
3869     // all floating-point, no support for integer ops. Default
3870     // to emitting fp zeroed vectors then.
3871     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3872     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3873     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3874   }
3875   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3876 }
3877
3878 /// getOnesVector - Returns a vector of specified type with all bits set.
3879 /// Always build ones vectors as <4 x i32> or <8 x i32> bitcasted to
3880 /// their original type, ensuring they get CSE'd.
3881 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3882   assert(VT.isVector() && "Expected a vector type");
3883   assert((VT.is128BitVector() || VT.is256BitVector())
3884          && "Expected a 128-bit or 256-bit vector type");
3885
3886   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3887
3888   SDValue Vec;
3889   if (VT.is256BitVector()) {
3890     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3891     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
3892   } else
3893     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3894   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3895 }
3896
3897 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3898 /// that point to V2 points to its first element.
3899 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3900   EVT VT = SVOp->getValueType(0);
3901   unsigned NumElems = VT.getVectorNumElements();
3902
3903   bool Changed = false;
3904   SmallVector<int, 8> MaskVec;
3905   SVOp->getMask(MaskVec);
3906
3907   for (unsigned i = 0; i != NumElems; ++i) {
3908     if (MaskVec[i] > (int)NumElems) {
3909       MaskVec[i] = NumElems;
3910       Changed = true;
3911     }
3912   }
3913   if (Changed)
3914     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3915                                 SVOp->getOperand(1), &MaskVec[0]);
3916   return SDValue(SVOp, 0);
3917 }
3918
3919 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3920 /// operation of specified width.
3921 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3922                        SDValue V2) {
3923   unsigned NumElems = VT.getVectorNumElements();
3924   SmallVector<int, 8> Mask;
3925   Mask.push_back(NumElems);
3926   for (unsigned i = 1; i != NumElems; ++i)
3927     Mask.push_back(i);
3928   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3929 }
3930
3931 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3932 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3933                           SDValue V2) {
3934   unsigned NumElems = VT.getVectorNumElements();
3935   SmallVector<int, 8> Mask;
3936   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3937     Mask.push_back(i);
3938     Mask.push_back(i + NumElems);
3939   }
3940   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3941 }
3942
3943 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
3944 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3945                           SDValue V2) {
3946   unsigned NumElems = VT.getVectorNumElements();
3947   unsigned Half = NumElems/2;
3948   SmallVector<int, 8> Mask;
3949   for (unsigned i = 0; i != Half; ++i) {
3950     Mask.push_back(i + Half);
3951     Mask.push_back(i + NumElems + Half);
3952   }
3953   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3954 }
3955
3956 // PromoteSplatv8v16 - All i16 and i8 vector types can't be used directly by
3957 // a generic shuffle instruction because the target has no such instructions.
3958 // Generate shuffles which repeat i16 and i8 several times until they can be
3959 // represented by v4f32 and then be manipulated by target suported shuffles.
3960 static SDValue PromoteSplatv8v16(SDValue V, SelectionDAG &DAG, int &EltNo) {
3961   EVT VT = V.getValueType();
3962   int NumElems = VT.getVectorNumElements();
3963   DebugLoc dl = V.getDebugLoc();
3964
3965   while (NumElems > 4) {
3966     if (EltNo < NumElems/2) {
3967       V = getUnpackl(DAG, dl, VT, V, V);
3968     } else {
3969       V = getUnpackh(DAG, dl, VT, V, V);
3970       EltNo -= NumElems/2;
3971     }
3972     NumElems >>= 1;
3973   }
3974   return V;
3975 }
3976
3977 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
3978 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
3979   EVT VT = V.getValueType();
3980   DebugLoc dl = V.getDebugLoc();
3981   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
3982          && "Vector size not supported");
3983
3984   bool Is128 = VT.getSizeInBits() == 128;
3985   EVT NVT = Is128 ? MVT::v4f32 : MVT::v8f32;
3986   V = DAG.getNode(ISD::BITCAST, dl, NVT, V);
3987
3988   if (Is128) {
3989     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3990     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3991   } else {
3992     // The second half of indicies refer to the higher part, which is a
3993     // duplication of the lower one. This makes this shuffle a perfect match
3994     // for the VPERM instruction.
3995     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
3996                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
3997     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3998   }
3999
4000   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4001 }
4002
4003 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32 and
4004 /// v8i32, v16i16 or v32i8 to v8f32.
4005 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4006   EVT SrcVT = SV->getValueType(0);
4007   SDValue V1 = SV->getOperand(0);
4008   DebugLoc dl = SV->getDebugLoc();
4009
4010   int EltNo = SV->getSplatIndex();
4011   int NumElems = SrcVT.getVectorNumElements();
4012   unsigned Size = SrcVT.getSizeInBits();
4013
4014   // Extract the 128-bit part containing the splat element and update
4015   // the splat element index when it refers to the higher register.
4016   if (Size == 256) {
4017     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4018     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4019     if (Idx > 0)
4020       EltNo -= NumElems/2;
4021   }
4022
4023   // Make this 128-bit vector duplicate i8 and i16 elements
4024   if (NumElems > 4)
4025     V1 = PromoteSplatv8v16(V1, DAG, EltNo);
4026
4027   // Recreate the 256-bit vector and place the same 128-bit vector
4028   // into the low and high part. This is necessary because we want
4029   // to use VPERM to shuffle the v8f32 vector, and VPERM only shuffles
4030   // inside each separate v4f32 lane.
4031   if (Size == 256) {
4032     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4033                          DAG.getConstant(0, MVT::i32), DAG, dl);
4034     V1 = Insert128BitVector(InsV, V1,
4035                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4036   }
4037
4038   return getLegalSplat(DAG, V1, EltNo);
4039 }
4040
4041 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4042 /// vector of zero or undef vector.  This produces a shuffle where the low
4043 /// element of V2 is swizzled into the zero/undef vector, landing at element
4044 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4045 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4046                                              bool isZero, bool HasSSE2,
4047                                              SelectionDAG &DAG) {
4048   EVT VT = V2.getValueType();
4049   SDValue V1 = isZero
4050     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4051   unsigned NumElems = VT.getVectorNumElements();
4052   SmallVector<int, 16> MaskVec;
4053   for (unsigned i = 0; i != NumElems; ++i)
4054     // If this is the insertion idx, put the low elt of V2 here.
4055     MaskVec.push_back(i == Idx ? NumElems : i);
4056   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4057 }
4058
4059 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4060 /// element of the result of the vector shuffle.
4061 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4062                                    unsigned Depth) {
4063   if (Depth == 6)
4064     return SDValue();  // Limit search depth.
4065
4066   SDValue V = SDValue(N, 0);
4067   EVT VT = V.getValueType();
4068   unsigned Opcode = V.getOpcode();
4069
4070   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4071   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4072     Index = SV->getMaskElt(Index);
4073
4074     if (Index < 0)
4075       return DAG.getUNDEF(VT.getVectorElementType());
4076
4077     int NumElems = VT.getVectorNumElements();
4078     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4079     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4080   }
4081
4082   // Recurse into target specific vector shuffles to find scalars.
4083   if (isTargetShuffle(Opcode)) {
4084     int NumElems = VT.getVectorNumElements();
4085     SmallVector<unsigned, 16> ShuffleMask;
4086     SDValue ImmN;
4087
4088     switch(Opcode) {
4089     case X86ISD::SHUFPS:
4090     case X86ISD::SHUFPD:
4091       ImmN = N->getOperand(N->getNumOperands()-1);
4092       DecodeSHUFPSMask(NumElems,
4093                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4094                        ShuffleMask);
4095       break;
4096     case X86ISD::PUNPCKHBW:
4097     case X86ISD::PUNPCKHWD:
4098     case X86ISD::PUNPCKHDQ:
4099     case X86ISD::PUNPCKHQDQ:
4100       DecodePUNPCKHMask(NumElems, ShuffleMask);
4101       break;
4102     case X86ISD::UNPCKHPS:
4103     case X86ISD::UNPCKHPD:
4104       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4105       break;
4106     case X86ISD::PUNPCKLBW:
4107     case X86ISD::PUNPCKLWD:
4108     case X86ISD::PUNPCKLDQ:
4109     case X86ISD::PUNPCKLQDQ:
4110       DecodePUNPCKLMask(VT, ShuffleMask);
4111       break;
4112     case X86ISD::UNPCKLPS:
4113     case X86ISD::UNPCKLPD:
4114     case X86ISD::VUNPCKLPS:
4115     case X86ISD::VUNPCKLPD:
4116     case X86ISD::VUNPCKLPSY:
4117     case X86ISD::VUNPCKLPDY:
4118       DecodeUNPCKLPMask(VT, ShuffleMask);
4119       break;
4120     case X86ISD::MOVHLPS:
4121       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4122       break;
4123     case X86ISD::MOVLHPS:
4124       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4125       break;
4126     case X86ISD::PSHUFD:
4127       ImmN = N->getOperand(N->getNumOperands()-1);
4128       DecodePSHUFMask(NumElems,
4129                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4130                       ShuffleMask);
4131       break;
4132     case X86ISD::PSHUFHW:
4133       ImmN = N->getOperand(N->getNumOperands()-1);
4134       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4135                         ShuffleMask);
4136       break;
4137     case X86ISD::PSHUFLW:
4138       ImmN = N->getOperand(N->getNumOperands()-1);
4139       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4140                         ShuffleMask);
4141       break;
4142     case X86ISD::MOVSS:
4143     case X86ISD::MOVSD: {
4144       // The index 0 always comes from the first element of the second source,
4145       // this is why MOVSS and MOVSD are used in the first place. The other
4146       // elements come from the other positions of the first source vector.
4147       unsigned OpNum = (Index == 0) ? 1 : 0;
4148       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4149                                  Depth+1);
4150     }
4151     case X86ISD::VPERMIL:
4152       ImmN = N->getOperand(N->getNumOperands()-1);
4153       DecodeVPERMILMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4154                         ShuffleMask);
4155     default:
4156       assert("not implemented for target shuffle node");
4157       return SDValue();
4158     }
4159
4160     Index = ShuffleMask[Index];
4161     if (Index < 0)
4162       return DAG.getUNDEF(VT.getVectorElementType());
4163
4164     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4165     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4166                                Depth+1);
4167   }
4168
4169   // Actual nodes that may contain scalar elements
4170   if (Opcode == ISD::BITCAST) {
4171     V = V.getOperand(0);
4172     EVT SrcVT = V.getValueType();
4173     unsigned NumElems = VT.getVectorNumElements();
4174
4175     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4176       return SDValue();
4177   }
4178
4179   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4180     return (Index == 0) ? V.getOperand(0)
4181                           : DAG.getUNDEF(VT.getVectorElementType());
4182
4183   if (V.getOpcode() == ISD::BUILD_VECTOR)
4184     return V.getOperand(Index);
4185
4186   return SDValue();
4187 }
4188
4189 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4190 /// shuffle operation which come from a consecutively from a zero. The
4191 /// search can start in two different directions, from left or right.
4192 static
4193 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4194                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4195   int i = 0;
4196
4197   while (i < NumElems) {
4198     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4199     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4200     if (!(Elt.getNode() &&
4201          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4202       break;
4203     ++i;
4204   }
4205
4206   return i;
4207 }
4208
4209 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4210 /// MaskE correspond consecutively to elements from one of the vector operands,
4211 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4212 static
4213 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4214                               int OpIdx, int NumElems, unsigned &OpNum) {
4215   bool SeenV1 = false;
4216   bool SeenV2 = false;
4217
4218   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4219     int Idx = SVOp->getMaskElt(i);
4220     // Ignore undef indicies
4221     if (Idx < 0)
4222       continue;
4223
4224     if (Idx < NumElems)
4225       SeenV1 = true;
4226     else
4227       SeenV2 = true;
4228
4229     // Only accept consecutive elements from the same vector
4230     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4231       return false;
4232   }
4233
4234   OpNum = SeenV1 ? 0 : 1;
4235   return true;
4236 }
4237
4238 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4239 /// logical left shift of a vector.
4240 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4241                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4242   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4243   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4244               false /* check zeros from right */, DAG);
4245   unsigned OpSrc;
4246
4247   if (!NumZeros)
4248     return false;
4249
4250   // Considering the elements in the mask that are not consecutive zeros,
4251   // check if they consecutively come from only one of the source vectors.
4252   //
4253   //               V1 = {X, A, B, C}     0
4254   //                         \  \  \    /
4255   //   vector_shuffle V1, V2 <1, 2, 3, X>
4256   //
4257   if (!isShuffleMaskConsecutive(SVOp,
4258             0,                   // Mask Start Index
4259             NumElems-NumZeros-1, // Mask End Index
4260             NumZeros,            // Where to start looking in the src vector
4261             NumElems,            // Number of elements in vector
4262             OpSrc))              // Which source operand ?
4263     return false;
4264
4265   isLeft = false;
4266   ShAmt = NumZeros;
4267   ShVal = SVOp->getOperand(OpSrc);
4268   return true;
4269 }
4270
4271 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4272 /// logical left shift of a vector.
4273 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4274                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4275   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4276   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4277               true /* check zeros from left */, DAG);
4278   unsigned OpSrc;
4279
4280   if (!NumZeros)
4281     return false;
4282
4283   // Considering the elements in the mask that are not consecutive zeros,
4284   // check if they consecutively come from only one of the source vectors.
4285   //
4286   //                           0    { A, B, X, X } = V2
4287   //                          / \    /  /
4288   //   vector_shuffle V1, V2 <X, X, 4, 5>
4289   //
4290   if (!isShuffleMaskConsecutive(SVOp,
4291             NumZeros,     // Mask Start Index
4292             NumElems-1,   // Mask End Index
4293             0,            // Where to start looking in the src vector
4294             NumElems,     // Number of elements in vector
4295             OpSrc))       // Which source operand ?
4296     return false;
4297
4298   isLeft = true;
4299   ShAmt = NumZeros;
4300   ShVal = SVOp->getOperand(OpSrc);
4301   return true;
4302 }
4303
4304 /// isVectorShift - Returns true if the shuffle can be implemented as a
4305 /// logical left or right shift of a vector.
4306 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4307                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4308   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4309       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4310     return true;
4311
4312   return false;
4313 }
4314
4315 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4316 ///
4317 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4318                                        unsigned NumNonZero, unsigned NumZero,
4319                                        SelectionDAG &DAG,
4320                                        const TargetLowering &TLI) {
4321   if (NumNonZero > 8)
4322     return SDValue();
4323
4324   DebugLoc dl = Op.getDebugLoc();
4325   SDValue V(0, 0);
4326   bool First = true;
4327   for (unsigned i = 0; i < 16; ++i) {
4328     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4329     if (ThisIsNonZero && First) {
4330       if (NumZero)
4331         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4332       else
4333         V = DAG.getUNDEF(MVT::v8i16);
4334       First = false;
4335     }
4336
4337     if ((i & 1) != 0) {
4338       SDValue ThisElt(0, 0), LastElt(0, 0);
4339       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4340       if (LastIsNonZero) {
4341         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4342                               MVT::i16, Op.getOperand(i-1));
4343       }
4344       if (ThisIsNonZero) {
4345         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4346         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4347                               ThisElt, DAG.getConstant(8, MVT::i8));
4348         if (LastIsNonZero)
4349           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4350       } else
4351         ThisElt = LastElt;
4352
4353       if (ThisElt.getNode())
4354         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4355                         DAG.getIntPtrConstant(i/2));
4356     }
4357   }
4358
4359   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4360 }
4361
4362 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4363 ///
4364 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4365                                      unsigned NumNonZero, unsigned NumZero,
4366                                      SelectionDAG &DAG,
4367                                      const TargetLowering &TLI) {
4368   if (NumNonZero > 4)
4369     return SDValue();
4370
4371   DebugLoc dl = Op.getDebugLoc();
4372   SDValue V(0, 0);
4373   bool First = true;
4374   for (unsigned i = 0; i < 8; ++i) {
4375     bool isNonZero = (NonZeros & (1 << i)) != 0;
4376     if (isNonZero) {
4377       if (First) {
4378         if (NumZero)
4379           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4380         else
4381           V = DAG.getUNDEF(MVT::v8i16);
4382         First = false;
4383       }
4384       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4385                       MVT::v8i16, V, Op.getOperand(i),
4386                       DAG.getIntPtrConstant(i));
4387     }
4388   }
4389
4390   return V;
4391 }
4392
4393 /// getVShift - Return a vector logical shift node.
4394 ///
4395 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4396                          unsigned NumBits, SelectionDAG &DAG,
4397                          const TargetLowering &TLI, DebugLoc dl) {
4398   EVT ShVT = MVT::v2i64;
4399   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4400   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4401   return DAG.getNode(ISD::BITCAST, dl, VT,
4402                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4403                              DAG.getConstant(NumBits,
4404                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4405 }
4406
4407 SDValue
4408 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4409                                           SelectionDAG &DAG) const {
4410
4411   // Check if the scalar load can be widened into a vector load. And if
4412   // the address is "base + cst" see if the cst can be "absorbed" into
4413   // the shuffle mask.
4414   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4415     SDValue Ptr = LD->getBasePtr();
4416     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4417       return SDValue();
4418     EVT PVT = LD->getValueType(0);
4419     if (PVT != MVT::i32 && PVT != MVT::f32)
4420       return SDValue();
4421
4422     int FI = -1;
4423     int64_t Offset = 0;
4424     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4425       FI = FINode->getIndex();
4426       Offset = 0;
4427     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4428                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4429       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4430       Offset = Ptr.getConstantOperandVal(1);
4431       Ptr = Ptr.getOperand(0);
4432     } else {
4433       return SDValue();
4434     }
4435
4436     SDValue Chain = LD->getChain();
4437     // Make sure the stack object alignment is at least 16.
4438     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4439     if (DAG.InferPtrAlignment(Ptr) < 16) {
4440       if (MFI->isFixedObjectIndex(FI)) {
4441         // Can't change the alignment. FIXME: It's possible to compute
4442         // the exact stack offset and reference FI + adjust offset instead.
4443         // If someone *really* cares about this. That's the way to implement it.
4444         return SDValue();
4445       } else {
4446         MFI->setObjectAlignment(FI, 16);
4447       }
4448     }
4449
4450     // (Offset % 16) must be multiple of 4. Then address is then
4451     // Ptr + (Offset & ~15).
4452     if (Offset < 0)
4453       return SDValue();
4454     if ((Offset % 16) & 3)
4455       return SDValue();
4456     int64_t StartOffset = Offset & ~15;
4457     if (StartOffset)
4458       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4459                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4460
4461     int EltNo = (Offset - StartOffset) >> 2;
4462     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4463     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4464     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4465                              LD->getPointerInfo().getWithOffset(StartOffset),
4466                              false, false, 0);
4467     // Canonicalize it to a v4i32 shuffle.
4468     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4469     return DAG.getNode(ISD::BITCAST, dl, VT,
4470                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4471                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4472   }
4473
4474   return SDValue();
4475 }
4476
4477 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4478 /// vector of type 'VT', see if the elements can be replaced by a single large
4479 /// load which has the same value as a build_vector whose operands are 'elts'.
4480 ///
4481 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4482 ///
4483 /// FIXME: we'd also like to handle the case where the last elements are zero
4484 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4485 /// There's even a handy isZeroNode for that purpose.
4486 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4487                                         DebugLoc &DL, SelectionDAG &DAG) {
4488   EVT EltVT = VT.getVectorElementType();
4489   unsigned NumElems = Elts.size();
4490
4491   LoadSDNode *LDBase = NULL;
4492   unsigned LastLoadedElt = -1U;
4493
4494   // For each element in the initializer, see if we've found a load or an undef.
4495   // If we don't find an initial load element, or later load elements are
4496   // non-consecutive, bail out.
4497   for (unsigned i = 0; i < NumElems; ++i) {
4498     SDValue Elt = Elts[i];
4499
4500     if (!Elt.getNode() ||
4501         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4502       return SDValue();
4503     if (!LDBase) {
4504       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4505         return SDValue();
4506       LDBase = cast<LoadSDNode>(Elt.getNode());
4507       LastLoadedElt = i;
4508       continue;
4509     }
4510     if (Elt.getOpcode() == ISD::UNDEF)
4511       continue;
4512
4513     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4514     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4515       return SDValue();
4516     LastLoadedElt = i;
4517   }
4518
4519   // If we have found an entire vector of loads and undefs, then return a large
4520   // load of the entire vector width starting at the base pointer.  If we found
4521   // consecutive loads for the low half, generate a vzext_load node.
4522   if (LastLoadedElt == NumElems - 1) {
4523     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4524       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4525                          LDBase->getPointerInfo(),
4526                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4527     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4528                        LDBase->getPointerInfo(),
4529                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4530                        LDBase->getAlignment());
4531   } else if (NumElems == 4 && LastLoadedElt == 1) {
4532     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4533     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4534     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4535                                               Ops, 2, MVT::i32,
4536                                               LDBase->getMemOperand());
4537     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4538   }
4539   return SDValue();
4540 }
4541
4542 SDValue
4543 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4544   DebugLoc dl = Op.getDebugLoc();
4545
4546   EVT VT = Op.getValueType();
4547   EVT ExtVT = VT.getVectorElementType();
4548
4549   unsigned NumElems = Op.getNumOperands();
4550
4551   // For AVX-length vectors, build the individual 128-bit pieces and
4552   // use shuffles to put them in place.
4553   if (VT.getSizeInBits() > 256 &&
4554       Subtarget->hasAVX() &&
4555       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4556     SmallVector<SDValue, 8> V;
4557     V.resize(NumElems);
4558     for (unsigned i = 0; i < NumElems; ++i) {
4559       V[i] = Op.getOperand(i);
4560     }
4561
4562     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4563
4564     // Build the lower subvector.
4565     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4566     // Build the upper subvector.
4567     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4568                                 NumElems/2);
4569
4570     return ConcatVectors(Lower, Upper, DAG);
4571   }
4572
4573   // All zero's:
4574   //  - pxor (SSE2), xorps (SSE1), vpxor (128 AVX), xorp[s|d] (256 AVX)
4575   // All one's:
4576   //  - pcmpeqd (SSE2 and 128 AVX), fallback to constant pools (256 AVX)
4577   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4578       ISD::isBuildVectorAllOnes(Op.getNode())) {
4579     // Canonicalize this to <4 x i32> or <8 x 32> (SSE) to
4580     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4581     // eliminated on x86-32 hosts.
4582     if (Op.getValueType() == MVT::v4i32 ||
4583         Op.getValueType() == MVT::v8i32)
4584       return Op;
4585
4586     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4587       return getOnesVector(Op.getValueType(), DAG, dl);
4588     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4589   }
4590
4591   unsigned EVTBits = ExtVT.getSizeInBits();
4592
4593   unsigned NumZero  = 0;
4594   unsigned NumNonZero = 0;
4595   unsigned NonZeros = 0;
4596   bool IsAllConstants = true;
4597   SmallSet<SDValue, 8> Values;
4598   for (unsigned i = 0; i < NumElems; ++i) {
4599     SDValue Elt = Op.getOperand(i);
4600     if (Elt.getOpcode() == ISD::UNDEF)
4601       continue;
4602     Values.insert(Elt);
4603     if (Elt.getOpcode() != ISD::Constant &&
4604         Elt.getOpcode() != ISD::ConstantFP)
4605       IsAllConstants = false;
4606     if (X86::isZeroNode(Elt))
4607       NumZero++;
4608     else {
4609       NonZeros |= (1 << i);
4610       NumNonZero++;
4611     }
4612   }
4613
4614   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4615   if (NumNonZero == 0)
4616     return DAG.getUNDEF(VT);
4617
4618   // Special case for single non-zero, non-undef, element.
4619   if (NumNonZero == 1) {
4620     unsigned Idx = CountTrailingZeros_32(NonZeros);
4621     SDValue Item = Op.getOperand(Idx);
4622
4623     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4624     // the value are obviously zero, truncate the value to i32 and do the
4625     // insertion that way.  Only do this if the value is non-constant or if the
4626     // value is a constant being inserted into element 0.  It is cheaper to do
4627     // a constant pool load than it is to do a movd + shuffle.
4628     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4629         (!IsAllConstants || Idx == 0)) {
4630       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4631         // Handle SSE only.
4632         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4633         EVT VecVT = MVT::v4i32;
4634         unsigned VecElts = 4;
4635
4636         // Truncate the value (which may itself be a constant) to i32, and
4637         // convert it to a vector with movd (S2V+shuffle to zero extend).
4638         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4639         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4640         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4641                                            Subtarget->hasSSE2(), DAG);
4642
4643         // Now we have our 32-bit value zero extended in the low element of
4644         // a vector.  If Idx != 0, swizzle it into place.
4645         if (Idx != 0) {
4646           SmallVector<int, 4> Mask;
4647           Mask.push_back(Idx);
4648           for (unsigned i = 1; i != VecElts; ++i)
4649             Mask.push_back(i);
4650           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4651                                       DAG.getUNDEF(Item.getValueType()),
4652                                       &Mask[0]);
4653         }
4654         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4655       }
4656     }
4657
4658     // If we have a constant or non-constant insertion into the low element of
4659     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4660     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4661     // depending on what the source datatype is.
4662     if (Idx == 0) {
4663       if (NumZero == 0) {
4664         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4665       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4666           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4667         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4668         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4669         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4670                                            DAG);
4671       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4672         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4673         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4674         EVT MiddleVT = MVT::v4i32;
4675         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4676         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4677                                            Subtarget->hasSSE2(), DAG);
4678         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4679       }
4680     }
4681
4682     // Is it a vector logical left shift?
4683     if (NumElems == 2 && Idx == 1 &&
4684         X86::isZeroNode(Op.getOperand(0)) &&
4685         !X86::isZeroNode(Op.getOperand(1))) {
4686       unsigned NumBits = VT.getSizeInBits();
4687       return getVShift(true, VT,
4688                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4689                                    VT, Op.getOperand(1)),
4690                        NumBits/2, DAG, *this, dl);
4691     }
4692
4693     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4694       return SDValue();
4695
4696     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4697     // is a non-constant being inserted into an element other than the low one,
4698     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4699     // movd/movss) to move this into the low element, then shuffle it into
4700     // place.
4701     if (EVTBits == 32) {
4702       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4703
4704       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4705       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4706                                          Subtarget->hasSSE2(), DAG);
4707       SmallVector<int, 8> MaskVec;
4708       for (unsigned i = 0; i < NumElems; i++)
4709         MaskVec.push_back(i == Idx ? 0 : 1);
4710       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4711     }
4712   }
4713
4714   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4715   if (Values.size() == 1) {
4716     if (EVTBits == 32) {
4717       // Instead of a shuffle like this:
4718       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4719       // Check if it's possible to issue this instead.
4720       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4721       unsigned Idx = CountTrailingZeros_32(NonZeros);
4722       SDValue Item = Op.getOperand(Idx);
4723       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4724         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4725     }
4726     return SDValue();
4727   }
4728
4729   // A vector full of immediates; various special cases are already
4730   // handled, so this is best done with a single constant-pool load.
4731   if (IsAllConstants)
4732     return SDValue();
4733
4734   // Let legalizer expand 2-wide build_vectors.
4735   if (EVTBits == 64) {
4736     if (NumNonZero == 1) {
4737       // One half is zero or undef.
4738       unsigned Idx = CountTrailingZeros_32(NonZeros);
4739       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4740                                  Op.getOperand(Idx));
4741       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4742                                          Subtarget->hasSSE2(), DAG);
4743     }
4744     return SDValue();
4745   }
4746
4747   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4748   if (EVTBits == 8 && NumElems == 16) {
4749     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4750                                         *this);
4751     if (V.getNode()) return V;
4752   }
4753
4754   if (EVTBits == 16 && NumElems == 8) {
4755     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4756                                       *this);
4757     if (V.getNode()) return V;
4758   }
4759
4760   // If element VT is == 32 bits, turn it into a number of shuffles.
4761   SmallVector<SDValue, 8> V;
4762   V.resize(NumElems);
4763   if (NumElems == 4 && NumZero > 0) {
4764     for (unsigned i = 0; i < 4; ++i) {
4765       bool isZero = !(NonZeros & (1 << i));
4766       if (isZero)
4767         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4768       else
4769         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4770     }
4771
4772     for (unsigned i = 0; i < 2; ++i) {
4773       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4774         default: break;
4775         case 0:
4776           V[i] = V[i*2];  // Must be a zero vector.
4777           break;
4778         case 1:
4779           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4780           break;
4781         case 2:
4782           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4783           break;
4784         case 3:
4785           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4786           break;
4787       }
4788     }
4789
4790     SmallVector<int, 8> MaskVec;
4791     bool Reverse = (NonZeros & 0x3) == 2;
4792     for (unsigned i = 0; i < 2; ++i)
4793       MaskVec.push_back(Reverse ? 1-i : i);
4794     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4795     for (unsigned i = 0; i < 2; ++i)
4796       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4797     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4798   }
4799
4800   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4801     // Check for a build vector of consecutive loads.
4802     for (unsigned i = 0; i < NumElems; ++i)
4803       V[i] = Op.getOperand(i);
4804
4805     // Check for elements which are consecutive loads.
4806     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4807     if (LD.getNode())
4808       return LD;
4809
4810     // For SSE 4.1, use insertps to put the high elements into the low element.
4811     if (getSubtarget()->hasSSE41()) {
4812       SDValue Result;
4813       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4814         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4815       else
4816         Result = DAG.getUNDEF(VT);
4817
4818       for (unsigned i = 1; i < NumElems; ++i) {
4819         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4820         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4821                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4822       }
4823       return Result;
4824     }
4825
4826     // Otherwise, expand into a number of unpckl*, start by extending each of
4827     // our (non-undef) elements to the full vector width with the element in the
4828     // bottom slot of the vector (which generates no code for SSE).
4829     for (unsigned i = 0; i < NumElems; ++i) {
4830       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4831         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4832       else
4833         V[i] = DAG.getUNDEF(VT);
4834     }
4835
4836     // Next, we iteratively mix elements, e.g. for v4f32:
4837     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4838     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4839     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4840     unsigned EltStride = NumElems >> 1;
4841     while (EltStride != 0) {
4842       for (unsigned i = 0; i < EltStride; ++i) {
4843         // If V[i+EltStride] is undef and this is the first round of mixing,
4844         // then it is safe to just drop this shuffle: V[i] is already in the
4845         // right place, the one element (since it's the first round) being
4846         // inserted as undef can be dropped.  This isn't safe for successive
4847         // rounds because they will permute elements within both vectors.
4848         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4849             EltStride == NumElems/2)
4850           continue;
4851
4852         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4853       }
4854       EltStride >>= 1;
4855     }
4856     return V[0];
4857   }
4858   return SDValue();
4859 }
4860
4861 SDValue
4862 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4863   // We support concatenate two MMX registers and place them in a MMX
4864   // register.  This is better than doing a stack convert.
4865   DebugLoc dl = Op.getDebugLoc();
4866   EVT ResVT = Op.getValueType();
4867   assert(Op.getNumOperands() == 2);
4868   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4869          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4870   int Mask[2];
4871   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4872   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4873   InVec = Op.getOperand(1);
4874   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4875     unsigned NumElts = ResVT.getVectorNumElements();
4876     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4877     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4878                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4879   } else {
4880     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4881     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4882     Mask[0] = 0; Mask[1] = 2;
4883     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4884   }
4885   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4886 }
4887
4888 // v8i16 shuffles - Prefer shuffles in the following order:
4889 // 1. [all]   pshuflw, pshufhw, optional move
4890 // 2. [ssse3] 1 x pshufb
4891 // 3. [ssse3] 2 x pshufb + 1 x por
4892 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4893 SDValue
4894 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4895                                             SelectionDAG &DAG) const {
4896   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4897   SDValue V1 = SVOp->getOperand(0);
4898   SDValue V2 = SVOp->getOperand(1);
4899   DebugLoc dl = SVOp->getDebugLoc();
4900   SmallVector<int, 8> MaskVals;
4901
4902   // Determine if more than 1 of the words in each of the low and high quadwords
4903   // of the result come from the same quadword of one of the two inputs.  Undef
4904   // mask values count as coming from any quadword, for better codegen.
4905   SmallVector<unsigned, 4> LoQuad(4);
4906   SmallVector<unsigned, 4> HiQuad(4);
4907   BitVector InputQuads(4);
4908   for (unsigned i = 0; i < 8; ++i) {
4909     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4910     int EltIdx = SVOp->getMaskElt(i);
4911     MaskVals.push_back(EltIdx);
4912     if (EltIdx < 0) {
4913       ++Quad[0];
4914       ++Quad[1];
4915       ++Quad[2];
4916       ++Quad[3];
4917       continue;
4918     }
4919     ++Quad[EltIdx / 4];
4920     InputQuads.set(EltIdx / 4);
4921   }
4922
4923   int BestLoQuad = -1;
4924   unsigned MaxQuad = 1;
4925   for (unsigned i = 0; i < 4; ++i) {
4926     if (LoQuad[i] > MaxQuad) {
4927       BestLoQuad = i;
4928       MaxQuad = LoQuad[i];
4929     }
4930   }
4931
4932   int BestHiQuad = -1;
4933   MaxQuad = 1;
4934   for (unsigned i = 0; i < 4; ++i) {
4935     if (HiQuad[i] > MaxQuad) {
4936       BestHiQuad = i;
4937       MaxQuad = HiQuad[i];
4938     }
4939   }
4940
4941   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4942   // of the two input vectors, shuffle them into one input vector so only a
4943   // single pshufb instruction is necessary. If There are more than 2 input
4944   // quads, disable the next transformation since it does not help SSSE3.
4945   bool V1Used = InputQuads[0] || InputQuads[1];
4946   bool V2Used = InputQuads[2] || InputQuads[3];
4947   if (Subtarget->hasSSSE3()) {
4948     if (InputQuads.count() == 2 && V1Used && V2Used) {
4949       BestLoQuad = InputQuads.find_first();
4950       BestHiQuad = InputQuads.find_next(BestLoQuad);
4951     }
4952     if (InputQuads.count() > 2) {
4953       BestLoQuad = -1;
4954       BestHiQuad = -1;
4955     }
4956   }
4957
4958   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4959   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4960   // words from all 4 input quadwords.
4961   SDValue NewV;
4962   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4963     SmallVector<int, 8> MaskV;
4964     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4965     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4966     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4967                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4968                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4969     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4970
4971     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4972     // source words for the shuffle, to aid later transformations.
4973     bool AllWordsInNewV = true;
4974     bool InOrder[2] = { true, true };
4975     for (unsigned i = 0; i != 8; ++i) {
4976       int idx = MaskVals[i];
4977       if (idx != (int)i)
4978         InOrder[i/4] = false;
4979       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4980         continue;
4981       AllWordsInNewV = false;
4982       break;
4983     }
4984
4985     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4986     if (AllWordsInNewV) {
4987       for (int i = 0; i != 8; ++i) {
4988         int idx = MaskVals[i];
4989         if (idx < 0)
4990           continue;
4991         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4992         if ((idx != i) && idx < 4)
4993           pshufhw = false;
4994         if ((idx != i) && idx > 3)
4995           pshuflw = false;
4996       }
4997       V1 = NewV;
4998       V2Used = false;
4999       BestLoQuad = 0;
5000       BestHiQuad = 1;
5001     }
5002
5003     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5004     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5005     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5006       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5007       unsigned TargetMask = 0;
5008       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5009                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5010       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5011                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5012       V1 = NewV.getOperand(0);
5013       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5014     }
5015   }
5016
5017   // If we have SSSE3, and all words of the result are from 1 input vector,
5018   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5019   // is present, fall back to case 4.
5020   if (Subtarget->hasSSSE3()) {
5021     SmallVector<SDValue,16> pshufbMask;
5022
5023     // If we have elements from both input vectors, set the high bit of the
5024     // shuffle mask element to zero out elements that come from V2 in the V1
5025     // mask, and elements that come from V1 in the V2 mask, so that the two
5026     // results can be OR'd together.
5027     bool TwoInputs = V1Used && V2Used;
5028     for (unsigned i = 0; i != 8; ++i) {
5029       int EltIdx = MaskVals[i] * 2;
5030       if (TwoInputs && (EltIdx >= 16)) {
5031         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5032         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5033         continue;
5034       }
5035       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5036       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5037     }
5038     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5039     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5040                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5041                                  MVT::v16i8, &pshufbMask[0], 16));
5042     if (!TwoInputs)
5043       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5044
5045     // Calculate the shuffle mask for the second input, shuffle it, and
5046     // OR it with the first shuffled input.
5047     pshufbMask.clear();
5048     for (unsigned i = 0; i != 8; ++i) {
5049       int EltIdx = MaskVals[i] * 2;
5050       if (EltIdx < 16) {
5051         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5052         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5053         continue;
5054       }
5055       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5056       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5057     }
5058     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5059     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5060                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5061                                  MVT::v16i8, &pshufbMask[0], 16));
5062     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5063     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5064   }
5065
5066   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5067   // and update MaskVals with new element order.
5068   BitVector InOrder(8);
5069   if (BestLoQuad >= 0) {
5070     SmallVector<int, 8> MaskV;
5071     for (int i = 0; i != 4; ++i) {
5072       int idx = MaskVals[i];
5073       if (idx < 0) {
5074         MaskV.push_back(-1);
5075         InOrder.set(i);
5076       } else if ((idx / 4) == BestLoQuad) {
5077         MaskV.push_back(idx & 3);
5078         InOrder.set(i);
5079       } else {
5080         MaskV.push_back(-1);
5081       }
5082     }
5083     for (unsigned i = 4; i != 8; ++i)
5084       MaskV.push_back(i);
5085     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5086                                 &MaskV[0]);
5087
5088     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5089       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5090                                NewV.getOperand(0),
5091                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5092                                DAG);
5093   }
5094
5095   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5096   // and update MaskVals with the new element order.
5097   if (BestHiQuad >= 0) {
5098     SmallVector<int, 8> MaskV;
5099     for (unsigned i = 0; i != 4; ++i)
5100       MaskV.push_back(i);
5101     for (unsigned i = 4; i != 8; ++i) {
5102       int idx = MaskVals[i];
5103       if (idx < 0) {
5104         MaskV.push_back(-1);
5105         InOrder.set(i);
5106       } else if ((idx / 4) == BestHiQuad) {
5107         MaskV.push_back((idx & 3) + 4);
5108         InOrder.set(i);
5109       } else {
5110         MaskV.push_back(-1);
5111       }
5112     }
5113     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5114                                 &MaskV[0]);
5115
5116     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5117       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5118                               NewV.getOperand(0),
5119                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5120                               DAG);
5121   }
5122
5123   // In case BestHi & BestLo were both -1, which means each quadword has a word
5124   // from each of the four input quadwords, calculate the InOrder bitvector now
5125   // before falling through to the insert/extract cleanup.
5126   if (BestLoQuad == -1 && BestHiQuad == -1) {
5127     NewV = V1;
5128     for (int i = 0; i != 8; ++i)
5129       if (MaskVals[i] < 0 || MaskVals[i] == i)
5130         InOrder.set(i);
5131   }
5132
5133   // The other elements are put in the right place using pextrw and pinsrw.
5134   for (unsigned i = 0; i != 8; ++i) {
5135     if (InOrder[i])
5136       continue;
5137     int EltIdx = MaskVals[i];
5138     if (EltIdx < 0)
5139       continue;
5140     SDValue ExtOp = (EltIdx < 8)
5141     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5142                   DAG.getIntPtrConstant(EltIdx))
5143     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5144                   DAG.getIntPtrConstant(EltIdx - 8));
5145     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5146                        DAG.getIntPtrConstant(i));
5147   }
5148   return NewV;
5149 }
5150
5151 // v16i8 shuffles - Prefer shuffles in the following order:
5152 // 1. [ssse3] 1 x pshufb
5153 // 2. [ssse3] 2 x pshufb + 1 x por
5154 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5155 static
5156 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5157                                  SelectionDAG &DAG,
5158                                  const X86TargetLowering &TLI) {
5159   SDValue V1 = SVOp->getOperand(0);
5160   SDValue V2 = SVOp->getOperand(1);
5161   DebugLoc dl = SVOp->getDebugLoc();
5162   SmallVector<int, 16> MaskVals;
5163   SVOp->getMask(MaskVals);
5164
5165   // If we have SSSE3, case 1 is generated when all result bytes come from
5166   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5167   // present, fall back to case 3.
5168   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5169   bool V1Only = true;
5170   bool V2Only = true;
5171   for (unsigned i = 0; i < 16; ++i) {
5172     int EltIdx = MaskVals[i];
5173     if (EltIdx < 0)
5174       continue;
5175     if (EltIdx < 16)
5176       V2Only = false;
5177     else
5178       V1Only = false;
5179   }
5180
5181   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5182   if (TLI.getSubtarget()->hasSSSE3()) {
5183     SmallVector<SDValue,16> pshufbMask;
5184
5185     // If all result elements are from one input vector, then only translate
5186     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5187     //
5188     // Otherwise, we have elements from both input vectors, and must zero out
5189     // elements that come from V2 in the first mask, and V1 in the second mask
5190     // so that we can OR them together.
5191     bool TwoInputs = !(V1Only || V2Only);
5192     for (unsigned i = 0; i != 16; ++i) {
5193       int EltIdx = MaskVals[i];
5194       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5195         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5196         continue;
5197       }
5198       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5199     }
5200     // If all the elements are from V2, assign it to V1 and return after
5201     // building the first pshufb.
5202     if (V2Only)
5203       V1 = V2;
5204     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5205                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5206                                  MVT::v16i8, &pshufbMask[0], 16));
5207     if (!TwoInputs)
5208       return V1;
5209
5210     // Calculate the shuffle mask for the second input, shuffle it, and
5211     // OR it with the first shuffled input.
5212     pshufbMask.clear();
5213     for (unsigned i = 0; i != 16; ++i) {
5214       int EltIdx = MaskVals[i];
5215       if (EltIdx < 16) {
5216         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5217         continue;
5218       }
5219       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5220     }
5221     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5222                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5223                                  MVT::v16i8, &pshufbMask[0], 16));
5224     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5225   }
5226
5227   // No SSSE3 - Calculate in place words and then fix all out of place words
5228   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5229   // the 16 different words that comprise the two doublequadword input vectors.
5230   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5231   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5232   SDValue NewV = V2Only ? V2 : V1;
5233   for (int i = 0; i != 8; ++i) {
5234     int Elt0 = MaskVals[i*2];
5235     int Elt1 = MaskVals[i*2+1];
5236
5237     // This word of the result is all undef, skip it.
5238     if (Elt0 < 0 && Elt1 < 0)
5239       continue;
5240
5241     // This word of the result is already in the correct place, skip it.
5242     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5243       continue;
5244     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5245       continue;
5246
5247     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5248     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5249     SDValue InsElt;
5250
5251     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5252     // using a single extract together, load it and store it.
5253     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5254       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5255                            DAG.getIntPtrConstant(Elt1 / 2));
5256       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5257                         DAG.getIntPtrConstant(i));
5258       continue;
5259     }
5260
5261     // If Elt1 is defined, extract it from the appropriate source.  If the
5262     // source byte is not also odd, shift the extracted word left 8 bits
5263     // otherwise clear the bottom 8 bits if we need to do an or.
5264     if (Elt1 >= 0) {
5265       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5266                            DAG.getIntPtrConstant(Elt1 / 2));
5267       if ((Elt1 & 1) == 0)
5268         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5269                              DAG.getConstant(8,
5270                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5271       else if (Elt0 >= 0)
5272         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5273                              DAG.getConstant(0xFF00, MVT::i16));
5274     }
5275     // If Elt0 is defined, extract it from the appropriate source.  If the
5276     // source byte is not also even, shift the extracted word right 8 bits. If
5277     // Elt1 was also defined, OR the extracted values together before
5278     // inserting them in the result.
5279     if (Elt0 >= 0) {
5280       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5281                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5282       if ((Elt0 & 1) != 0)
5283         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5284                               DAG.getConstant(8,
5285                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5286       else if (Elt1 >= 0)
5287         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5288                              DAG.getConstant(0x00FF, MVT::i16));
5289       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5290                          : InsElt0;
5291     }
5292     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5293                        DAG.getIntPtrConstant(i));
5294   }
5295   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5296 }
5297
5298 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5299 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5300 /// done when every pair / quad of shuffle mask elements point to elements in
5301 /// the right sequence. e.g.
5302 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5303 static
5304 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5305                                  SelectionDAG &DAG, DebugLoc dl) {
5306   EVT VT = SVOp->getValueType(0);
5307   SDValue V1 = SVOp->getOperand(0);
5308   SDValue V2 = SVOp->getOperand(1);
5309   unsigned NumElems = VT.getVectorNumElements();
5310   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5311   EVT NewVT;
5312   switch (VT.getSimpleVT().SimpleTy) {
5313   default: assert(false && "Unexpected!");
5314   case MVT::v4f32: NewVT = MVT::v2f64; break;
5315   case MVT::v4i32: NewVT = MVT::v2i64; break;
5316   case MVT::v8i16: NewVT = MVT::v4i32; break;
5317   case MVT::v16i8: NewVT = MVT::v4i32; break;
5318   }
5319
5320   int Scale = NumElems / NewWidth;
5321   SmallVector<int, 8> MaskVec;
5322   for (unsigned i = 0; i < NumElems; i += Scale) {
5323     int StartIdx = -1;
5324     for (int j = 0; j < Scale; ++j) {
5325       int EltIdx = SVOp->getMaskElt(i+j);
5326       if (EltIdx < 0)
5327         continue;
5328       if (StartIdx == -1)
5329         StartIdx = EltIdx - (EltIdx % Scale);
5330       if (EltIdx != StartIdx + j)
5331         return SDValue();
5332     }
5333     if (StartIdx == -1)
5334       MaskVec.push_back(-1);
5335     else
5336       MaskVec.push_back(StartIdx / Scale);
5337   }
5338
5339   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5340   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5341   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5342 }
5343
5344 /// getVZextMovL - Return a zero-extending vector move low node.
5345 ///
5346 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5347                             SDValue SrcOp, SelectionDAG &DAG,
5348                             const X86Subtarget *Subtarget, DebugLoc dl) {
5349   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5350     LoadSDNode *LD = NULL;
5351     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5352       LD = dyn_cast<LoadSDNode>(SrcOp);
5353     if (!LD) {
5354       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5355       // instead.
5356       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5357       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5358           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5359           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5360           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5361         // PR2108
5362         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5363         return DAG.getNode(ISD::BITCAST, dl, VT,
5364                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5365                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5366                                                    OpVT,
5367                                                    SrcOp.getOperand(0)
5368                                                           .getOperand(0))));
5369       }
5370     }
5371   }
5372
5373   return DAG.getNode(ISD::BITCAST, dl, VT,
5374                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5375                                  DAG.getNode(ISD::BITCAST, dl,
5376                                              OpVT, SrcOp)));
5377 }
5378
5379 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5380 /// which could not be matched by any known target speficic shuffle
5381 static SDValue
5382 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5383   return SDValue();
5384 }
5385
5386 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5387 /// 4 elements, and match them with several different shuffle types.
5388 static SDValue
5389 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5390   SDValue V1 = SVOp->getOperand(0);
5391   SDValue V2 = SVOp->getOperand(1);
5392   DebugLoc dl = SVOp->getDebugLoc();
5393   EVT VT = SVOp->getValueType(0);
5394
5395   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5396
5397   SmallVector<std::pair<int, int>, 8> Locs;
5398   Locs.resize(4);
5399   SmallVector<int, 8> Mask1(4U, -1);
5400   SmallVector<int, 8> PermMask;
5401   SVOp->getMask(PermMask);
5402
5403   unsigned NumHi = 0;
5404   unsigned NumLo = 0;
5405   for (unsigned i = 0; i != 4; ++i) {
5406     int Idx = PermMask[i];
5407     if (Idx < 0) {
5408       Locs[i] = std::make_pair(-1, -1);
5409     } else {
5410       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5411       if (Idx < 4) {
5412         Locs[i] = std::make_pair(0, NumLo);
5413         Mask1[NumLo] = Idx;
5414         NumLo++;
5415       } else {
5416         Locs[i] = std::make_pair(1, NumHi);
5417         if (2+NumHi < 4)
5418           Mask1[2+NumHi] = Idx;
5419         NumHi++;
5420       }
5421     }
5422   }
5423
5424   if (NumLo <= 2 && NumHi <= 2) {
5425     // If no more than two elements come from either vector. This can be
5426     // implemented with two shuffles. First shuffle gather the elements.
5427     // The second shuffle, which takes the first shuffle as both of its
5428     // vector operands, put the elements into the right order.
5429     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5430
5431     SmallVector<int, 8> Mask2(4U, -1);
5432
5433     for (unsigned i = 0; i != 4; ++i) {
5434       if (Locs[i].first == -1)
5435         continue;
5436       else {
5437         unsigned Idx = (i < 2) ? 0 : 4;
5438         Idx += Locs[i].first * 2 + Locs[i].second;
5439         Mask2[i] = Idx;
5440       }
5441     }
5442
5443     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5444   } else if (NumLo == 3 || NumHi == 3) {
5445     // Otherwise, we must have three elements from one vector, call it X, and
5446     // one element from the other, call it Y.  First, use a shufps to build an
5447     // intermediate vector with the one element from Y and the element from X
5448     // that will be in the same half in the final destination (the indexes don't
5449     // matter). Then, use a shufps to build the final vector, taking the half
5450     // containing the element from Y from the intermediate, and the other half
5451     // from X.
5452     if (NumHi == 3) {
5453       // Normalize it so the 3 elements come from V1.
5454       CommuteVectorShuffleMask(PermMask, VT);
5455       std::swap(V1, V2);
5456     }
5457
5458     // Find the element from V2.
5459     unsigned HiIndex;
5460     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5461       int Val = PermMask[HiIndex];
5462       if (Val < 0)
5463         continue;
5464       if (Val >= 4)
5465         break;
5466     }
5467
5468     Mask1[0] = PermMask[HiIndex];
5469     Mask1[1] = -1;
5470     Mask1[2] = PermMask[HiIndex^1];
5471     Mask1[3] = -1;
5472     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5473
5474     if (HiIndex >= 2) {
5475       Mask1[0] = PermMask[0];
5476       Mask1[1] = PermMask[1];
5477       Mask1[2] = HiIndex & 1 ? 6 : 4;
5478       Mask1[3] = HiIndex & 1 ? 4 : 6;
5479       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5480     } else {
5481       Mask1[0] = HiIndex & 1 ? 2 : 0;
5482       Mask1[1] = HiIndex & 1 ? 0 : 2;
5483       Mask1[2] = PermMask[2];
5484       Mask1[3] = PermMask[3];
5485       if (Mask1[2] >= 0)
5486         Mask1[2] += 4;
5487       if (Mask1[3] >= 0)
5488         Mask1[3] += 4;
5489       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5490     }
5491   }
5492
5493   // Break it into (shuffle shuffle_hi, shuffle_lo).
5494   Locs.clear();
5495   Locs.resize(4);
5496   SmallVector<int,8> LoMask(4U, -1);
5497   SmallVector<int,8> HiMask(4U, -1);
5498
5499   SmallVector<int,8> *MaskPtr = &LoMask;
5500   unsigned MaskIdx = 0;
5501   unsigned LoIdx = 0;
5502   unsigned HiIdx = 2;
5503   for (unsigned i = 0; i != 4; ++i) {
5504     if (i == 2) {
5505       MaskPtr = &HiMask;
5506       MaskIdx = 1;
5507       LoIdx = 0;
5508       HiIdx = 2;
5509     }
5510     int Idx = PermMask[i];
5511     if (Idx < 0) {
5512       Locs[i] = std::make_pair(-1, -1);
5513     } else if (Idx < 4) {
5514       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5515       (*MaskPtr)[LoIdx] = Idx;
5516       LoIdx++;
5517     } else {
5518       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5519       (*MaskPtr)[HiIdx] = Idx;
5520       HiIdx++;
5521     }
5522   }
5523
5524   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5525   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5526   SmallVector<int, 8> MaskOps;
5527   for (unsigned i = 0; i != 4; ++i) {
5528     if (Locs[i].first == -1) {
5529       MaskOps.push_back(-1);
5530     } else {
5531       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5532       MaskOps.push_back(Idx);
5533     }
5534   }
5535   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5536 }
5537
5538 static bool MayFoldVectorLoad(SDValue V) {
5539   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5540     V = V.getOperand(0);
5541   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5542     V = V.getOperand(0);
5543   if (MayFoldLoad(V))
5544     return true;
5545   return false;
5546 }
5547
5548 // FIXME: the version above should always be used. Since there's
5549 // a bug where several vector shuffles can't be folded because the
5550 // DAG is not updated during lowering and a node claims to have two
5551 // uses while it only has one, use this version, and let isel match
5552 // another instruction if the load really happens to have more than
5553 // one use. Remove this version after this bug get fixed.
5554 // rdar://8434668, PR8156
5555 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5556   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5557     V = V.getOperand(0);
5558   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5559     V = V.getOperand(0);
5560   if (ISD::isNormalLoad(V.getNode()))
5561     return true;
5562   return false;
5563 }
5564
5565 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5566 /// a vector extract, and if both can be later optimized into a single load.
5567 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5568 /// here because otherwise a target specific shuffle node is going to be
5569 /// emitted for this shuffle, and the optimization not done.
5570 /// FIXME: This is probably not the best approach, but fix the problem
5571 /// until the right path is decided.
5572 static
5573 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5574                                          const TargetLowering &TLI) {
5575   EVT VT = V.getValueType();
5576   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5577
5578   // Be sure that the vector shuffle is present in a pattern like this:
5579   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5580   if (!V.hasOneUse())
5581     return false;
5582
5583   SDNode *N = *V.getNode()->use_begin();
5584   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5585     return false;
5586
5587   SDValue EltNo = N->getOperand(1);
5588   if (!isa<ConstantSDNode>(EltNo))
5589     return false;
5590
5591   // If the bit convert changed the number of elements, it is unsafe
5592   // to examine the mask.
5593   bool HasShuffleIntoBitcast = false;
5594   if (V.getOpcode() == ISD::BITCAST) {
5595     EVT SrcVT = V.getOperand(0).getValueType();
5596     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5597       return false;
5598     V = V.getOperand(0);
5599     HasShuffleIntoBitcast = true;
5600   }
5601
5602   // Select the input vector, guarding against out of range extract vector.
5603   unsigned NumElems = VT.getVectorNumElements();
5604   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5605   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5606   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5607
5608   // Skip one more bit_convert if necessary
5609   if (V.getOpcode() == ISD::BITCAST)
5610     V = V.getOperand(0);
5611
5612   if (ISD::isNormalLoad(V.getNode())) {
5613     // Is the original load suitable?
5614     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5615
5616     // FIXME: avoid the multi-use bug that is preventing lots of
5617     // of foldings to be detected, this is still wrong of course, but
5618     // give the temporary desired behavior, and if it happens that
5619     // the load has real more uses, during isel it will not fold, and
5620     // will generate poor code.
5621     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5622       return false;
5623
5624     if (!HasShuffleIntoBitcast)
5625       return true;
5626
5627     // If there's a bitcast before the shuffle, check if the load type and
5628     // alignment is valid.
5629     unsigned Align = LN0->getAlignment();
5630     unsigned NewAlign =
5631       TLI.getTargetData()->getABITypeAlignment(
5632                                     VT.getTypeForEVT(*DAG.getContext()));
5633
5634     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5635       return false;
5636   }
5637
5638   return true;
5639 }
5640
5641 static
5642 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5643   EVT VT = Op.getValueType();
5644
5645   // Canonizalize to v2f64.
5646   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5647   return DAG.getNode(ISD::BITCAST, dl, VT,
5648                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5649                                           V1, DAG));
5650 }
5651
5652 static
5653 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5654                         bool HasSSE2) {
5655   SDValue V1 = Op.getOperand(0);
5656   SDValue V2 = Op.getOperand(1);
5657   EVT VT = Op.getValueType();
5658
5659   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5660
5661   if (HasSSE2 && VT == MVT::v2f64)
5662     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5663
5664   // v4f32 or v4i32
5665   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5666 }
5667
5668 static
5669 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5670   SDValue V1 = Op.getOperand(0);
5671   SDValue V2 = Op.getOperand(1);
5672   EVT VT = Op.getValueType();
5673
5674   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5675          "unsupported shuffle type");
5676
5677   if (V2.getOpcode() == ISD::UNDEF)
5678     V2 = V1;
5679
5680   // v4i32 or v4f32
5681   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5682 }
5683
5684 static
5685 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5686   SDValue V1 = Op.getOperand(0);
5687   SDValue V2 = Op.getOperand(1);
5688   EVT VT = Op.getValueType();
5689   unsigned NumElems = VT.getVectorNumElements();
5690
5691   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5692   // operand of these instructions is only memory, so check if there's a
5693   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5694   // same masks.
5695   bool CanFoldLoad = false;
5696
5697   // Trivial case, when V2 comes from a load.
5698   if (MayFoldVectorLoad(V2))
5699     CanFoldLoad = true;
5700
5701   // When V1 is a load, it can be folded later into a store in isel, example:
5702   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5703   //    turns into:
5704   //  (MOVLPSmr addr:$src1, VR128:$src2)
5705   // So, recognize this potential and also use MOVLPS or MOVLPD
5706   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5707     CanFoldLoad = true;
5708
5709   // Both of them can't be memory operations though.
5710   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5711     CanFoldLoad = false;
5712
5713   if (CanFoldLoad) {
5714     if (HasSSE2 && NumElems == 2)
5715       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5716
5717     if (NumElems == 4)
5718       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5719   }
5720
5721   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5722   // movl and movlp will both match v2i64, but v2i64 is never matched by
5723   // movl earlier because we make it strict to avoid messing with the movlp load
5724   // folding logic (see the code above getMOVLP call). Match it here then,
5725   // this is horrible, but will stay like this until we move all shuffle
5726   // matching to x86 specific nodes. Note that for the 1st condition all
5727   // types are matched with movsd.
5728   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5729     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5730   else if (HasSSE2)
5731     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5732
5733
5734   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5735
5736   // Invert the operand order and use SHUFPS to match it.
5737   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5738                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5739 }
5740
5741 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5742   switch(VT.getSimpleVT().SimpleTy) {
5743   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5744   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5745   case MVT::v4f32:
5746     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5747   case MVT::v2f64:
5748     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5749   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5750   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5751   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5752   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5753   default:
5754     llvm_unreachable("Unknown type for unpckl");
5755   }
5756   return 0;
5757 }
5758
5759 static inline unsigned getUNPCKHOpcode(EVT VT) {
5760   switch(VT.getSimpleVT().SimpleTy) {
5761   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5762   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5763   case MVT::v4f32: return X86ISD::UNPCKHPS;
5764   case MVT::v2f64: return X86ISD::UNPCKHPD;
5765   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5766   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5767   default:
5768     llvm_unreachable("Unknown type for unpckh");
5769   }
5770   return 0;
5771 }
5772
5773 static
5774 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5775                                const TargetLowering &TLI,
5776                                const X86Subtarget *Subtarget) {
5777   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5778   EVT VT = Op.getValueType();
5779   DebugLoc dl = Op.getDebugLoc();
5780   SDValue V1 = Op.getOperand(0);
5781   SDValue V2 = Op.getOperand(1);
5782
5783   if (isZeroShuffle(SVOp))
5784     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5785
5786   // Handle splat operations
5787   if (SVOp->isSplat()) {
5788     unsigned NumElem = VT.getVectorNumElements();
5789     // Special case, this is the only place now where it's allowed to return
5790     // a vector_shuffle operation without using a target specific node, because
5791     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
5792     // this be moved to DAGCombine instead?
5793     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5794       return Op;
5795
5796     // Handle splats by matching through known masks
5797     if ((VT.is128BitVector() && NumElem <= 4) ||
5798         (VT.is256BitVector() && NumElem <= 8))
5799       return SDValue();
5800
5801     // All i16 and i8 vector types can't be used directly by a generic shuffle
5802     // instruction because the target has no such instruction. Generate shuffles
5803     // which repeat i16 and i8 several times until they fit in i32, and then can
5804     // be manipulated by target suported shuffles. After the insertion of the
5805     // necessary shuffles, the result is bitcasted back to v4f32 or v8f32.
5806     return PromoteSplat(SVOp, DAG);
5807   }
5808
5809   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5810   // do it!
5811   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5812     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5813     if (NewOp.getNode())
5814       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5815   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5816     // FIXME: Figure out a cleaner way to do this.
5817     // Try to make use of movq to zero out the top part.
5818     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5819       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5820       if (NewOp.getNode()) {
5821         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5822           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5823                               DAG, Subtarget, dl);
5824       }
5825     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5826       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5827       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5828         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5829                             DAG, Subtarget, dl);
5830     }
5831   }
5832   return SDValue();
5833 }
5834
5835 SDValue
5836 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5837   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5838   SDValue V1 = Op.getOperand(0);
5839   SDValue V2 = Op.getOperand(1);
5840   EVT VT = Op.getValueType();
5841   DebugLoc dl = Op.getDebugLoc();
5842   unsigned NumElems = VT.getVectorNumElements();
5843   bool isMMX = VT.getSizeInBits() == 64;
5844   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5845   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5846   bool V1IsSplat = false;
5847   bool V2IsSplat = false;
5848   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5849   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5850   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5851   MachineFunction &MF = DAG.getMachineFunction();
5852   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5853
5854   // Shuffle operations on MMX not supported.
5855   if (isMMX)
5856     return Op;
5857
5858   // Vector shuffle lowering takes 3 steps:
5859   //
5860   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5861   //    narrowing and commutation of operands should be handled.
5862   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5863   //    shuffle nodes.
5864   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5865   //    so the shuffle can be broken into other shuffles and the legalizer can
5866   //    try the lowering again.
5867   //
5868   // The general ideia is that no vector_shuffle operation should be left to
5869   // be matched during isel, all of them must be converted to a target specific
5870   // node here.
5871
5872   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5873   // narrowing and commutation of operands should be handled. The actual code
5874   // doesn't include all of those, work in progress...
5875   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5876   if (NewOp.getNode())
5877     return NewOp;
5878
5879   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5880   // unpckh_undef). Only use pshufd if speed is more important than size.
5881   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5882     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5883       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5884   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5885     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5886       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5887
5888   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5889       RelaxedMayFoldVectorLoad(V1))
5890     return getMOVDDup(Op, dl, V1, DAG);
5891
5892   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5893     return getMOVHighToLow(Op, dl, DAG);
5894
5895   // Use to match splats
5896   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5897       (VT == MVT::v2f64 || VT == MVT::v2i64))
5898     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5899
5900   if (X86::isPSHUFDMask(SVOp)) {
5901     // The actual implementation will match the mask in the if above and then
5902     // during isel it can match several different instructions, not only pshufd
5903     // as its name says, sad but true, emulate the behavior for now...
5904     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5905         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5906
5907     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5908
5909     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5910       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5911
5912     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5913       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5914                                   TargetMask, DAG);
5915
5916     if (VT == MVT::v4f32)
5917       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5918                                   TargetMask, DAG);
5919   }
5920
5921   // Check if this can be converted into a logical shift.
5922   bool isLeft = false;
5923   unsigned ShAmt = 0;
5924   SDValue ShVal;
5925   bool isShift = getSubtarget()->hasSSE2() &&
5926     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5927   if (isShift && ShVal.hasOneUse()) {
5928     // If the shifted value has multiple uses, it may be cheaper to use
5929     // v_set0 + movlhps or movhlps, etc.
5930     EVT EltVT = VT.getVectorElementType();
5931     ShAmt *= EltVT.getSizeInBits();
5932     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5933   }
5934
5935   if (X86::isMOVLMask(SVOp)) {
5936     if (V1IsUndef)
5937       return V2;
5938     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5939       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5940     if (!X86::isMOVLPMask(SVOp)) {
5941       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5942         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5943
5944       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5945         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5946     }
5947   }
5948
5949   // FIXME: fold these into legal mask.
5950   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5951     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5952
5953   if (X86::isMOVHLPSMask(SVOp))
5954     return getMOVHighToLow(Op, dl, DAG);
5955
5956   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5957     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5958
5959   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5960     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5961
5962   if (X86::isMOVLPMask(SVOp))
5963     return getMOVLP(Op, dl, DAG, HasSSE2);
5964
5965   if (ShouldXformToMOVHLPS(SVOp) ||
5966       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5967     return CommuteVectorShuffle(SVOp, DAG);
5968
5969   if (isShift) {
5970     // No better options. Use a vshl / vsrl.
5971     EVT EltVT = VT.getVectorElementType();
5972     ShAmt *= EltVT.getSizeInBits();
5973     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5974   }
5975
5976   bool Commuted = false;
5977   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5978   // 1,1,1,1 -> v8i16 though.
5979   V1IsSplat = isSplatVector(V1.getNode());
5980   V2IsSplat = isSplatVector(V2.getNode());
5981
5982   // Canonicalize the splat or undef, if present, to be on the RHS.
5983   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5984     Op = CommuteVectorShuffle(SVOp, DAG);
5985     SVOp = cast<ShuffleVectorSDNode>(Op);
5986     V1 = SVOp->getOperand(0);
5987     V2 = SVOp->getOperand(1);
5988     std::swap(V1IsSplat, V2IsSplat);
5989     std::swap(V1IsUndef, V2IsUndef);
5990     Commuted = true;
5991   }
5992
5993   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5994     // Shuffling low element of v1 into undef, just return v1.
5995     if (V2IsUndef)
5996       return V1;
5997     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5998     // the instruction selector will not match, so get a canonical MOVL with
5999     // swapped operands to undo the commute.
6000     return getMOVL(DAG, dl, VT, V2, V1);
6001   }
6002
6003   if (X86::isUNPCKLMask(SVOp))
6004     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6005                                 dl, VT, V1, V2, DAG);
6006
6007   if (X86::isUNPCKHMask(SVOp))
6008     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6009
6010   if (V2IsSplat) {
6011     // Normalize mask so all entries that point to V2 points to its first
6012     // element then try to match unpck{h|l} again. If match, return a
6013     // new vector_shuffle with the corrected mask.
6014     SDValue NewMask = NormalizeMask(SVOp, DAG);
6015     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6016     if (NSVOp != SVOp) {
6017       if (X86::isUNPCKLMask(NSVOp, true)) {
6018         return NewMask;
6019       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6020         return NewMask;
6021       }
6022     }
6023   }
6024
6025   if (Commuted) {
6026     // Commute is back and try unpck* again.
6027     // FIXME: this seems wrong.
6028     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6029     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6030
6031     if (X86::isUNPCKLMask(NewSVOp))
6032       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6033                                   dl, VT, V2, V1, DAG);
6034
6035     if (X86::isUNPCKHMask(NewSVOp))
6036       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6037   }
6038
6039   // Normalize the node to match x86 shuffle ops if needed
6040   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6041     return CommuteVectorShuffle(SVOp, DAG);
6042
6043   // The checks below are all present in isShuffleMaskLegal, but they are
6044   // inlined here right now to enable us to directly emit target specific
6045   // nodes, and remove one by one until they don't return Op anymore.
6046   SmallVector<int, 16> M;
6047   SVOp->getMask(M);
6048
6049   if (isPALIGNRMask(M, VT, HasSSSE3))
6050     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6051                                 X86::getShufflePALIGNRImmediate(SVOp),
6052                                 DAG);
6053
6054   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6055       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6056     if (VT == MVT::v2f64) {
6057       X86ISD::NodeType Opcode =
6058         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
6059       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
6060     }
6061     if (VT == MVT::v2i64)
6062       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6063   }
6064
6065   if (isPSHUFHWMask(M, VT))
6066     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6067                                 X86::getShufflePSHUFHWImmediate(SVOp),
6068                                 DAG);
6069
6070   if (isPSHUFLWMask(M, VT))
6071     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6072                                 X86::getShufflePSHUFLWImmediate(SVOp),
6073                                 DAG);
6074
6075   if (isSHUFPMask(M, VT)) {
6076     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6077     if (VT == MVT::v4f32 || VT == MVT::v4i32)
6078       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6079                                   TargetMask, DAG);
6080     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6081       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6082                                   TargetMask, DAG);
6083   }
6084
6085   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6086     if (VT != MVT::v2i64 && VT != MVT::v2f64)
6087       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6088                                   dl, VT, V1, V1, DAG);
6089   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6090     if (VT != MVT::v2i64 && VT != MVT::v2f64)
6091       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6092
6093   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6094   if (VT == MVT::v8i16) {
6095     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6096     if (NewOp.getNode())
6097       return NewOp;
6098   }
6099
6100   if (VT == MVT::v16i8) {
6101     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6102     if (NewOp.getNode())
6103       return NewOp;
6104   }
6105
6106   // Handle all 128-bit wide vectors with 4 elements, and match them with
6107   // several different shuffle types.
6108   if (NumElems == 4 && VT.getSizeInBits() == 128)
6109     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6110
6111   //===--------------------------------------------------------------------===//
6112   //  Custom lower or generate target specific nodes for 256-bit shuffles.
6113
6114   // Handle VPERMIL permutations
6115   if (isVPERMILMask(M, VT)) {
6116     unsigned TargetMask = getShuffleVPERMILImmediate(SVOp);
6117     if (VT == MVT::v8f32)
6118       return getTargetShuffleNode(X86ISD::VPERMIL, dl, VT, V1, TargetMask, DAG);
6119   }
6120
6121   // Handle general 256-bit shuffles
6122   if (VT.is256BitVector())
6123     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6124
6125   return SDValue();
6126 }
6127
6128 SDValue
6129 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6130                                                 SelectionDAG &DAG) const {
6131   EVT VT = Op.getValueType();
6132   DebugLoc dl = Op.getDebugLoc();
6133   if (VT.getSizeInBits() == 8) {
6134     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6135                                     Op.getOperand(0), Op.getOperand(1));
6136     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6137                                     DAG.getValueType(VT));
6138     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6139   } else if (VT.getSizeInBits() == 16) {
6140     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6141     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6142     if (Idx == 0)
6143       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6144                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6145                                      DAG.getNode(ISD::BITCAST, dl,
6146                                                  MVT::v4i32,
6147                                                  Op.getOperand(0)),
6148                                      Op.getOperand(1)));
6149     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6150                                     Op.getOperand(0), Op.getOperand(1));
6151     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6152                                     DAG.getValueType(VT));
6153     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6154   } else if (VT == MVT::f32) {
6155     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6156     // the result back to FR32 register. It's only worth matching if the
6157     // result has a single use which is a store or a bitcast to i32.  And in
6158     // the case of a store, it's not worth it if the index is a constant 0,
6159     // because a MOVSSmr can be used instead, which is smaller and faster.
6160     if (!Op.hasOneUse())
6161       return SDValue();
6162     SDNode *User = *Op.getNode()->use_begin();
6163     if ((User->getOpcode() != ISD::STORE ||
6164          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6165           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6166         (User->getOpcode() != ISD::BITCAST ||
6167          User->getValueType(0) != MVT::i32))
6168       return SDValue();
6169     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6170                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6171                                               Op.getOperand(0)),
6172                                               Op.getOperand(1));
6173     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6174   } else if (VT == MVT::i32) {
6175     // ExtractPS works with constant index.
6176     if (isa<ConstantSDNode>(Op.getOperand(1)))
6177       return Op;
6178   }
6179   return SDValue();
6180 }
6181
6182
6183 SDValue
6184 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6185                                            SelectionDAG &DAG) const {
6186   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6187     return SDValue();
6188
6189   SDValue Vec = Op.getOperand(0);
6190   EVT VecVT = Vec.getValueType();
6191
6192   // If this is a 256-bit vector result, first extract the 128-bit
6193   // vector and then extract from the 128-bit vector.
6194   if (VecVT.getSizeInBits() > 128) {
6195     DebugLoc dl = Op.getNode()->getDebugLoc();
6196     unsigned NumElems = VecVT.getVectorNumElements();
6197     SDValue Idx = Op.getOperand(1);
6198
6199     if (!isa<ConstantSDNode>(Idx))
6200       return SDValue();
6201
6202     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6203     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6204
6205     // Get the 128-bit vector.
6206     bool Upper = IdxVal >= ExtractNumElems;
6207     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6208
6209     // Extract from it.
6210     SDValue ScaledIdx = Idx;
6211     if (Upper)
6212       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6213                               DAG.getConstant(ExtractNumElems,
6214                                               Idx.getValueType()));
6215     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6216                        ScaledIdx);
6217   }
6218
6219   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6220
6221   if (Subtarget->hasSSE41()) {
6222     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6223     if (Res.getNode())
6224       return Res;
6225   }
6226
6227   EVT VT = Op.getValueType();
6228   DebugLoc dl = Op.getDebugLoc();
6229   // TODO: handle v16i8.
6230   if (VT.getSizeInBits() == 16) {
6231     SDValue Vec = Op.getOperand(0);
6232     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6233     if (Idx == 0)
6234       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6235                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6236                                      DAG.getNode(ISD::BITCAST, dl,
6237                                                  MVT::v4i32, Vec),
6238                                      Op.getOperand(1)));
6239     // Transform it so it match pextrw which produces a 32-bit result.
6240     EVT EltVT = MVT::i32;
6241     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6242                                     Op.getOperand(0), Op.getOperand(1));
6243     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6244                                     DAG.getValueType(VT));
6245     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6246   } else if (VT.getSizeInBits() == 32) {
6247     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6248     if (Idx == 0)
6249       return Op;
6250
6251     // SHUFPS the element to the lowest double word, then movss.
6252     int Mask[4] = { Idx, -1, -1, -1 };
6253     EVT VVT = Op.getOperand(0).getValueType();
6254     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6255                                        DAG.getUNDEF(VVT), Mask);
6256     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6257                        DAG.getIntPtrConstant(0));
6258   } else if (VT.getSizeInBits() == 64) {
6259     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6260     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6261     //        to match extract_elt for f64.
6262     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6263     if (Idx == 0)
6264       return Op;
6265
6266     // UNPCKHPD the element to the lowest double word, then movsd.
6267     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6268     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6269     int Mask[2] = { 1, -1 };
6270     EVT VVT = Op.getOperand(0).getValueType();
6271     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6272                                        DAG.getUNDEF(VVT), Mask);
6273     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6274                        DAG.getIntPtrConstant(0));
6275   }
6276
6277   return SDValue();
6278 }
6279
6280 SDValue
6281 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6282                                                SelectionDAG &DAG) const {
6283   EVT VT = Op.getValueType();
6284   EVT EltVT = VT.getVectorElementType();
6285   DebugLoc dl = Op.getDebugLoc();
6286
6287   SDValue N0 = Op.getOperand(0);
6288   SDValue N1 = Op.getOperand(1);
6289   SDValue N2 = Op.getOperand(2);
6290
6291   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6292       isa<ConstantSDNode>(N2)) {
6293     unsigned Opc;
6294     if (VT == MVT::v8i16)
6295       Opc = X86ISD::PINSRW;
6296     else if (VT == MVT::v16i8)
6297       Opc = X86ISD::PINSRB;
6298     else
6299       Opc = X86ISD::PINSRB;
6300
6301     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6302     // argument.
6303     if (N1.getValueType() != MVT::i32)
6304       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6305     if (N2.getValueType() != MVT::i32)
6306       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6307     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6308   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6309     // Bits [7:6] of the constant are the source select.  This will always be
6310     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6311     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6312     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6313     // Bits [5:4] of the constant are the destination select.  This is the
6314     //  value of the incoming immediate.
6315     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6316     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6317     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6318     // Create this as a scalar to vector..
6319     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6320     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6321   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6322     // PINSR* works with constant index.
6323     return Op;
6324   }
6325   return SDValue();
6326 }
6327
6328 SDValue
6329 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6330   EVT VT = Op.getValueType();
6331   EVT EltVT = VT.getVectorElementType();
6332
6333   DebugLoc dl = Op.getDebugLoc();
6334   SDValue N0 = Op.getOperand(0);
6335   SDValue N1 = Op.getOperand(1);
6336   SDValue N2 = Op.getOperand(2);
6337
6338   // If this is a 256-bit vector result, first insert into a 128-bit
6339   // vector and then insert into the 256-bit vector.
6340   if (VT.getSizeInBits() > 128) {
6341     if (!isa<ConstantSDNode>(N2))
6342       return SDValue();
6343
6344     // Get the 128-bit vector.
6345     unsigned NumElems = VT.getVectorNumElements();
6346     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6347     bool Upper = IdxVal >= NumElems / 2;
6348
6349     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6350
6351     // Insert into it.
6352     SDValue ScaledN2 = N2;
6353     if (Upper)
6354       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6355                              DAG.getConstant(NumElems /
6356                                              (VT.getSizeInBits() / 128),
6357                                              N2.getValueType()));
6358     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6359                      N1, ScaledN2);
6360
6361     // Insert the 128-bit vector
6362     // FIXME: Why UNDEF?
6363     return Insert128BitVector(N0, Op, N2, DAG, dl);
6364   }
6365
6366   if (Subtarget->hasSSE41())
6367     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6368
6369   if (EltVT == MVT::i8)
6370     return SDValue();
6371
6372   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6373     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6374     // as its second argument.
6375     if (N1.getValueType() != MVT::i32)
6376       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6377     if (N2.getValueType() != MVT::i32)
6378       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6379     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6380   }
6381   return SDValue();
6382 }
6383
6384 SDValue
6385 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6386   LLVMContext *Context = DAG.getContext();
6387   DebugLoc dl = Op.getDebugLoc();
6388   EVT OpVT = Op.getValueType();
6389
6390   // If this is a 256-bit vector result, first insert into a 128-bit
6391   // vector and then insert into the 256-bit vector.
6392   if (OpVT.getSizeInBits() > 128) {
6393     // Insert into a 128-bit vector.
6394     EVT VT128 = EVT::getVectorVT(*Context,
6395                                  OpVT.getVectorElementType(),
6396                                  OpVT.getVectorNumElements() / 2);
6397
6398     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6399
6400     // Insert the 128-bit vector.
6401     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6402                               DAG.getConstant(0, MVT::i32),
6403                               DAG, dl);
6404   }
6405
6406   if (Op.getValueType() == MVT::v1i64 &&
6407       Op.getOperand(0).getValueType() == MVT::i64)
6408     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6409
6410   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6411   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6412          "Expected an SSE type!");
6413   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6414                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6415 }
6416
6417 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6418 // a simple subregister reference or explicit instructions to grab
6419 // upper bits of a vector.
6420 SDValue
6421 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6422   if (Subtarget->hasAVX()) {
6423     DebugLoc dl = Op.getNode()->getDebugLoc();
6424     SDValue Vec = Op.getNode()->getOperand(0);
6425     SDValue Idx = Op.getNode()->getOperand(1);
6426
6427     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6428         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6429         return Extract128BitVector(Vec, Idx, DAG, dl);
6430     }
6431   }
6432   return SDValue();
6433 }
6434
6435 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6436 // simple superregister reference or explicit instructions to insert
6437 // the upper bits of a vector.
6438 SDValue
6439 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6440   if (Subtarget->hasAVX()) {
6441     DebugLoc dl = Op.getNode()->getDebugLoc();
6442     SDValue Vec = Op.getNode()->getOperand(0);
6443     SDValue SubVec = Op.getNode()->getOperand(1);
6444     SDValue Idx = Op.getNode()->getOperand(2);
6445
6446     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6447         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6448       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6449     }
6450   }
6451   return SDValue();
6452 }
6453
6454 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6455 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6456 // one of the above mentioned nodes. It has to be wrapped because otherwise
6457 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6458 // be used to form addressing mode. These wrapped nodes will be selected
6459 // into MOV32ri.
6460 SDValue
6461 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6462   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6463
6464   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6465   // global base reg.
6466   unsigned char OpFlag = 0;
6467   unsigned WrapperKind = X86ISD::Wrapper;
6468   CodeModel::Model M = getTargetMachine().getCodeModel();
6469
6470   if (Subtarget->isPICStyleRIPRel() &&
6471       (M == CodeModel::Small || M == CodeModel::Kernel))
6472     WrapperKind = X86ISD::WrapperRIP;
6473   else if (Subtarget->isPICStyleGOT())
6474     OpFlag = X86II::MO_GOTOFF;
6475   else if (Subtarget->isPICStyleStubPIC())
6476     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6477
6478   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6479                                              CP->getAlignment(),
6480                                              CP->getOffset(), OpFlag);
6481   DebugLoc DL = CP->getDebugLoc();
6482   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6483   // With PIC, the address is actually $g + Offset.
6484   if (OpFlag) {
6485     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6486                          DAG.getNode(X86ISD::GlobalBaseReg,
6487                                      DebugLoc(), getPointerTy()),
6488                          Result);
6489   }
6490
6491   return Result;
6492 }
6493
6494 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6495   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6496
6497   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6498   // global base reg.
6499   unsigned char OpFlag = 0;
6500   unsigned WrapperKind = X86ISD::Wrapper;
6501   CodeModel::Model M = getTargetMachine().getCodeModel();
6502
6503   if (Subtarget->isPICStyleRIPRel() &&
6504       (M == CodeModel::Small || M == CodeModel::Kernel))
6505     WrapperKind = X86ISD::WrapperRIP;
6506   else if (Subtarget->isPICStyleGOT())
6507     OpFlag = X86II::MO_GOTOFF;
6508   else if (Subtarget->isPICStyleStubPIC())
6509     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6510
6511   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6512                                           OpFlag);
6513   DebugLoc DL = JT->getDebugLoc();
6514   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6515
6516   // With PIC, the address is actually $g + Offset.
6517   if (OpFlag)
6518     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6519                          DAG.getNode(X86ISD::GlobalBaseReg,
6520                                      DebugLoc(), getPointerTy()),
6521                          Result);
6522
6523   return Result;
6524 }
6525
6526 SDValue
6527 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6528   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6529
6530   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6531   // global base reg.
6532   unsigned char OpFlag = 0;
6533   unsigned WrapperKind = X86ISD::Wrapper;
6534   CodeModel::Model M = getTargetMachine().getCodeModel();
6535
6536   if (Subtarget->isPICStyleRIPRel() &&
6537       (M == CodeModel::Small || M == CodeModel::Kernel))
6538     WrapperKind = X86ISD::WrapperRIP;
6539   else if (Subtarget->isPICStyleGOT())
6540     OpFlag = X86II::MO_GOTOFF;
6541   else if (Subtarget->isPICStyleStubPIC())
6542     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6543
6544   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6545
6546   DebugLoc DL = Op.getDebugLoc();
6547   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6548
6549
6550   // With PIC, the address is actually $g + Offset.
6551   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6552       !Subtarget->is64Bit()) {
6553     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6554                          DAG.getNode(X86ISD::GlobalBaseReg,
6555                                      DebugLoc(), getPointerTy()),
6556                          Result);
6557   }
6558
6559   return Result;
6560 }
6561
6562 SDValue
6563 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6564   // Create the TargetBlockAddressAddress node.
6565   unsigned char OpFlags =
6566     Subtarget->ClassifyBlockAddressReference();
6567   CodeModel::Model M = getTargetMachine().getCodeModel();
6568   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6569   DebugLoc dl = Op.getDebugLoc();
6570   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6571                                        /*isTarget=*/true, OpFlags);
6572
6573   if (Subtarget->isPICStyleRIPRel() &&
6574       (M == CodeModel::Small || M == CodeModel::Kernel))
6575     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6576   else
6577     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6578
6579   // With PIC, the address is actually $g + Offset.
6580   if (isGlobalRelativeToPICBase(OpFlags)) {
6581     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6582                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6583                          Result);
6584   }
6585
6586   return Result;
6587 }
6588
6589 SDValue
6590 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6591                                       int64_t Offset,
6592                                       SelectionDAG &DAG) const {
6593   // Create the TargetGlobalAddress node, folding in the constant
6594   // offset if it is legal.
6595   unsigned char OpFlags =
6596     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6597   CodeModel::Model M = getTargetMachine().getCodeModel();
6598   SDValue Result;
6599   if (OpFlags == X86II::MO_NO_FLAG &&
6600       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6601     // A direct static reference to a global.
6602     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6603     Offset = 0;
6604   } else {
6605     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6606   }
6607
6608   if (Subtarget->isPICStyleRIPRel() &&
6609       (M == CodeModel::Small || M == CodeModel::Kernel))
6610     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6611   else
6612     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6613
6614   // With PIC, the address is actually $g + Offset.
6615   if (isGlobalRelativeToPICBase(OpFlags)) {
6616     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6617                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6618                          Result);
6619   }
6620
6621   // For globals that require a load from a stub to get the address, emit the
6622   // load.
6623   if (isGlobalStubReference(OpFlags))
6624     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6625                          MachinePointerInfo::getGOT(), false, false, 0);
6626
6627   // If there was a non-zero offset that we didn't fold, create an explicit
6628   // addition for it.
6629   if (Offset != 0)
6630     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6631                          DAG.getConstant(Offset, getPointerTy()));
6632
6633   return Result;
6634 }
6635
6636 SDValue
6637 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6638   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6639   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6640   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6641 }
6642
6643 static SDValue
6644 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6645            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6646            unsigned char OperandFlags) {
6647   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6648   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6649   DebugLoc dl = GA->getDebugLoc();
6650   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6651                                            GA->getValueType(0),
6652                                            GA->getOffset(),
6653                                            OperandFlags);
6654   if (InFlag) {
6655     SDValue Ops[] = { Chain,  TGA, *InFlag };
6656     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6657   } else {
6658     SDValue Ops[]  = { Chain, TGA };
6659     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6660   }
6661
6662   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6663   MFI->setAdjustsStack(true);
6664
6665   SDValue Flag = Chain.getValue(1);
6666   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6667 }
6668
6669 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6670 static SDValue
6671 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6672                                 const EVT PtrVT) {
6673   SDValue InFlag;
6674   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6675   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6676                                      DAG.getNode(X86ISD::GlobalBaseReg,
6677                                                  DebugLoc(), PtrVT), InFlag);
6678   InFlag = Chain.getValue(1);
6679
6680   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6681 }
6682
6683 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6684 static SDValue
6685 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6686                                 const EVT PtrVT) {
6687   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6688                     X86::RAX, X86II::MO_TLSGD);
6689 }
6690
6691 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6692 // "local exec" model.
6693 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6694                                    const EVT PtrVT, TLSModel::Model model,
6695                                    bool is64Bit) {
6696   DebugLoc dl = GA->getDebugLoc();
6697
6698   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6699   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6700                                                          is64Bit ? 257 : 256));
6701
6702   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6703                                       DAG.getIntPtrConstant(0),
6704                                       MachinePointerInfo(Ptr), false, false, 0);
6705
6706   unsigned char OperandFlags = 0;
6707   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6708   // initialexec.
6709   unsigned WrapperKind = X86ISD::Wrapper;
6710   if (model == TLSModel::LocalExec) {
6711     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6712   } else if (is64Bit) {
6713     assert(model == TLSModel::InitialExec);
6714     OperandFlags = X86II::MO_GOTTPOFF;
6715     WrapperKind = X86ISD::WrapperRIP;
6716   } else {
6717     assert(model == TLSModel::InitialExec);
6718     OperandFlags = X86II::MO_INDNTPOFF;
6719   }
6720
6721   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6722   // exec)
6723   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6724                                            GA->getValueType(0),
6725                                            GA->getOffset(), OperandFlags);
6726   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6727
6728   if (model == TLSModel::InitialExec)
6729     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6730                          MachinePointerInfo::getGOT(), false, false, 0);
6731
6732   // The address of the thread local variable is the add of the thread
6733   // pointer with the offset of the variable.
6734   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6735 }
6736
6737 SDValue
6738 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6739
6740   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6741   const GlobalValue *GV = GA->getGlobal();
6742
6743   if (Subtarget->isTargetELF()) {
6744     // TODO: implement the "local dynamic" model
6745     // TODO: implement the "initial exec"model for pic executables
6746
6747     // If GV is an alias then use the aliasee for determining
6748     // thread-localness.
6749     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6750       GV = GA->resolveAliasedGlobal(false);
6751
6752     TLSModel::Model model
6753       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6754
6755     switch (model) {
6756       case TLSModel::GeneralDynamic:
6757       case TLSModel::LocalDynamic: // not implemented
6758         if (Subtarget->is64Bit())
6759           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6760         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6761
6762       case TLSModel::InitialExec:
6763       case TLSModel::LocalExec:
6764         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6765                                    Subtarget->is64Bit());
6766     }
6767   } else if (Subtarget->isTargetDarwin()) {
6768     // Darwin only has one model of TLS.  Lower to that.
6769     unsigned char OpFlag = 0;
6770     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6771                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6772
6773     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6774     // global base reg.
6775     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6776                   !Subtarget->is64Bit();
6777     if (PIC32)
6778       OpFlag = X86II::MO_TLVP_PIC_BASE;
6779     else
6780       OpFlag = X86II::MO_TLVP;
6781     DebugLoc DL = Op.getDebugLoc();
6782     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6783                                                 GA->getValueType(0),
6784                                                 GA->getOffset(), OpFlag);
6785     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6786
6787     // With PIC32, the address is actually $g + Offset.
6788     if (PIC32)
6789       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6790                            DAG.getNode(X86ISD::GlobalBaseReg,
6791                                        DebugLoc(), getPointerTy()),
6792                            Offset);
6793
6794     // Lowering the machine isd will make sure everything is in the right
6795     // location.
6796     SDValue Chain = DAG.getEntryNode();
6797     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6798     SDValue Args[] = { Chain, Offset };
6799     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6800
6801     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6802     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6803     MFI->setAdjustsStack(true);
6804
6805     // And our return value (tls address) is in the standard call return value
6806     // location.
6807     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6808     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6809   }
6810
6811   assert(false &&
6812          "TLS not implemented for this target.");
6813
6814   llvm_unreachable("Unreachable");
6815   return SDValue();
6816 }
6817
6818
6819 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6820 /// take a 2 x i32 value to shift plus a shift amount.
6821 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6822   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6823   EVT VT = Op.getValueType();
6824   unsigned VTBits = VT.getSizeInBits();
6825   DebugLoc dl = Op.getDebugLoc();
6826   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6827   SDValue ShOpLo = Op.getOperand(0);
6828   SDValue ShOpHi = Op.getOperand(1);
6829   SDValue ShAmt  = Op.getOperand(2);
6830   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6831                                      DAG.getConstant(VTBits - 1, MVT::i8))
6832                        : DAG.getConstant(0, VT);
6833
6834   SDValue Tmp2, Tmp3;
6835   if (Op.getOpcode() == ISD::SHL_PARTS) {
6836     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6837     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6838   } else {
6839     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6840     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6841   }
6842
6843   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6844                                 DAG.getConstant(VTBits, MVT::i8));
6845   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6846                              AndNode, DAG.getConstant(0, MVT::i8));
6847
6848   SDValue Hi, Lo;
6849   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6850   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6851   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6852
6853   if (Op.getOpcode() == ISD::SHL_PARTS) {
6854     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6855     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6856   } else {
6857     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6858     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6859   }
6860
6861   SDValue Ops[2] = { Lo, Hi };
6862   return DAG.getMergeValues(Ops, 2, dl);
6863 }
6864
6865 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6866                                            SelectionDAG &DAG) const {
6867   EVT SrcVT = Op.getOperand(0).getValueType();
6868
6869   if (SrcVT.isVector())
6870     return SDValue();
6871
6872   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6873          "Unknown SINT_TO_FP to lower!");
6874
6875   // These are really Legal; return the operand so the caller accepts it as
6876   // Legal.
6877   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6878     return Op;
6879   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6880       Subtarget->is64Bit()) {
6881     return Op;
6882   }
6883
6884   DebugLoc dl = Op.getDebugLoc();
6885   unsigned Size = SrcVT.getSizeInBits()/8;
6886   MachineFunction &MF = DAG.getMachineFunction();
6887   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6888   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6889   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6890                                StackSlot,
6891                                MachinePointerInfo::getFixedStack(SSFI),
6892                                false, false, 0);
6893   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6894 }
6895
6896 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6897                                      SDValue StackSlot,
6898                                      SelectionDAG &DAG) const {
6899   // Build the FILD
6900   DebugLoc DL = Op.getDebugLoc();
6901   SDVTList Tys;
6902   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6903   if (useSSE)
6904     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6905   else
6906     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6907
6908   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6909
6910   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6911   MachineMemOperand *MMO;
6912   if (FI) {
6913     int SSFI = FI->getIndex();
6914     MMO =
6915       DAG.getMachineFunction()
6916       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6917                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6918   } else {
6919     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6920     StackSlot = StackSlot.getOperand(1);
6921   }
6922   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6923   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6924                                            X86ISD::FILD, DL,
6925                                            Tys, Ops, array_lengthof(Ops),
6926                                            SrcVT, MMO);
6927
6928   if (useSSE) {
6929     Chain = Result.getValue(1);
6930     SDValue InFlag = Result.getValue(2);
6931
6932     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6933     // shouldn't be necessary except that RFP cannot be live across
6934     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6935     MachineFunction &MF = DAG.getMachineFunction();
6936     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6937     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6938     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6939     Tys = DAG.getVTList(MVT::Other);
6940     SDValue Ops[] = {
6941       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6942     };
6943     MachineMemOperand *MMO =
6944       DAG.getMachineFunction()
6945       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6946                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6947
6948     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6949                                     Ops, array_lengthof(Ops),
6950                                     Op.getValueType(), MMO);
6951     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6952                          MachinePointerInfo::getFixedStack(SSFI),
6953                          false, false, 0);
6954   }
6955
6956   return Result;
6957 }
6958
6959 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6960 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6961                                                SelectionDAG &DAG) const {
6962   // This algorithm is not obvious. Here it is in C code, more or less:
6963   /*
6964     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6965       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6966       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6967
6968       // Copy ints to xmm registers.
6969       __m128i xh = _mm_cvtsi32_si128( hi );
6970       __m128i xl = _mm_cvtsi32_si128( lo );
6971
6972       // Combine into low half of a single xmm register.
6973       __m128i x = _mm_unpacklo_epi32( xh, xl );
6974       __m128d d;
6975       double sd;
6976
6977       // Merge in appropriate exponents to give the integer bits the right
6978       // magnitude.
6979       x = _mm_unpacklo_epi32( x, exp );
6980
6981       // Subtract away the biases to deal with the IEEE-754 double precision
6982       // implicit 1.
6983       d = _mm_sub_pd( (__m128d) x, bias );
6984
6985       // All conversions up to here are exact. The correctly rounded result is
6986       // calculated using the current rounding mode using the following
6987       // horizontal add.
6988       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6989       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6990                                 // store doesn't really need to be here (except
6991                                 // maybe to zero the other double)
6992       return sd;
6993     }
6994   */
6995
6996   DebugLoc dl = Op.getDebugLoc();
6997   LLVMContext *Context = DAG.getContext();
6998
6999   // Build some magic constants.
7000   std::vector<Constant*> CV0;
7001   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7002   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7003   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7004   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7005   Constant *C0 = ConstantVector::get(CV0);
7006   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7007
7008   std::vector<Constant*> CV1;
7009   CV1.push_back(
7010     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7011   CV1.push_back(
7012     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7013   Constant *C1 = ConstantVector::get(CV1);
7014   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7015
7016   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7017                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7018                                         Op.getOperand(0),
7019                                         DAG.getIntPtrConstant(1)));
7020   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7021                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7022                                         Op.getOperand(0),
7023                                         DAG.getIntPtrConstant(0)));
7024   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7025   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7026                               MachinePointerInfo::getConstantPool(),
7027                               false, false, 16);
7028   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7029   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7030   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7031                               MachinePointerInfo::getConstantPool(),
7032                               false, false, 16);
7033   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7034
7035   // Add the halves; easiest way is to swap them into another reg first.
7036   int ShufMask[2] = { 1, -1 };
7037   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7038                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7039   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7040   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7041                      DAG.getIntPtrConstant(0));
7042 }
7043
7044 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7045 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7046                                                SelectionDAG &DAG) const {
7047   DebugLoc dl = Op.getDebugLoc();
7048   // FP constant to bias correct the final result.
7049   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7050                                    MVT::f64);
7051
7052   // Load the 32-bit value into an XMM register.
7053   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7054                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7055                                          Op.getOperand(0),
7056                                          DAG.getIntPtrConstant(0)));
7057
7058   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7059                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7060                      DAG.getIntPtrConstant(0));
7061
7062   // Or the load with the bias.
7063   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7064                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7065                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7066                                                    MVT::v2f64, Load)),
7067                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7068                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7069                                                    MVT::v2f64, Bias)));
7070   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7071                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7072                    DAG.getIntPtrConstant(0));
7073
7074   // Subtract the bias.
7075   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7076
7077   // Handle final rounding.
7078   EVT DestVT = Op.getValueType();
7079
7080   if (DestVT.bitsLT(MVT::f64)) {
7081     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7082                        DAG.getIntPtrConstant(0));
7083   } else if (DestVT.bitsGT(MVT::f64)) {
7084     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7085   }
7086
7087   // Handle final rounding.
7088   return Sub;
7089 }
7090
7091 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7092                                            SelectionDAG &DAG) const {
7093   SDValue N0 = Op.getOperand(0);
7094   DebugLoc dl = Op.getDebugLoc();
7095
7096   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7097   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7098   // the optimization here.
7099   if (DAG.SignBitIsZero(N0))
7100     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7101
7102   EVT SrcVT = N0.getValueType();
7103   EVT DstVT = Op.getValueType();
7104   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7105     return LowerUINT_TO_FP_i64(Op, DAG);
7106   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7107     return LowerUINT_TO_FP_i32(Op, DAG);
7108
7109   // Make a 64-bit buffer, and use it to build an FILD.
7110   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7111   if (SrcVT == MVT::i32) {
7112     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7113     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7114                                      getPointerTy(), StackSlot, WordOff);
7115     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7116                                   StackSlot, MachinePointerInfo(),
7117                                   false, false, 0);
7118     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7119                                   OffsetSlot, MachinePointerInfo(),
7120                                   false, false, 0);
7121     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7122     return Fild;
7123   }
7124
7125   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7126   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7127                                 StackSlot, MachinePointerInfo(),
7128                                false, false, 0);
7129   // For i64 source, we need to add the appropriate power of 2 if the input
7130   // was negative.  This is the same as the optimization in
7131   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7132   // we must be careful to do the computation in x87 extended precision, not
7133   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7134   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7135   MachineMemOperand *MMO =
7136     DAG.getMachineFunction()
7137     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7138                           MachineMemOperand::MOLoad, 8, 8);
7139
7140   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7141   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7142   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7143                                          MVT::i64, MMO);
7144
7145   APInt FF(32, 0x5F800000ULL);
7146
7147   // Check whether the sign bit is set.
7148   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7149                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7150                                  ISD::SETLT);
7151
7152   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7153   SDValue FudgePtr = DAG.getConstantPool(
7154                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7155                                          getPointerTy());
7156
7157   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7158   SDValue Zero = DAG.getIntPtrConstant(0);
7159   SDValue Four = DAG.getIntPtrConstant(4);
7160   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7161                                Zero, Four);
7162   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7163
7164   // Load the value out, extending it from f32 to f80.
7165   // FIXME: Avoid the extend by constructing the right constant pool?
7166   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7167                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7168                                  MVT::f32, false, false, 4);
7169   // Extend everything to 80 bits to force it to be done on x87.
7170   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7171   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7172 }
7173
7174 std::pair<SDValue,SDValue> X86TargetLowering::
7175 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7176   DebugLoc DL = Op.getDebugLoc();
7177
7178   EVT DstTy = Op.getValueType();
7179
7180   if (!IsSigned) {
7181     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7182     DstTy = MVT::i64;
7183   }
7184
7185   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7186          DstTy.getSimpleVT() >= MVT::i16 &&
7187          "Unknown FP_TO_SINT to lower!");
7188
7189   // These are really Legal.
7190   if (DstTy == MVT::i32 &&
7191       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7192     return std::make_pair(SDValue(), SDValue());
7193   if (Subtarget->is64Bit() &&
7194       DstTy == MVT::i64 &&
7195       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7196     return std::make_pair(SDValue(), SDValue());
7197
7198   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7199   // stack slot.
7200   MachineFunction &MF = DAG.getMachineFunction();
7201   unsigned MemSize = DstTy.getSizeInBits()/8;
7202   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7203   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7204
7205
7206
7207   unsigned Opc;
7208   switch (DstTy.getSimpleVT().SimpleTy) {
7209   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7210   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7211   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7212   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7213   }
7214
7215   SDValue Chain = DAG.getEntryNode();
7216   SDValue Value = Op.getOperand(0);
7217   EVT TheVT = Op.getOperand(0).getValueType();
7218   if (isScalarFPTypeInSSEReg(TheVT)) {
7219     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7220     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7221                          MachinePointerInfo::getFixedStack(SSFI),
7222                          false, false, 0);
7223     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7224     SDValue Ops[] = {
7225       Chain, StackSlot, DAG.getValueType(TheVT)
7226     };
7227
7228     MachineMemOperand *MMO =
7229       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7230                               MachineMemOperand::MOLoad, MemSize, MemSize);
7231     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7232                                     DstTy, MMO);
7233     Chain = Value.getValue(1);
7234     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7235     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7236   }
7237
7238   MachineMemOperand *MMO =
7239     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7240                             MachineMemOperand::MOStore, MemSize, MemSize);
7241
7242   // Build the FP_TO_INT*_IN_MEM
7243   SDValue Ops[] = { Chain, Value, StackSlot };
7244   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7245                                          Ops, 3, DstTy, MMO);
7246
7247   return std::make_pair(FIST, StackSlot);
7248 }
7249
7250 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7251                                            SelectionDAG &DAG) const {
7252   if (Op.getValueType().isVector())
7253     return SDValue();
7254
7255   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7256   SDValue FIST = Vals.first, StackSlot = Vals.second;
7257   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7258   if (FIST.getNode() == 0) return Op;
7259
7260   // Load the result.
7261   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7262                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7263 }
7264
7265 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7266                                            SelectionDAG &DAG) const {
7267   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7268   SDValue FIST = Vals.first, StackSlot = Vals.second;
7269   assert(FIST.getNode() && "Unexpected failure");
7270
7271   // Load the result.
7272   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7273                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7274 }
7275
7276 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7277                                      SelectionDAG &DAG) const {
7278   LLVMContext *Context = DAG.getContext();
7279   DebugLoc dl = Op.getDebugLoc();
7280   EVT VT = Op.getValueType();
7281   EVT EltVT = VT;
7282   if (VT.isVector())
7283     EltVT = VT.getVectorElementType();
7284   std::vector<Constant*> CV;
7285   if (EltVT == MVT::f64) {
7286     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7287     CV.push_back(C);
7288     CV.push_back(C);
7289   } else {
7290     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7291     CV.push_back(C);
7292     CV.push_back(C);
7293     CV.push_back(C);
7294     CV.push_back(C);
7295   }
7296   Constant *C = ConstantVector::get(CV);
7297   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7298   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7299                              MachinePointerInfo::getConstantPool(),
7300                              false, false, 16);
7301   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7302 }
7303
7304 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7305   LLVMContext *Context = DAG.getContext();
7306   DebugLoc dl = Op.getDebugLoc();
7307   EVT VT = Op.getValueType();
7308   EVT EltVT = VT;
7309   if (VT.isVector())
7310     EltVT = VT.getVectorElementType();
7311   std::vector<Constant*> CV;
7312   if (EltVT == MVT::f64) {
7313     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7314     CV.push_back(C);
7315     CV.push_back(C);
7316   } else {
7317     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7318     CV.push_back(C);
7319     CV.push_back(C);
7320     CV.push_back(C);
7321     CV.push_back(C);
7322   }
7323   Constant *C = ConstantVector::get(CV);
7324   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7325   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7326                              MachinePointerInfo::getConstantPool(),
7327                              false, false, 16);
7328   if (VT.isVector()) {
7329     return DAG.getNode(ISD::BITCAST, dl, VT,
7330                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7331                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7332                                 Op.getOperand(0)),
7333                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7334   } else {
7335     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7336   }
7337 }
7338
7339 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7340   LLVMContext *Context = DAG.getContext();
7341   SDValue Op0 = Op.getOperand(0);
7342   SDValue Op1 = Op.getOperand(1);
7343   DebugLoc dl = Op.getDebugLoc();
7344   EVT VT = Op.getValueType();
7345   EVT SrcVT = Op1.getValueType();
7346
7347   // If second operand is smaller, extend it first.
7348   if (SrcVT.bitsLT(VT)) {
7349     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7350     SrcVT = VT;
7351   }
7352   // And if it is bigger, shrink it first.
7353   if (SrcVT.bitsGT(VT)) {
7354     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7355     SrcVT = VT;
7356   }
7357
7358   // At this point the operands and the result should have the same
7359   // type, and that won't be f80 since that is not custom lowered.
7360
7361   // First get the sign bit of second operand.
7362   std::vector<Constant*> CV;
7363   if (SrcVT == MVT::f64) {
7364     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7365     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7366   } else {
7367     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7368     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7369     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7370     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7371   }
7372   Constant *C = ConstantVector::get(CV);
7373   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7374   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7375                               MachinePointerInfo::getConstantPool(),
7376                               false, false, 16);
7377   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7378
7379   // Shift sign bit right or left if the two operands have different types.
7380   if (SrcVT.bitsGT(VT)) {
7381     // Op0 is MVT::f32, Op1 is MVT::f64.
7382     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7383     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7384                           DAG.getConstant(32, MVT::i32));
7385     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7386     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7387                           DAG.getIntPtrConstant(0));
7388   }
7389
7390   // Clear first operand sign bit.
7391   CV.clear();
7392   if (VT == MVT::f64) {
7393     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7394     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7395   } else {
7396     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7397     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7398     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7399     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7400   }
7401   C = ConstantVector::get(CV);
7402   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7403   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7404                               MachinePointerInfo::getConstantPool(),
7405                               false, false, 16);
7406   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7407
7408   // Or the value with the sign bit.
7409   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7410 }
7411
7412 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7413   SDValue N0 = Op.getOperand(0);
7414   DebugLoc dl = Op.getDebugLoc();
7415   EVT VT = Op.getValueType();
7416
7417   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7418   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7419                                   DAG.getConstant(1, VT));
7420   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7421 }
7422
7423 /// Emit nodes that will be selected as "test Op0,Op0", or something
7424 /// equivalent.
7425 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7426                                     SelectionDAG &DAG) const {
7427   DebugLoc dl = Op.getDebugLoc();
7428
7429   // CF and OF aren't always set the way we want. Determine which
7430   // of these we need.
7431   bool NeedCF = false;
7432   bool NeedOF = false;
7433   switch (X86CC) {
7434   default: break;
7435   case X86::COND_A: case X86::COND_AE:
7436   case X86::COND_B: case X86::COND_BE:
7437     NeedCF = true;
7438     break;
7439   case X86::COND_G: case X86::COND_GE:
7440   case X86::COND_L: case X86::COND_LE:
7441   case X86::COND_O: case X86::COND_NO:
7442     NeedOF = true;
7443     break;
7444   }
7445
7446   // See if we can use the EFLAGS value from the operand instead of
7447   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7448   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7449   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7450     // Emit a CMP with 0, which is the TEST pattern.
7451     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7452                        DAG.getConstant(0, Op.getValueType()));
7453
7454   unsigned Opcode = 0;
7455   unsigned NumOperands = 0;
7456   switch (Op.getNode()->getOpcode()) {
7457   case ISD::ADD:
7458     // Due to an isel shortcoming, be conservative if this add is likely to be
7459     // selected as part of a load-modify-store instruction. When the root node
7460     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7461     // uses of other nodes in the match, such as the ADD in this case. This
7462     // leads to the ADD being left around and reselected, with the result being
7463     // two adds in the output.  Alas, even if none our users are stores, that
7464     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7465     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7466     // climbing the DAG back to the root, and it doesn't seem to be worth the
7467     // effort.
7468     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7469            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7470       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7471         goto default_case;
7472
7473     if (ConstantSDNode *C =
7474         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7475       // An add of one will be selected as an INC.
7476       if (C->getAPIntValue() == 1) {
7477         Opcode = X86ISD::INC;
7478         NumOperands = 1;
7479         break;
7480       }
7481
7482       // An add of negative one (subtract of one) will be selected as a DEC.
7483       if (C->getAPIntValue().isAllOnesValue()) {
7484         Opcode = X86ISD::DEC;
7485         NumOperands = 1;
7486         break;
7487       }
7488     }
7489
7490     // Otherwise use a regular EFLAGS-setting add.
7491     Opcode = X86ISD::ADD;
7492     NumOperands = 2;
7493     break;
7494   case ISD::AND: {
7495     // If the primary and result isn't used, don't bother using X86ISD::AND,
7496     // because a TEST instruction will be better.
7497     bool NonFlagUse = false;
7498     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7499            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7500       SDNode *User = *UI;
7501       unsigned UOpNo = UI.getOperandNo();
7502       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7503         // Look pass truncate.
7504         UOpNo = User->use_begin().getOperandNo();
7505         User = *User->use_begin();
7506       }
7507
7508       if (User->getOpcode() != ISD::BRCOND &&
7509           User->getOpcode() != ISD::SETCC &&
7510           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7511         NonFlagUse = true;
7512         break;
7513       }
7514     }
7515
7516     if (!NonFlagUse)
7517       break;
7518   }
7519     // FALL THROUGH
7520   case ISD::SUB:
7521   case ISD::OR:
7522   case ISD::XOR:
7523     // Due to the ISEL shortcoming noted above, be conservative if this op is
7524     // likely to be selected as part of a load-modify-store instruction.
7525     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7526            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7527       if (UI->getOpcode() == ISD::STORE)
7528         goto default_case;
7529
7530     // Otherwise use a regular EFLAGS-setting instruction.
7531     switch (Op.getNode()->getOpcode()) {
7532     default: llvm_unreachable("unexpected operator!");
7533     case ISD::SUB: Opcode = X86ISD::SUB; break;
7534     case ISD::OR:  Opcode = X86ISD::OR;  break;
7535     case ISD::XOR: Opcode = X86ISD::XOR; break;
7536     case ISD::AND: Opcode = X86ISD::AND; break;
7537     }
7538
7539     NumOperands = 2;
7540     break;
7541   case X86ISD::ADD:
7542   case X86ISD::SUB:
7543   case X86ISD::INC:
7544   case X86ISD::DEC:
7545   case X86ISD::OR:
7546   case X86ISD::XOR:
7547   case X86ISD::AND:
7548     return SDValue(Op.getNode(), 1);
7549   default:
7550   default_case:
7551     break;
7552   }
7553
7554   if (Opcode == 0)
7555     // Emit a CMP with 0, which is the TEST pattern.
7556     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7557                        DAG.getConstant(0, Op.getValueType()));
7558
7559   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7560   SmallVector<SDValue, 4> Ops;
7561   for (unsigned i = 0; i != NumOperands; ++i)
7562     Ops.push_back(Op.getOperand(i));
7563
7564   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7565   DAG.ReplaceAllUsesWith(Op, New);
7566   return SDValue(New.getNode(), 1);
7567 }
7568
7569 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7570 /// equivalent.
7571 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7572                                    SelectionDAG &DAG) const {
7573   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7574     if (C->getAPIntValue() == 0)
7575       return EmitTest(Op0, X86CC, DAG);
7576
7577   DebugLoc dl = Op0.getDebugLoc();
7578   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7579 }
7580
7581 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7582 /// if it's possible.
7583 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7584                                      DebugLoc dl, SelectionDAG &DAG) const {
7585   SDValue Op0 = And.getOperand(0);
7586   SDValue Op1 = And.getOperand(1);
7587   if (Op0.getOpcode() == ISD::TRUNCATE)
7588     Op0 = Op0.getOperand(0);
7589   if (Op1.getOpcode() == ISD::TRUNCATE)
7590     Op1 = Op1.getOperand(0);
7591
7592   SDValue LHS, RHS;
7593   if (Op1.getOpcode() == ISD::SHL)
7594     std::swap(Op0, Op1);
7595   if (Op0.getOpcode() == ISD::SHL) {
7596     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7597       if (And00C->getZExtValue() == 1) {
7598         // If we looked past a truncate, check that it's only truncating away
7599         // known zeros.
7600         unsigned BitWidth = Op0.getValueSizeInBits();
7601         unsigned AndBitWidth = And.getValueSizeInBits();
7602         if (BitWidth > AndBitWidth) {
7603           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7604           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7605           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7606             return SDValue();
7607         }
7608         LHS = Op1;
7609         RHS = Op0.getOperand(1);
7610       }
7611   } else if (Op1.getOpcode() == ISD::Constant) {
7612     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7613     SDValue AndLHS = Op0;
7614     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7615       LHS = AndLHS.getOperand(0);
7616       RHS = AndLHS.getOperand(1);
7617     }
7618   }
7619
7620   if (LHS.getNode()) {
7621     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7622     // instruction.  Since the shift amount is in-range-or-undefined, we know
7623     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7624     // the encoding for the i16 version is larger than the i32 version.
7625     // Also promote i16 to i32 for performance / code size reason.
7626     if (LHS.getValueType() == MVT::i8 ||
7627         LHS.getValueType() == MVT::i16)
7628       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7629
7630     // If the operand types disagree, extend the shift amount to match.  Since
7631     // BT ignores high bits (like shifts) we can use anyextend.
7632     if (LHS.getValueType() != RHS.getValueType())
7633       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7634
7635     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7636     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7637     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7638                        DAG.getConstant(Cond, MVT::i8), BT);
7639   }
7640
7641   return SDValue();
7642 }
7643
7644 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7645   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7646   SDValue Op0 = Op.getOperand(0);
7647   SDValue Op1 = Op.getOperand(1);
7648   DebugLoc dl = Op.getDebugLoc();
7649   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7650
7651   // Optimize to BT if possible.
7652   // Lower (X & (1 << N)) == 0 to BT(X, N).
7653   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7654   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7655   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7656       Op1.getOpcode() == ISD::Constant &&
7657       cast<ConstantSDNode>(Op1)->isNullValue() &&
7658       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7659     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7660     if (NewSetCC.getNode())
7661       return NewSetCC;
7662   }
7663
7664   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7665   // these.
7666   if (Op1.getOpcode() == ISD::Constant &&
7667       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7668        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7669       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7670
7671     // If the input is a setcc, then reuse the input setcc or use a new one with
7672     // the inverted condition.
7673     if (Op0.getOpcode() == X86ISD::SETCC) {
7674       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7675       bool Invert = (CC == ISD::SETNE) ^
7676         cast<ConstantSDNode>(Op1)->isNullValue();
7677       if (!Invert) return Op0;
7678
7679       CCode = X86::GetOppositeBranchCondition(CCode);
7680       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7681                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7682     }
7683   }
7684
7685   bool isFP = Op1.getValueType().isFloatingPoint();
7686   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7687   if (X86CC == X86::COND_INVALID)
7688     return SDValue();
7689
7690   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7691   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7692                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7693 }
7694
7695 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7696   SDValue Cond;
7697   SDValue Op0 = Op.getOperand(0);
7698   SDValue Op1 = Op.getOperand(1);
7699   SDValue CC = Op.getOperand(2);
7700   EVT VT = Op.getValueType();
7701   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7702   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7703   DebugLoc dl = Op.getDebugLoc();
7704
7705   if (isFP) {
7706     unsigned SSECC = 8;
7707     EVT VT0 = Op0.getValueType();
7708     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7709     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7710     bool Swap = false;
7711
7712     switch (SetCCOpcode) {
7713     default: break;
7714     case ISD::SETOEQ:
7715     case ISD::SETEQ:  SSECC = 0; break;
7716     case ISD::SETOGT:
7717     case ISD::SETGT: Swap = true; // Fallthrough
7718     case ISD::SETLT:
7719     case ISD::SETOLT: SSECC = 1; break;
7720     case ISD::SETOGE:
7721     case ISD::SETGE: Swap = true; // Fallthrough
7722     case ISD::SETLE:
7723     case ISD::SETOLE: SSECC = 2; break;
7724     case ISD::SETUO:  SSECC = 3; break;
7725     case ISD::SETUNE:
7726     case ISD::SETNE:  SSECC = 4; break;
7727     case ISD::SETULE: Swap = true;
7728     case ISD::SETUGE: SSECC = 5; break;
7729     case ISD::SETULT: Swap = true;
7730     case ISD::SETUGT: SSECC = 6; break;
7731     case ISD::SETO:   SSECC = 7; break;
7732     }
7733     if (Swap)
7734       std::swap(Op0, Op1);
7735
7736     // In the two special cases we can't handle, emit two comparisons.
7737     if (SSECC == 8) {
7738       if (SetCCOpcode == ISD::SETUEQ) {
7739         SDValue UNORD, EQ;
7740         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7741         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7742         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7743       }
7744       else if (SetCCOpcode == ISD::SETONE) {
7745         SDValue ORD, NEQ;
7746         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7747         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7748         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7749       }
7750       llvm_unreachable("Illegal FP comparison");
7751     }
7752     // Handle all other FP comparisons here.
7753     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7754   }
7755
7756   // We are handling one of the integer comparisons here.  Since SSE only has
7757   // GT and EQ comparisons for integer, swapping operands and multiple
7758   // operations may be required for some comparisons.
7759   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7760   bool Swap = false, Invert = false, FlipSigns = false;
7761
7762   switch (VT.getSimpleVT().SimpleTy) {
7763   default: break;
7764   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7765   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7766   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7767   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7768   }
7769
7770   switch (SetCCOpcode) {
7771   default: break;
7772   case ISD::SETNE:  Invert = true;
7773   case ISD::SETEQ:  Opc = EQOpc; break;
7774   case ISD::SETLT:  Swap = true;
7775   case ISD::SETGT:  Opc = GTOpc; break;
7776   case ISD::SETGE:  Swap = true;
7777   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7778   case ISD::SETULT: Swap = true;
7779   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7780   case ISD::SETUGE: Swap = true;
7781   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7782   }
7783   if (Swap)
7784     std::swap(Op0, Op1);
7785
7786   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7787   // bits of the inputs before performing those operations.
7788   if (FlipSigns) {
7789     EVT EltVT = VT.getVectorElementType();
7790     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7791                                       EltVT);
7792     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7793     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7794                                     SignBits.size());
7795     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7796     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7797   }
7798
7799   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7800
7801   // If the logical-not of the result is required, perform that now.
7802   if (Invert)
7803     Result = DAG.getNOT(dl, Result, VT);
7804
7805   return Result;
7806 }
7807
7808 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7809 static bool isX86LogicalCmp(SDValue Op) {
7810   unsigned Opc = Op.getNode()->getOpcode();
7811   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7812     return true;
7813   if (Op.getResNo() == 1 &&
7814       (Opc == X86ISD::ADD ||
7815        Opc == X86ISD::SUB ||
7816        Opc == X86ISD::ADC ||
7817        Opc == X86ISD::SBB ||
7818        Opc == X86ISD::SMUL ||
7819        Opc == X86ISD::UMUL ||
7820        Opc == X86ISD::INC ||
7821        Opc == X86ISD::DEC ||
7822        Opc == X86ISD::OR ||
7823        Opc == X86ISD::XOR ||
7824        Opc == X86ISD::AND))
7825     return true;
7826
7827   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7828     return true;
7829
7830   return false;
7831 }
7832
7833 static bool isZero(SDValue V) {
7834   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7835   return C && C->isNullValue();
7836 }
7837
7838 static bool isAllOnes(SDValue V) {
7839   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7840   return C && C->isAllOnesValue();
7841 }
7842
7843 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7844   bool addTest = true;
7845   SDValue Cond  = Op.getOperand(0);
7846   SDValue Op1 = Op.getOperand(1);
7847   SDValue Op2 = Op.getOperand(2);
7848   DebugLoc DL = Op.getDebugLoc();
7849   SDValue CC;
7850
7851   if (Cond.getOpcode() == ISD::SETCC) {
7852     SDValue NewCond = LowerSETCC(Cond, DAG);
7853     if (NewCond.getNode())
7854       Cond = NewCond;
7855   }
7856
7857   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7858   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7859   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7860   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7861   if (Cond.getOpcode() == X86ISD::SETCC &&
7862       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7863       isZero(Cond.getOperand(1).getOperand(1))) {
7864     SDValue Cmp = Cond.getOperand(1);
7865
7866     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7867
7868     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7869         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7870       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7871
7872       SDValue CmpOp0 = Cmp.getOperand(0);
7873       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7874                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7875
7876       SDValue Res =   // Res = 0 or -1.
7877         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7878                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7879
7880       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7881         Res = DAG.getNOT(DL, Res, Res.getValueType());
7882
7883       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7884       if (N2C == 0 || !N2C->isNullValue())
7885         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7886       return Res;
7887     }
7888   }
7889
7890   // Look past (and (setcc_carry (cmp ...)), 1).
7891   if (Cond.getOpcode() == ISD::AND &&
7892       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7893     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7894     if (C && C->getAPIntValue() == 1)
7895       Cond = Cond.getOperand(0);
7896   }
7897
7898   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7899   // setting operand in place of the X86ISD::SETCC.
7900   if (Cond.getOpcode() == X86ISD::SETCC ||
7901       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7902     CC = Cond.getOperand(0);
7903
7904     SDValue Cmp = Cond.getOperand(1);
7905     unsigned Opc = Cmp.getOpcode();
7906     EVT VT = Op.getValueType();
7907
7908     bool IllegalFPCMov = false;
7909     if (VT.isFloatingPoint() && !VT.isVector() &&
7910         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7911       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7912
7913     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7914         Opc == X86ISD::BT) { // FIXME
7915       Cond = Cmp;
7916       addTest = false;
7917     }
7918   }
7919
7920   if (addTest) {
7921     // Look pass the truncate.
7922     if (Cond.getOpcode() == ISD::TRUNCATE)
7923       Cond = Cond.getOperand(0);
7924
7925     // We know the result of AND is compared against zero. Try to match
7926     // it to BT.
7927     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7928       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7929       if (NewSetCC.getNode()) {
7930         CC = NewSetCC.getOperand(0);
7931         Cond = NewSetCC.getOperand(1);
7932         addTest = false;
7933       }
7934     }
7935   }
7936
7937   if (addTest) {
7938     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7939     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7940   }
7941
7942   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7943   // a <  b ?  0 : -1 -> RES = setcc_carry
7944   // a >= b ? -1 :  0 -> RES = setcc_carry
7945   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7946   if (Cond.getOpcode() == X86ISD::CMP) {
7947     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7948
7949     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7950         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7951       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7952                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7953       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7954         return DAG.getNOT(DL, Res, Res.getValueType());
7955       return Res;
7956     }
7957   }
7958
7959   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7960   // condition is true.
7961   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7962   SDValue Ops[] = { Op2, Op1, CC, Cond };
7963   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7964 }
7965
7966 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7967 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7968 // from the AND / OR.
7969 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7970   Opc = Op.getOpcode();
7971   if (Opc != ISD::OR && Opc != ISD::AND)
7972     return false;
7973   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7974           Op.getOperand(0).hasOneUse() &&
7975           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7976           Op.getOperand(1).hasOneUse());
7977 }
7978
7979 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7980 // 1 and that the SETCC node has a single use.
7981 static bool isXor1OfSetCC(SDValue Op) {
7982   if (Op.getOpcode() != ISD::XOR)
7983     return false;
7984   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7985   if (N1C && N1C->getAPIntValue() == 1) {
7986     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7987       Op.getOperand(0).hasOneUse();
7988   }
7989   return false;
7990 }
7991
7992 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7993   bool addTest = true;
7994   SDValue Chain = Op.getOperand(0);
7995   SDValue Cond  = Op.getOperand(1);
7996   SDValue Dest  = Op.getOperand(2);
7997   DebugLoc dl = Op.getDebugLoc();
7998   SDValue CC;
7999
8000   if (Cond.getOpcode() == ISD::SETCC) {
8001     SDValue NewCond = LowerSETCC(Cond, DAG);
8002     if (NewCond.getNode())
8003       Cond = NewCond;
8004   }
8005 #if 0
8006   // FIXME: LowerXALUO doesn't handle these!!
8007   else if (Cond.getOpcode() == X86ISD::ADD  ||
8008            Cond.getOpcode() == X86ISD::SUB  ||
8009            Cond.getOpcode() == X86ISD::SMUL ||
8010            Cond.getOpcode() == X86ISD::UMUL)
8011     Cond = LowerXALUO(Cond, DAG);
8012 #endif
8013
8014   // Look pass (and (setcc_carry (cmp ...)), 1).
8015   if (Cond.getOpcode() == ISD::AND &&
8016       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8017     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8018     if (C && C->getAPIntValue() == 1)
8019       Cond = Cond.getOperand(0);
8020   }
8021
8022   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8023   // setting operand in place of the X86ISD::SETCC.
8024   if (Cond.getOpcode() == X86ISD::SETCC ||
8025       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8026     CC = Cond.getOperand(0);
8027
8028     SDValue Cmp = Cond.getOperand(1);
8029     unsigned Opc = Cmp.getOpcode();
8030     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8031     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8032       Cond = Cmp;
8033       addTest = false;
8034     } else {
8035       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8036       default: break;
8037       case X86::COND_O:
8038       case X86::COND_B:
8039         // These can only come from an arithmetic instruction with overflow,
8040         // e.g. SADDO, UADDO.
8041         Cond = Cond.getNode()->getOperand(1);
8042         addTest = false;
8043         break;
8044       }
8045     }
8046   } else {
8047     unsigned CondOpc;
8048     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8049       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8050       if (CondOpc == ISD::OR) {
8051         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8052         // two branches instead of an explicit OR instruction with a
8053         // separate test.
8054         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8055             isX86LogicalCmp(Cmp)) {
8056           CC = Cond.getOperand(0).getOperand(0);
8057           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8058                               Chain, Dest, CC, Cmp);
8059           CC = Cond.getOperand(1).getOperand(0);
8060           Cond = Cmp;
8061           addTest = false;
8062         }
8063       } else { // ISD::AND
8064         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8065         // two branches instead of an explicit AND instruction with a
8066         // separate test. However, we only do this if this block doesn't
8067         // have a fall-through edge, because this requires an explicit
8068         // jmp when the condition is false.
8069         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8070             isX86LogicalCmp(Cmp) &&
8071             Op.getNode()->hasOneUse()) {
8072           X86::CondCode CCode =
8073             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8074           CCode = X86::GetOppositeBranchCondition(CCode);
8075           CC = DAG.getConstant(CCode, MVT::i8);
8076           SDNode *User = *Op.getNode()->use_begin();
8077           // Look for an unconditional branch following this conditional branch.
8078           // We need this because we need to reverse the successors in order
8079           // to implement FCMP_OEQ.
8080           if (User->getOpcode() == ISD::BR) {
8081             SDValue FalseBB = User->getOperand(1);
8082             SDNode *NewBR =
8083               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8084             assert(NewBR == User);
8085             (void)NewBR;
8086             Dest = FalseBB;
8087
8088             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8089                                 Chain, Dest, CC, Cmp);
8090             X86::CondCode CCode =
8091               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8092             CCode = X86::GetOppositeBranchCondition(CCode);
8093             CC = DAG.getConstant(CCode, MVT::i8);
8094             Cond = Cmp;
8095             addTest = false;
8096           }
8097         }
8098       }
8099     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8100       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8101       // It should be transformed during dag combiner except when the condition
8102       // is set by a arithmetics with overflow node.
8103       X86::CondCode CCode =
8104         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8105       CCode = X86::GetOppositeBranchCondition(CCode);
8106       CC = DAG.getConstant(CCode, MVT::i8);
8107       Cond = Cond.getOperand(0).getOperand(1);
8108       addTest = false;
8109     }
8110   }
8111
8112   if (addTest) {
8113     // Look pass the truncate.
8114     if (Cond.getOpcode() == ISD::TRUNCATE)
8115       Cond = Cond.getOperand(0);
8116
8117     // We know the result of AND is compared against zero. Try to match
8118     // it to BT.
8119     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8120       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8121       if (NewSetCC.getNode()) {
8122         CC = NewSetCC.getOperand(0);
8123         Cond = NewSetCC.getOperand(1);
8124         addTest = false;
8125       }
8126     }
8127   }
8128
8129   if (addTest) {
8130     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8131     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8132   }
8133   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8134                      Chain, Dest, CC, Cond);
8135 }
8136
8137
8138 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8139 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8140 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8141 // that the guard pages used by the OS virtual memory manager are allocated in
8142 // correct sequence.
8143 SDValue
8144 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8145                                            SelectionDAG &DAG) const {
8146   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8147          "This should be used only on Windows targets");
8148   assert(!Subtarget->isTargetEnvMacho());
8149   DebugLoc dl = Op.getDebugLoc();
8150
8151   // Get the inputs.
8152   SDValue Chain = Op.getOperand(0);
8153   SDValue Size  = Op.getOperand(1);
8154   // FIXME: Ensure alignment here
8155
8156   SDValue Flag;
8157
8158   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8159   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8160
8161   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8162   Flag = Chain.getValue(1);
8163
8164   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8165
8166   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8167   Flag = Chain.getValue(1);
8168
8169   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8170
8171   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8172   return DAG.getMergeValues(Ops1, 2, dl);
8173 }
8174
8175 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8176   MachineFunction &MF = DAG.getMachineFunction();
8177   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8178
8179   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8180   DebugLoc DL = Op.getDebugLoc();
8181
8182   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8183     // vastart just stores the address of the VarArgsFrameIndex slot into the
8184     // memory location argument.
8185     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8186                                    getPointerTy());
8187     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8188                         MachinePointerInfo(SV), false, false, 0);
8189   }
8190
8191   // __va_list_tag:
8192   //   gp_offset         (0 - 6 * 8)
8193   //   fp_offset         (48 - 48 + 8 * 16)
8194   //   overflow_arg_area (point to parameters coming in memory).
8195   //   reg_save_area
8196   SmallVector<SDValue, 8> MemOps;
8197   SDValue FIN = Op.getOperand(1);
8198   // Store gp_offset
8199   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8200                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8201                                                MVT::i32),
8202                                FIN, MachinePointerInfo(SV), false, false, 0);
8203   MemOps.push_back(Store);
8204
8205   // Store fp_offset
8206   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8207                     FIN, DAG.getIntPtrConstant(4));
8208   Store = DAG.getStore(Op.getOperand(0), DL,
8209                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8210                                        MVT::i32),
8211                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8212   MemOps.push_back(Store);
8213
8214   // Store ptr to overflow_arg_area
8215   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8216                     FIN, DAG.getIntPtrConstant(4));
8217   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8218                                     getPointerTy());
8219   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8220                        MachinePointerInfo(SV, 8),
8221                        false, false, 0);
8222   MemOps.push_back(Store);
8223
8224   // Store ptr to reg_save_area.
8225   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8226                     FIN, DAG.getIntPtrConstant(8));
8227   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8228                                     getPointerTy());
8229   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8230                        MachinePointerInfo(SV, 16), false, false, 0);
8231   MemOps.push_back(Store);
8232   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8233                      &MemOps[0], MemOps.size());
8234 }
8235
8236 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8237   assert(Subtarget->is64Bit() &&
8238          "LowerVAARG only handles 64-bit va_arg!");
8239   assert((Subtarget->isTargetLinux() ||
8240           Subtarget->isTargetDarwin()) &&
8241           "Unhandled target in LowerVAARG");
8242   assert(Op.getNode()->getNumOperands() == 4);
8243   SDValue Chain = Op.getOperand(0);
8244   SDValue SrcPtr = Op.getOperand(1);
8245   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8246   unsigned Align = Op.getConstantOperandVal(3);
8247   DebugLoc dl = Op.getDebugLoc();
8248
8249   EVT ArgVT = Op.getNode()->getValueType(0);
8250   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8251   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8252   uint8_t ArgMode;
8253
8254   // Decide which area this value should be read from.
8255   // TODO: Implement the AMD64 ABI in its entirety. This simple
8256   // selection mechanism works only for the basic types.
8257   if (ArgVT == MVT::f80) {
8258     llvm_unreachable("va_arg for f80 not yet implemented");
8259   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8260     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8261   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8262     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8263   } else {
8264     llvm_unreachable("Unhandled argument type in LowerVAARG");
8265   }
8266
8267   if (ArgMode == 2) {
8268     // Sanity Check: Make sure using fp_offset makes sense.
8269     assert(!UseSoftFloat &&
8270            !(DAG.getMachineFunction()
8271                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8272            Subtarget->hasXMM());
8273   }
8274
8275   // Insert VAARG_64 node into the DAG
8276   // VAARG_64 returns two values: Variable Argument Address, Chain
8277   SmallVector<SDValue, 11> InstOps;
8278   InstOps.push_back(Chain);
8279   InstOps.push_back(SrcPtr);
8280   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8281   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8282   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8283   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8284   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8285                                           VTs, &InstOps[0], InstOps.size(),
8286                                           MVT::i64,
8287                                           MachinePointerInfo(SV),
8288                                           /*Align=*/0,
8289                                           /*Volatile=*/false,
8290                                           /*ReadMem=*/true,
8291                                           /*WriteMem=*/true);
8292   Chain = VAARG.getValue(1);
8293
8294   // Load the next argument and return it
8295   return DAG.getLoad(ArgVT, dl,
8296                      Chain,
8297                      VAARG,
8298                      MachinePointerInfo(),
8299                      false, false, 0);
8300 }
8301
8302 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8303   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8304   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8305   SDValue Chain = Op.getOperand(0);
8306   SDValue DstPtr = Op.getOperand(1);
8307   SDValue SrcPtr = Op.getOperand(2);
8308   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8309   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8310   DebugLoc DL = Op.getDebugLoc();
8311
8312   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8313                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8314                        false,
8315                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8316 }
8317
8318 SDValue
8319 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8320   DebugLoc dl = Op.getDebugLoc();
8321   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8322   switch (IntNo) {
8323   default: return SDValue();    // Don't custom lower most intrinsics.
8324   // Comparison intrinsics.
8325   case Intrinsic::x86_sse_comieq_ss:
8326   case Intrinsic::x86_sse_comilt_ss:
8327   case Intrinsic::x86_sse_comile_ss:
8328   case Intrinsic::x86_sse_comigt_ss:
8329   case Intrinsic::x86_sse_comige_ss:
8330   case Intrinsic::x86_sse_comineq_ss:
8331   case Intrinsic::x86_sse_ucomieq_ss:
8332   case Intrinsic::x86_sse_ucomilt_ss:
8333   case Intrinsic::x86_sse_ucomile_ss:
8334   case Intrinsic::x86_sse_ucomigt_ss:
8335   case Intrinsic::x86_sse_ucomige_ss:
8336   case Intrinsic::x86_sse_ucomineq_ss:
8337   case Intrinsic::x86_sse2_comieq_sd:
8338   case Intrinsic::x86_sse2_comilt_sd:
8339   case Intrinsic::x86_sse2_comile_sd:
8340   case Intrinsic::x86_sse2_comigt_sd:
8341   case Intrinsic::x86_sse2_comige_sd:
8342   case Intrinsic::x86_sse2_comineq_sd:
8343   case Intrinsic::x86_sse2_ucomieq_sd:
8344   case Intrinsic::x86_sse2_ucomilt_sd:
8345   case Intrinsic::x86_sse2_ucomile_sd:
8346   case Intrinsic::x86_sse2_ucomigt_sd:
8347   case Intrinsic::x86_sse2_ucomige_sd:
8348   case Intrinsic::x86_sse2_ucomineq_sd: {
8349     unsigned Opc = 0;
8350     ISD::CondCode CC = ISD::SETCC_INVALID;
8351     switch (IntNo) {
8352     default: break;
8353     case Intrinsic::x86_sse_comieq_ss:
8354     case Intrinsic::x86_sse2_comieq_sd:
8355       Opc = X86ISD::COMI;
8356       CC = ISD::SETEQ;
8357       break;
8358     case Intrinsic::x86_sse_comilt_ss:
8359     case Intrinsic::x86_sse2_comilt_sd:
8360       Opc = X86ISD::COMI;
8361       CC = ISD::SETLT;
8362       break;
8363     case Intrinsic::x86_sse_comile_ss:
8364     case Intrinsic::x86_sse2_comile_sd:
8365       Opc = X86ISD::COMI;
8366       CC = ISD::SETLE;
8367       break;
8368     case Intrinsic::x86_sse_comigt_ss:
8369     case Intrinsic::x86_sse2_comigt_sd:
8370       Opc = X86ISD::COMI;
8371       CC = ISD::SETGT;
8372       break;
8373     case Intrinsic::x86_sse_comige_ss:
8374     case Intrinsic::x86_sse2_comige_sd:
8375       Opc = X86ISD::COMI;
8376       CC = ISD::SETGE;
8377       break;
8378     case Intrinsic::x86_sse_comineq_ss:
8379     case Intrinsic::x86_sse2_comineq_sd:
8380       Opc = X86ISD::COMI;
8381       CC = ISD::SETNE;
8382       break;
8383     case Intrinsic::x86_sse_ucomieq_ss:
8384     case Intrinsic::x86_sse2_ucomieq_sd:
8385       Opc = X86ISD::UCOMI;
8386       CC = ISD::SETEQ;
8387       break;
8388     case Intrinsic::x86_sse_ucomilt_ss:
8389     case Intrinsic::x86_sse2_ucomilt_sd:
8390       Opc = X86ISD::UCOMI;
8391       CC = ISD::SETLT;
8392       break;
8393     case Intrinsic::x86_sse_ucomile_ss:
8394     case Intrinsic::x86_sse2_ucomile_sd:
8395       Opc = X86ISD::UCOMI;
8396       CC = ISD::SETLE;
8397       break;
8398     case Intrinsic::x86_sse_ucomigt_ss:
8399     case Intrinsic::x86_sse2_ucomigt_sd:
8400       Opc = X86ISD::UCOMI;
8401       CC = ISD::SETGT;
8402       break;
8403     case Intrinsic::x86_sse_ucomige_ss:
8404     case Intrinsic::x86_sse2_ucomige_sd:
8405       Opc = X86ISD::UCOMI;
8406       CC = ISD::SETGE;
8407       break;
8408     case Intrinsic::x86_sse_ucomineq_ss:
8409     case Intrinsic::x86_sse2_ucomineq_sd:
8410       Opc = X86ISD::UCOMI;
8411       CC = ISD::SETNE;
8412       break;
8413     }
8414
8415     SDValue LHS = Op.getOperand(1);
8416     SDValue RHS = Op.getOperand(2);
8417     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8418     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8419     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8420     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8421                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8422     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8423   }
8424   // ptest and testp intrinsics. The intrinsic these come from are designed to
8425   // return an integer value, not just an instruction so lower it to the ptest
8426   // or testp pattern and a setcc for the result.
8427   case Intrinsic::x86_sse41_ptestz:
8428   case Intrinsic::x86_sse41_ptestc:
8429   case Intrinsic::x86_sse41_ptestnzc:
8430   case Intrinsic::x86_avx_ptestz_256:
8431   case Intrinsic::x86_avx_ptestc_256:
8432   case Intrinsic::x86_avx_ptestnzc_256:
8433   case Intrinsic::x86_avx_vtestz_ps:
8434   case Intrinsic::x86_avx_vtestc_ps:
8435   case Intrinsic::x86_avx_vtestnzc_ps:
8436   case Intrinsic::x86_avx_vtestz_pd:
8437   case Intrinsic::x86_avx_vtestc_pd:
8438   case Intrinsic::x86_avx_vtestnzc_pd:
8439   case Intrinsic::x86_avx_vtestz_ps_256:
8440   case Intrinsic::x86_avx_vtestc_ps_256:
8441   case Intrinsic::x86_avx_vtestnzc_ps_256:
8442   case Intrinsic::x86_avx_vtestz_pd_256:
8443   case Intrinsic::x86_avx_vtestc_pd_256:
8444   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8445     bool IsTestPacked = false;
8446     unsigned X86CC = 0;
8447     switch (IntNo) {
8448     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8449     case Intrinsic::x86_avx_vtestz_ps:
8450     case Intrinsic::x86_avx_vtestz_pd:
8451     case Intrinsic::x86_avx_vtestz_ps_256:
8452     case Intrinsic::x86_avx_vtestz_pd_256:
8453       IsTestPacked = true; // Fallthrough
8454     case Intrinsic::x86_sse41_ptestz:
8455     case Intrinsic::x86_avx_ptestz_256:
8456       // ZF = 1
8457       X86CC = X86::COND_E;
8458       break;
8459     case Intrinsic::x86_avx_vtestc_ps:
8460     case Intrinsic::x86_avx_vtestc_pd:
8461     case Intrinsic::x86_avx_vtestc_ps_256:
8462     case Intrinsic::x86_avx_vtestc_pd_256:
8463       IsTestPacked = true; // Fallthrough
8464     case Intrinsic::x86_sse41_ptestc:
8465     case Intrinsic::x86_avx_ptestc_256:
8466       // CF = 1
8467       X86CC = X86::COND_B;
8468       break;
8469     case Intrinsic::x86_avx_vtestnzc_ps:
8470     case Intrinsic::x86_avx_vtestnzc_pd:
8471     case Intrinsic::x86_avx_vtestnzc_ps_256:
8472     case Intrinsic::x86_avx_vtestnzc_pd_256:
8473       IsTestPacked = true; // Fallthrough
8474     case Intrinsic::x86_sse41_ptestnzc:
8475     case Intrinsic::x86_avx_ptestnzc_256:
8476       // ZF and CF = 0
8477       X86CC = X86::COND_A;
8478       break;
8479     }
8480
8481     SDValue LHS = Op.getOperand(1);
8482     SDValue RHS = Op.getOperand(2);
8483     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8484     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8485     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8486     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8487     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8488   }
8489
8490   // Fix vector shift instructions where the last operand is a non-immediate
8491   // i32 value.
8492   case Intrinsic::x86_sse2_pslli_w:
8493   case Intrinsic::x86_sse2_pslli_d:
8494   case Intrinsic::x86_sse2_pslli_q:
8495   case Intrinsic::x86_sse2_psrli_w:
8496   case Intrinsic::x86_sse2_psrli_d:
8497   case Intrinsic::x86_sse2_psrli_q:
8498   case Intrinsic::x86_sse2_psrai_w:
8499   case Intrinsic::x86_sse2_psrai_d:
8500   case Intrinsic::x86_mmx_pslli_w:
8501   case Intrinsic::x86_mmx_pslli_d:
8502   case Intrinsic::x86_mmx_pslli_q:
8503   case Intrinsic::x86_mmx_psrli_w:
8504   case Intrinsic::x86_mmx_psrli_d:
8505   case Intrinsic::x86_mmx_psrli_q:
8506   case Intrinsic::x86_mmx_psrai_w:
8507   case Intrinsic::x86_mmx_psrai_d: {
8508     SDValue ShAmt = Op.getOperand(2);
8509     if (isa<ConstantSDNode>(ShAmt))
8510       return SDValue();
8511
8512     unsigned NewIntNo = 0;
8513     EVT ShAmtVT = MVT::v4i32;
8514     switch (IntNo) {
8515     case Intrinsic::x86_sse2_pslli_w:
8516       NewIntNo = Intrinsic::x86_sse2_psll_w;
8517       break;
8518     case Intrinsic::x86_sse2_pslli_d:
8519       NewIntNo = Intrinsic::x86_sse2_psll_d;
8520       break;
8521     case Intrinsic::x86_sse2_pslli_q:
8522       NewIntNo = Intrinsic::x86_sse2_psll_q;
8523       break;
8524     case Intrinsic::x86_sse2_psrli_w:
8525       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8526       break;
8527     case Intrinsic::x86_sse2_psrli_d:
8528       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8529       break;
8530     case Intrinsic::x86_sse2_psrli_q:
8531       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8532       break;
8533     case Intrinsic::x86_sse2_psrai_w:
8534       NewIntNo = Intrinsic::x86_sse2_psra_w;
8535       break;
8536     case Intrinsic::x86_sse2_psrai_d:
8537       NewIntNo = Intrinsic::x86_sse2_psra_d;
8538       break;
8539     default: {
8540       ShAmtVT = MVT::v2i32;
8541       switch (IntNo) {
8542       case Intrinsic::x86_mmx_pslli_w:
8543         NewIntNo = Intrinsic::x86_mmx_psll_w;
8544         break;
8545       case Intrinsic::x86_mmx_pslli_d:
8546         NewIntNo = Intrinsic::x86_mmx_psll_d;
8547         break;
8548       case Intrinsic::x86_mmx_pslli_q:
8549         NewIntNo = Intrinsic::x86_mmx_psll_q;
8550         break;
8551       case Intrinsic::x86_mmx_psrli_w:
8552         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8553         break;
8554       case Intrinsic::x86_mmx_psrli_d:
8555         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8556         break;
8557       case Intrinsic::x86_mmx_psrli_q:
8558         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8559         break;
8560       case Intrinsic::x86_mmx_psrai_w:
8561         NewIntNo = Intrinsic::x86_mmx_psra_w;
8562         break;
8563       case Intrinsic::x86_mmx_psrai_d:
8564         NewIntNo = Intrinsic::x86_mmx_psra_d;
8565         break;
8566       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8567       }
8568       break;
8569     }
8570     }
8571
8572     // The vector shift intrinsics with scalars uses 32b shift amounts but
8573     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8574     // to be zero.
8575     SDValue ShOps[4];
8576     ShOps[0] = ShAmt;
8577     ShOps[1] = DAG.getConstant(0, MVT::i32);
8578     if (ShAmtVT == MVT::v4i32) {
8579       ShOps[2] = DAG.getUNDEF(MVT::i32);
8580       ShOps[3] = DAG.getUNDEF(MVT::i32);
8581       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8582     } else {
8583       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8584 // FIXME this must be lowered to get rid of the invalid type.
8585     }
8586
8587     EVT VT = Op.getValueType();
8588     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8589     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8590                        DAG.getConstant(NewIntNo, MVT::i32),
8591                        Op.getOperand(1), ShAmt);
8592   }
8593   }
8594 }
8595
8596 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8597                                            SelectionDAG &DAG) const {
8598   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8599   MFI->setReturnAddressIsTaken(true);
8600
8601   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8602   DebugLoc dl = Op.getDebugLoc();
8603
8604   if (Depth > 0) {
8605     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8606     SDValue Offset =
8607       DAG.getConstant(TD->getPointerSize(),
8608                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8609     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8610                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8611                                    FrameAddr, Offset),
8612                        MachinePointerInfo(), false, false, 0);
8613   }
8614
8615   // Just load the return address.
8616   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8617   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8618                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8619 }
8620
8621 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8622   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8623   MFI->setFrameAddressIsTaken(true);
8624
8625   EVT VT = Op.getValueType();
8626   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8627   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8628   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8629   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8630   while (Depth--)
8631     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8632                             MachinePointerInfo(),
8633                             false, false, 0);
8634   return FrameAddr;
8635 }
8636
8637 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8638                                                      SelectionDAG &DAG) const {
8639   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8640 }
8641
8642 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8643   MachineFunction &MF = DAG.getMachineFunction();
8644   SDValue Chain     = Op.getOperand(0);
8645   SDValue Offset    = Op.getOperand(1);
8646   SDValue Handler   = Op.getOperand(2);
8647   DebugLoc dl       = Op.getDebugLoc();
8648
8649   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8650                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8651                                      getPointerTy());
8652   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8653
8654   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8655                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8656   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8657   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8658                        false, false, 0);
8659   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8660   MF.getRegInfo().addLiveOut(StoreAddrReg);
8661
8662   return DAG.getNode(X86ISD::EH_RETURN, dl,
8663                      MVT::Other,
8664                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8665 }
8666
8667 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8668                                              SelectionDAG &DAG) const {
8669   SDValue Root = Op.getOperand(0);
8670   SDValue Trmp = Op.getOperand(1); // trampoline
8671   SDValue FPtr = Op.getOperand(2); // nested function
8672   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8673   DebugLoc dl  = Op.getDebugLoc();
8674
8675   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8676
8677   if (Subtarget->is64Bit()) {
8678     SDValue OutChains[6];
8679
8680     // Large code-model.
8681     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8682     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8683
8684     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
8685     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
8686
8687     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8688
8689     // Load the pointer to the nested function into R11.
8690     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8691     SDValue Addr = Trmp;
8692     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8693                                 Addr, MachinePointerInfo(TrmpAddr),
8694                                 false, false, 0);
8695
8696     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8697                        DAG.getConstant(2, MVT::i64));
8698     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8699                                 MachinePointerInfo(TrmpAddr, 2),
8700                                 false, false, 2);
8701
8702     // Load the 'nest' parameter value into R10.
8703     // R10 is specified in X86CallingConv.td
8704     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8705     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8706                        DAG.getConstant(10, MVT::i64));
8707     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8708                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8709                                 false, false, 0);
8710
8711     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8712                        DAG.getConstant(12, MVT::i64));
8713     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8714                                 MachinePointerInfo(TrmpAddr, 12),
8715                                 false, false, 2);
8716
8717     // Jump to the nested function.
8718     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8719     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8720                        DAG.getConstant(20, MVT::i64));
8721     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8722                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8723                                 false, false, 0);
8724
8725     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8726     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8727                        DAG.getConstant(22, MVT::i64));
8728     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8729                                 MachinePointerInfo(TrmpAddr, 22),
8730                                 false, false, 0);
8731
8732     SDValue Ops[] =
8733       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8734     return DAG.getMergeValues(Ops, 2, dl);
8735   } else {
8736     const Function *Func =
8737       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8738     CallingConv::ID CC = Func->getCallingConv();
8739     unsigned NestReg;
8740
8741     switch (CC) {
8742     default:
8743       llvm_unreachable("Unsupported calling convention");
8744     case CallingConv::C:
8745     case CallingConv::X86_StdCall: {
8746       // Pass 'nest' parameter in ECX.
8747       // Must be kept in sync with X86CallingConv.td
8748       NestReg = X86::ECX;
8749
8750       // Check that ECX wasn't needed by an 'inreg' parameter.
8751       FunctionType *FTy = Func->getFunctionType();
8752       const AttrListPtr &Attrs = Func->getAttributes();
8753
8754       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8755         unsigned InRegCount = 0;
8756         unsigned Idx = 1;
8757
8758         for (FunctionType::param_iterator I = FTy->param_begin(),
8759              E = FTy->param_end(); I != E; ++I, ++Idx)
8760           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8761             // FIXME: should only count parameters that are lowered to integers.
8762             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8763
8764         if (InRegCount > 2) {
8765           report_fatal_error("Nest register in use - reduce number of inreg"
8766                              " parameters!");
8767         }
8768       }
8769       break;
8770     }
8771     case CallingConv::X86_FastCall:
8772     case CallingConv::X86_ThisCall:
8773     case CallingConv::Fast:
8774       // Pass 'nest' parameter in EAX.
8775       // Must be kept in sync with X86CallingConv.td
8776       NestReg = X86::EAX;
8777       break;
8778     }
8779
8780     SDValue OutChains[4];
8781     SDValue Addr, Disp;
8782
8783     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8784                        DAG.getConstant(10, MVT::i32));
8785     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8786
8787     // This is storing the opcode for MOV32ri.
8788     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8789     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
8790     OutChains[0] = DAG.getStore(Root, dl,
8791                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8792                                 Trmp, MachinePointerInfo(TrmpAddr),
8793                                 false, false, 0);
8794
8795     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8796                        DAG.getConstant(1, MVT::i32));
8797     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8798                                 MachinePointerInfo(TrmpAddr, 1),
8799                                 false, false, 1);
8800
8801     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8802     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8803                        DAG.getConstant(5, MVT::i32));
8804     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8805                                 MachinePointerInfo(TrmpAddr, 5),
8806                                 false, false, 1);
8807
8808     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8809                        DAG.getConstant(6, MVT::i32));
8810     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8811                                 MachinePointerInfo(TrmpAddr, 6),
8812                                 false, false, 1);
8813
8814     SDValue Ops[] =
8815       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8816     return DAG.getMergeValues(Ops, 2, dl);
8817   }
8818 }
8819
8820 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8821                                             SelectionDAG &DAG) const {
8822   /*
8823    The rounding mode is in bits 11:10 of FPSR, and has the following
8824    settings:
8825      00 Round to nearest
8826      01 Round to -inf
8827      10 Round to +inf
8828      11 Round to 0
8829
8830   FLT_ROUNDS, on the other hand, expects the following:
8831     -1 Undefined
8832      0 Round to 0
8833      1 Round to nearest
8834      2 Round to +inf
8835      3 Round to -inf
8836
8837   To perform the conversion, we do:
8838     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8839   */
8840
8841   MachineFunction &MF = DAG.getMachineFunction();
8842   const TargetMachine &TM = MF.getTarget();
8843   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8844   unsigned StackAlignment = TFI.getStackAlignment();
8845   EVT VT = Op.getValueType();
8846   DebugLoc DL = Op.getDebugLoc();
8847
8848   // Save FP Control Word to stack slot
8849   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8850   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8851
8852
8853   MachineMemOperand *MMO =
8854    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8855                            MachineMemOperand::MOStore, 2, 2);
8856
8857   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8858   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8859                                           DAG.getVTList(MVT::Other),
8860                                           Ops, 2, MVT::i16, MMO);
8861
8862   // Load FP Control Word from stack slot
8863   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8864                             MachinePointerInfo(), false, false, 0);
8865
8866   // Transform as necessary
8867   SDValue CWD1 =
8868     DAG.getNode(ISD::SRL, DL, MVT::i16,
8869                 DAG.getNode(ISD::AND, DL, MVT::i16,
8870                             CWD, DAG.getConstant(0x800, MVT::i16)),
8871                 DAG.getConstant(11, MVT::i8));
8872   SDValue CWD2 =
8873     DAG.getNode(ISD::SRL, DL, MVT::i16,
8874                 DAG.getNode(ISD::AND, DL, MVT::i16,
8875                             CWD, DAG.getConstant(0x400, MVT::i16)),
8876                 DAG.getConstant(9, MVT::i8));
8877
8878   SDValue RetVal =
8879     DAG.getNode(ISD::AND, DL, MVT::i16,
8880                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8881                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8882                             DAG.getConstant(1, MVT::i16)),
8883                 DAG.getConstant(3, MVT::i16));
8884
8885
8886   return DAG.getNode((VT.getSizeInBits() < 16 ?
8887                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8888 }
8889
8890 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8891   EVT VT = Op.getValueType();
8892   EVT OpVT = VT;
8893   unsigned NumBits = VT.getSizeInBits();
8894   DebugLoc dl = Op.getDebugLoc();
8895
8896   Op = Op.getOperand(0);
8897   if (VT == MVT::i8) {
8898     // Zero extend to i32 since there is not an i8 bsr.
8899     OpVT = MVT::i32;
8900     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8901   }
8902
8903   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8904   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8905   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8906
8907   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8908   SDValue Ops[] = {
8909     Op,
8910     DAG.getConstant(NumBits+NumBits-1, OpVT),
8911     DAG.getConstant(X86::COND_E, MVT::i8),
8912     Op.getValue(1)
8913   };
8914   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8915
8916   // Finally xor with NumBits-1.
8917   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8918
8919   if (VT == MVT::i8)
8920     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8921   return Op;
8922 }
8923
8924 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8925   EVT VT = Op.getValueType();
8926   EVT OpVT = VT;
8927   unsigned NumBits = VT.getSizeInBits();
8928   DebugLoc dl = Op.getDebugLoc();
8929
8930   Op = Op.getOperand(0);
8931   if (VT == MVT::i8) {
8932     OpVT = MVT::i32;
8933     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8934   }
8935
8936   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8937   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8938   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8939
8940   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8941   SDValue Ops[] = {
8942     Op,
8943     DAG.getConstant(NumBits, OpVT),
8944     DAG.getConstant(X86::COND_E, MVT::i8),
8945     Op.getValue(1)
8946   };
8947   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8948
8949   if (VT == MVT::i8)
8950     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8951   return Op;
8952 }
8953
8954 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8955   EVT VT = Op.getValueType();
8956   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8957   DebugLoc dl = Op.getDebugLoc();
8958
8959   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8960   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8961   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8962   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8963   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8964   //
8965   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8966   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8967   //  return AloBlo + AloBhi + AhiBlo;
8968
8969   SDValue A = Op.getOperand(0);
8970   SDValue B = Op.getOperand(1);
8971
8972   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8973                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8974                        A, DAG.getConstant(32, MVT::i32));
8975   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8976                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8977                        B, DAG.getConstant(32, MVT::i32));
8978   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8979                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8980                        A, B);
8981   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8982                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8983                        A, Bhi);
8984   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8985                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8986                        Ahi, B);
8987   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8988                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8989                        AloBhi, DAG.getConstant(32, MVT::i32));
8990   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8991                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8992                        AhiBlo, DAG.getConstant(32, MVT::i32));
8993   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8994   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8995   return Res;
8996 }
8997
8998 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8999
9000   EVT VT = Op.getValueType();
9001   DebugLoc dl = Op.getDebugLoc();
9002   SDValue R = Op.getOperand(0);
9003   SDValue Amt = Op.getOperand(1);
9004
9005   LLVMContext *Context = DAG.getContext();
9006
9007   // Must have SSE2.
9008   if (!Subtarget->hasSSE2()) return SDValue();
9009
9010   // Optimize shl/srl/sra with constant shift amount.
9011   if (isSplatVector(Amt.getNode())) {
9012     SDValue SclrAmt = Amt->getOperand(0);
9013     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9014       uint64_t ShiftAmt = C->getZExtValue();
9015
9016       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9017        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9018                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9019                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9020
9021       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9022        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9023                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9024                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9025
9026       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9027        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9028                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9029                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9030
9031       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9032        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9033                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9034                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9035
9036       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9037        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9038                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9039                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9040
9041       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9042        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9043                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9044                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9045
9046       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9047        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9048                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9049                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9050
9051       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9052        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9053                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9054                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9055     }
9056   }
9057
9058   // Lower SHL with variable shift amount.
9059   // Cannot lower SHL without SSE2 or later.
9060   if (!Subtarget->hasSSE2()) return SDValue();
9061
9062   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9063     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9064                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9065                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9066
9067     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9068
9069     std::vector<Constant*> CV(4, CI);
9070     Constant *C = ConstantVector::get(CV);
9071     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9072     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9073                                  MachinePointerInfo::getConstantPool(),
9074                                  false, false, 16);
9075
9076     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9077     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9078     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9079     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9080   }
9081   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9082     // a = a << 5;
9083     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9084                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9085                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9086
9087     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9088     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9089
9090     std::vector<Constant*> CVM1(16, CM1);
9091     std::vector<Constant*> CVM2(16, CM2);
9092     Constant *C = ConstantVector::get(CVM1);
9093     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9094     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9095                             MachinePointerInfo::getConstantPool(),
9096                             false, false, 16);
9097
9098     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9099     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9100     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9101                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9102                     DAG.getConstant(4, MVT::i32));
9103     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9104     // a += a
9105     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9106
9107     C = ConstantVector::get(CVM2);
9108     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9109     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9110                     MachinePointerInfo::getConstantPool(),
9111                     false, false, 16);
9112
9113     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9114     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9115     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9116                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9117                     DAG.getConstant(2, MVT::i32));
9118     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9119     // a += a
9120     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9121
9122     // return pblendv(r, r+r, a);
9123     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9124                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9125     return R;
9126   }
9127   return SDValue();
9128 }
9129
9130 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9131   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9132   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9133   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9134   // has only one use.
9135   SDNode *N = Op.getNode();
9136   SDValue LHS = N->getOperand(0);
9137   SDValue RHS = N->getOperand(1);
9138   unsigned BaseOp = 0;
9139   unsigned Cond = 0;
9140   DebugLoc DL = Op.getDebugLoc();
9141   switch (Op.getOpcode()) {
9142   default: llvm_unreachable("Unknown ovf instruction!");
9143   case ISD::SADDO:
9144     // A subtract of one will be selected as a INC. Note that INC doesn't
9145     // set CF, so we can't do this for UADDO.
9146     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9147       if (C->isOne()) {
9148         BaseOp = X86ISD::INC;
9149         Cond = X86::COND_O;
9150         break;
9151       }
9152     BaseOp = X86ISD::ADD;
9153     Cond = X86::COND_O;
9154     break;
9155   case ISD::UADDO:
9156     BaseOp = X86ISD::ADD;
9157     Cond = X86::COND_B;
9158     break;
9159   case ISD::SSUBO:
9160     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9161     // set CF, so we can't do this for USUBO.
9162     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9163       if (C->isOne()) {
9164         BaseOp = X86ISD::DEC;
9165         Cond = X86::COND_O;
9166         break;
9167       }
9168     BaseOp = X86ISD::SUB;
9169     Cond = X86::COND_O;
9170     break;
9171   case ISD::USUBO:
9172     BaseOp = X86ISD::SUB;
9173     Cond = X86::COND_B;
9174     break;
9175   case ISD::SMULO:
9176     BaseOp = X86ISD::SMUL;
9177     Cond = X86::COND_O;
9178     break;
9179   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9180     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9181                                  MVT::i32);
9182     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9183
9184     SDValue SetCC =
9185       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9186                   DAG.getConstant(X86::COND_O, MVT::i32),
9187                   SDValue(Sum.getNode(), 2));
9188
9189     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9190     return Sum;
9191   }
9192   }
9193
9194   // Also sets EFLAGS.
9195   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9196   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9197
9198   SDValue SetCC =
9199     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9200                 DAG.getConstant(Cond, MVT::i32),
9201                 SDValue(Sum.getNode(), 1));
9202
9203   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9204   return Sum;
9205 }
9206
9207 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9208   DebugLoc dl = Op.getDebugLoc();
9209   SDNode* Node = Op.getNode();
9210   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9211   EVT VT = Node->getValueType(0);
9212
9213   if (Subtarget->hasSSE2() && VT.isVector()) {
9214     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9215                         ExtraVT.getScalarType().getSizeInBits();
9216     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9217
9218     unsigned SHLIntrinsicsID = 0;
9219     unsigned SRAIntrinsicsID = 0;
9220     switch (VT.getSimpleVT().SimpleTy) {
9221       default:
9222         return SDValue();
9223       case MVT::v2i64: {
9224         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9225         SRAIntrinsicsID = 0;
9226         break;
9227       }
9228       case MVT::v4i32: {
9229         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9230         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9231         break;
9232       }
9233       case MVT::v8i16: {
9234         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9235         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9236         break;
9237       }
9238     }
9239
9240     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9241                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9242                          Node->getOperand(0), ShAmt);
9243
9244     // In case of 1 bit sext, no need to shr
9245     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9246
9247     if (SRAIntrinsicsID) {
9248       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9249                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9250                          Tmp1, ShAmt);
9251     }
9252     return Tmp1;
9253   }
9254
9255   return SDValue();
9256 }
9257
9258
9259 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9260   DebugLoc dl = Op.getDebugLoc();
9261
9262   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9263   // There isn't any reason to disable it if the target processor supports it.
9264   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9265     SDValue Chain = Op.getOperand(0);
9266     SDValue Zero = DAG.getConstant(0, MVT::i32);
9267     SDValue Ops[] = {
9268       DAG.getRegister(X86::ESP, MVT::i32), // Base
9269       DAG.getTargetConstant(1, MVT::i8),   // Scale
9270       DAG.getRegister(0, MVT::i32),        // Index
9271       DAG.getTargetConstant(0, MVT::i32),  // Disp
9272       DAG.getRegister(0, MVT::i32),        // Segment.
9273       Zero,
9274       Chain
9275     };
9276     SDNode *Res =
9277       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9278                           array_lengthof(Ops));
9279     return SDValue(Res, 0);
9280   }
9281
9282   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9283   if (!isDev)
9284     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9285
9286   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9287   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9288   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9289   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9290
9291   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9292   if (!Op1 && !Op2 && !Op3 && Op4)
9293     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9294
9295   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9296   if (Op1 && !Op2 && !Op3 && !Op4)
9297     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9298
9299   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9300   //           (MFENCE)>;
9301   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9302 }
9303
9304 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9305   EVT T = Op.getValueType();
9306   DebugLoc DL = Op.getDebugLoc();
9307   unsigned Reg = 0;
9308   unsigned size = 0;
9309   switch(T.getSimpleVT().SimpleTy) {
9310   default:
9311     assert(false && "Invalid value type!");
9312   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9313   case MVT::i16: Reg = X86::AX;  size = 2; break;
9314   case MVT::i32: Reg = X86::EAX; size = 4; break;
9315   case MVT::i64:
9316     assert(Subtarget->is64Bit() && "Node not type legal!");
9317     Reg = X86::RAX; size = 8;
9318     break;
9319   }
9320   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9321                                     Op.getOperand(2), SDValue());
9322   SDValue Ops[] = { cpIn.getValue(0),
9323                     Op.getOperand(1),
9324                     Op.getOperand(3),
9325                     DAG.getTargetConstant(size, MVT::i8),
9326                     cpIn.getValue(1) };
9327   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9328   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9329   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9330                                            Ops, 5, T, MMO);
9331   SDValue cpOut =
9332     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9333   return cpOut;
9334 }
9335
9336 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9337                                                  SelectionDAG &DAG) const {
9338   assert(Subtarget->is64Bit() && "Result not type legalized?");
9339   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9340   SDValue TheChain = Op.getOperand(0);
9341   DebugLoc dl = Op.getDebugLoc();
9342   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9343   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9344   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9345                                    rax.getValue(2));
9346   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9347                             DAG.getConstant(32, MVT::i8));
9348   SDValue Ops[] = {
9349     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9350     rdx.getValue(1)
9351   };
9352   return DAG.getMergeValues(Ops, 2, dl);
9353 }
9354
9355 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9356                                             SelectionDAG &DAG) const {
9357   EVT SrcVT = Op.getOperand(0).getValueType();
9358   EVT DstVT = Op.getValueType();
9359   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9360          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9361   assert((DstVT == MVT::i64 ||
9362           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9363          "Unexpected custom BITCAST");
9364   // i64 <=> MMX conversions are Legal.
9365   if (SrcVT==MVT::i64 && DstVT.isVector())
9366     return Op;
9367   if (DstVT==MVT::i64 && SrcVT.isVector())
9368     return Op;
9369   // MMX <=> MMX conversions are Legal.
9370   if (SrcVT.isVector() && DstVT.isVector())
9371     return Op;
9372   // All other conversions need to be expanded.
9373   return SDValue();
9374 }
9375
9376 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9377   SDNode *Node = Op.getNode();
9378   DebugLoc dl = Node->getDebugLoc();
9379   EVT T = Node->getValueType(0);
9380   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9381                               DAG.getConstant(0, T), Node->getOperand(2));
9382   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9383                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9384                        Node->getOperand(0),
9385                        Node->getOperand(1), negOp,
9386                        cast<AtomicSDNode>(Node)->getSrcValue(),
9387                        cast<AtomicSDNode>(Node)->getAlignment());
9388 }
9389
9390 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9391   EVT VT = Op.getNode()->getValueType(0);
9392
9393   // Let legalize expand this if it isn't a legal type yet.
9394   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9395     return SDValue();
9396
9397   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9398
9399   unsigned Opc;
9400   bool ExtraOp = false;
9401   switch (Op.getOpcode()) {
9402   default: assert(0 && "Invalid code");
9403   case ISD::ADDC: Opc = X86ISD::ADD; break;
9404   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9405   case ISD::SUBC: Opc = X86ISD::SUB; break;
9406   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9407   }
9408
9409   if (!ExtraOp)
9410     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9411                        Op.getOperand(1));
9412   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9413                      Op.getOperand(1), Op.getOperand(2));
9414 }
9415
9416 /// LowerOperation - Provide custom lowering hooks for some operations.
9417 ///
9418 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9419   switch (Op.getOpcode()) {
9420   default: llvm_unreachable("Should not custom lower this!");
9421   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
9422   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9423   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9424   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9425   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9426   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9427   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9428   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9429   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9430   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9431   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9432   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9433   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9434   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9435   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9436   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9437   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9438   case ISD::SHL_PARTS:
9439   case ISD::SRA_PARTS:
9440   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9441   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9442   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9443   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9444   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9445   case ISD::FABS:               return LowerFABS(Op, DAG);
9446   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9447   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9448   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9449   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9450   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9451   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9452   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9453   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9454   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9455   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9456   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9457   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9458   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9459   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9460   case ISD::FRAME_TO_ARGS_OFFSET:
9461                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9462   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9463   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9464   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9465   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9466   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9467   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9468   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9469   case ISD::SRA:
9470   case ISD::SRL:
9471   case ISD::SHL:                return LowerShift(Op, DAG);
9472   case ISD::SADDO:
9473   case ISD::UADDO:
9474   case ISD::SSUBO:
9475   case ISD::USUBO:
9476   case ISD::SMULO:
9477   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9478   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9479   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9480   case ISD::ADDC:
9481   case ISD::ADDE:
9482   case ISD::SUBC:
9483   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9484   }
9485 }
9486
9487 void X86TargetLowering::
9488 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9489                         SelectionDAG &DAG, unsigned NewOp) const {
9490   EVT T = Node->getValueType(0);
9491   DebugLoc dl = Node->getDebugLoc();
9492   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9493
9494   SDValue Chain = Node->getOperand(0);
9495   SDValue In1 = Node->getOperand(1);
9496   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9497                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9498   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9499                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9500   SDValue Ops[] = { Chain, In1, In2L, In2H };
9501   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9502   SDValue Result =
9503     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9504                             cast<MemSDNode>(Node)->getMemOperand());
9505   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9506   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9507   Results.push_back(Result.getValue(2));
9508 }
9509
9510 /// ReplaceNodeResults - Replace a node with an illegal result type
9511 /// with a new node built out of custom code.
9512 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9513                                            SmallVectorImpl<SDValue>&Results,
9514                                            SelectionDAG &DAG) const {
9515   DebugLoc dl = N->getDebugLoc();
9516   switch (N->getOpcode()) {
9517   default:
9518     assert(false && "Do not know how to custom type legalize this operation!");
9519     return;
9520   case ISD::SIGN_EXTEND_INREG:
9521   case ISD::ADDC:
9522   case ISD::ADDE:
9523   case ISD::SUBC:
9524   case ISD::SUBE:
9525     // We don't want to expand or promote these.
9526     return;
9527   case ISD::FP_TO_SINT: {
9528     std::pair<SDValue,SDValue> Vals =
9529         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9530     SDValue FIST = Vals.first, StackSlot = Vals.second;
9531     if (FIST.getNode() != 0) {
9532       EVT VT = N->getValueType(0);
9533       // Return a load from the stack slot.
9534       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9535                                     MachinePointerInfo(), false, false, 0));
9536     }
9537     return;
9538   }
9539   case ISD::READCYCLECOUNTER: {
9540     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9541     SDValue TheChain = N->getOperand(0);
9542     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9543     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9544                                      rd.getValue(1));
9545     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9546                                      eax.getValue(2));
9547     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9548     SDValue Ops[] = { eax, edx };
9549     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9550     Results.push_back(edx.getValue(1));
9551     return;
9552   }
9553   case ISD::ATOMIC_CMP_SWAP: {
9554     EVT T = N->getValueType(0);
9555     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9556     SDValue cpInL, cpInH;
9557     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9558                         DAG.getConstant(0, MVT::i32));
9559     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9560                         DAG.getConstant(1, MVT::i32));
9561     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9562     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9563                              cpInL.getValue(1));
9564     SDValue swapInL, swapInH;
9565     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9566                           DAG.getConstant(0, MVT::i32));
9567     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9568                           DAG.getConstant(1, MVT::i32));
9569     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9570                                cpInH.getValue(1));
9571     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9572                                swapInL.getValue(1));
9573     SDValue Ops[] = { swapInH.getValue(0),
9574                       N->getOperand(1),
9575                       swapInH.getValue(1) };
9576     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9577     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9578     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9579                                              Ops, 3, T, MMO);
9580     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9581                                         MVT::i32, Result.getValue(1));
9582     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9583                                         MVT::i32, cpOutL.getValue(2));
9584     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9585     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9586     Results.push_back(cpOutH.getValue(1));
9587     return;
9588   }
9589   case ISD::ATOMIC_LOAD_ADD:
9590     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9591     return;
9592   case ISD::ATOMIC_LOAD_AND:
9593     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9594     return;
9595   case ISD::ATOMIC_LOAD_NAND:
9596     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9597     return;
9598   case ISD::ATOMIC_LOAD_OR:
9599     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9600     return;
9601   case ISD::ATOMIC_LOAD_SUB:
9602     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9603     return;
9604   case ISD::ATOMIC_LOAD_XOR:
9605     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9606     return;
9607   case ISD::ATOMIC_SWAP:
9608     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9609     return;
9610   }
9611 }
9612
9613 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9614   switch (Opcode) {
9615   default: return NULL;
9616   case X86ISD::BSF:                return "X86ISD::BSF";
9617   case X86ISD::BSR:                return "X86ISD::BSR";
9618   case X86ISD::SHLD:               return "X86ISD::SHLD";
9619   case X86ISD::SHRD:               return "X86ISD::SHRD";
9620   case X86ISD::FAND:               return "X86ISD::FAND";
9621   case X86ISD::FOR:                return "X86ISD::FOR";
9622   case X86ISD::FXOR:               return "X86ISD::FXOR";
9623   case X86ISD::FSRL:               return "X86ISD::FSRL";
9624   case X86ISD::FILD:               return "X86ISD::FILD";
9625   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9626   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9627   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9628   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9629   case X86ISD::FLD:                return "X86ISD::FLD";
9630   case X86ISD::FST:                return "X86ISD::FST";
9631   case X86ISD::CALL:               return "X86ISD::CALL";
9632   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9633   case X86ISD::BT:                 return "X86ISD::BT";
9634   case X86ISD::CMP:                return "X86ISD::CMP";
9635   case X86ISD::COMI:               return "X86ISD::COMI";
9636   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9637   case X86ISD::SETCC:              return "X86ISD::SETCC";
9638   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9639   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9640   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9641   case X86ISD::CMOV:               return "X86ISD::CMOV";
9642   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9643   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9644   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9645   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9646   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9647   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9648   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9649   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9650   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9651   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9652   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9653   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9654   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9655   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
9656   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9657   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9658   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9659   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9660   case X86ISD::FMAX:               return "X86ISD::FMAX";
9661   case X86ISD::FMIN:               return "X86ISD::FMIN";
9662   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9663   case X86ISD::FRCP:               return "X86ISD::FRCP";
9664   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9665   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9666   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9667   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9668   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9669   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9670   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9671   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9672   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9673   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9674   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9675   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9676   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9677   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9678   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9679   case X86ISD::VSHL:               return "X86ISD::VSHL";
9680   case X86ISD::VSRL:               return "X86ISD::VSRL";
9681   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9682   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9683   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9684   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9685   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9686   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9687   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9688   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9689   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9690   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9691   case X86ISD::ADD:                return "X86ISD::ADD";
9692   case X86ISD::SUB:                return "X86ISD::SUB";
9693   case X86ISD::ADC:                return "X86ISD::ADC";
9694   case X86ISD::SBB:                return "X86ISD::SBB";
9695   case X86ISD::SMUL:               return "X86ISD::SMUL";
9696   case X86ISD::UMUL:               return "X86ISD::UMUL";
9697   case X86ISD::INC:                return "X86ISD::INC";
9698   case X86ISD::DEC:                return "X86ISD::DEC";
9699   case X86ISD::OR:                 return "X86ISD::OR";
9700   case X86ISD::XOR:                return "X86ISD::XOR";
9701   case X86ISD::AND:                return "X86ISD::AND";
9702   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9703   case X86ISD::PTEST:              return "X86ISD::PTEST";
9704   case X86ISD::TESTP:              return "X86ISD::TESTP";
9705   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9706   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9707   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9708   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9709   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9710   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9711   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9712   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9713   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9714   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9715   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9716   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9717   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9718   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9719   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9720   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9721   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9722   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9723   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9724   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9725   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9726   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9727   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9728   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9729   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9730   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9731   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9732   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9733   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9734   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9735   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9736   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9737   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9738   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9739   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9740   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9741   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9742   case X86ISD::VPERMIL:            return "X86ISD::VPERMIL";
9743   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9744   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9745   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9746   }
9747 }
9748
9749 // isLegalAddressingMode - Return true if the addressing mode represented
9750 // by AM is legal for this target, for a load/store of the specified type.
9751 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9752                                               Type *Ty) const {
9753   // X86 supports extremely general addressing modes.
9754   CodeModel::Model M = getTargetMachine().getCodeModel();
9755   Reloc::Model R = getTargetMachine().getRelocationModel();
9756
9757   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9758   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9759     return false;
9760
9761   if (AM.BaseGV) {
9762     unsigned GVFlags =
9763       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9764
9765     // If a reference to this global requires an extra load, we can't fold it.
9766     if (isGlobalStubReference(GVFlags))
9767       return false;
9768
9769     // If BaseGV requires a register for the PIC base, we cannot also have a
9770     // BaseReg specified.
9771     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9772       return false;
9773
9774     // If lower 4G is not available, then we must use rip-relative addressing.
9775     if ((M != CodeModel::Small || R != Reloc::Static) &&
9776         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9777       return false;
9778   }
9779
9780   switch (AM.Scale) {
9781   case 0:
9782   case 1:
9783   case 2:
9784   case 4:
9785   case 8:
9786     // These scales always work.
9787     break;
9788   case 3:
9789   case 5:
9790   case 9:
9791     // These scales are formed with basereg+scalereg.  Only accept if there is
9792     // no basereg yet.
9793     if (AM.HasBaseReg)
9794       return false;
9795     break;
9796   default:  // Other stuff never works.
9797     return false;
9798   }
9799
9800   return true;
9801 }
9802
9803
9804 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9805   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9806     return false;
9807   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9808   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9809   if (NumBits1 <= NumBits2)
9810     return false;
9811   return true;
9812 }
9813
9814 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9815   if (!VT1.isInteger() || !VT2.isInteger())
9816     return false;
9817   unsigned NumBits1 = VT1.getSizeInBits();
9818   unsigned NumBits2 = VT2.getSizeInBits();
9819   if (NumBits1 <= NumBits2)
9820     return false;
9821   return true;
9822 }
9823
9824 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9825   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9826   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9827 }
9828
9829 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9830   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9831   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9832 }
9833
9834 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9835   // i16 instructions are longer (0x66 prefix) and potentially slower.
9836   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9837 }
9838
9839 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9840 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9841 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9842 /// are assumed to be legal.
9843 bool
9844 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9845                                       EVT VT) const {
9846   // Very little shuffling can be done for 64-bit vectors right now.
9847   if (VT.getSizeInBits() == 64)
9848     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9849
9850   // FIXME: pshufb, blends, shifts.
9851   return (VT.getVectorNumElements() == 2 ||
9852           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9853           isMOVLMask(M, VT) ||
9854           isSHUFPMask(M, VT) ||
9855           isPSHUFDMask(M, VT) ||
9856           isPSHUFHWMask(M, VT) ||
9857           isPSHUFLWMask(M, VT) ||
9858           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9859           isUNPCKLMask(M, VT) ||
9860           isUNPCKHMask(M, VT) ||
9861           isUNPCKL_v_undef_Mask(M, VT) ||
9862           isUNPCKH_v_undef_Mask(M, VT));
9863 }
9864
9865 bool
9866 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9867                                           EVT VT) const {
9868   unsigned NumElts = VT.getVectorNumElements();
9869   // FIXME: This collection of masks seems suspect.
9870   if (NumElts == 2)
9871     return true;
9872   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9873     return (isMOVLMask(Mask, VT)  ||
9874             isCommutedMOVLMask(Mask, VT, true) ||
9875             isSHUFPMask(Mask, VT) ||
9876             isCommutedSHUFPMask(Mask, VT));
9877   }
9878   return false;
9879 }
9880
9881 //===----------------------------------------------------------------------===//
9882 //                           X86 Scheduler Hooks
9883 //===----------------------------------------------------------------------===//
9884
9885 // private utility function
9886 MachineBasicBlock *
9887 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9888                                                        MachineBasicBlock *MBB,
9889                                                        unsigned regOpc,
9890                                                        unsigned immOpc,
9891                                                        unsigned LoadOpc,
9892                                                        unsigned CXchgOpc,
9893                                                        unsigned notOpc,
9894                                                        unsigned EAXreg,
9895                                                        TargetRegisterClass *RC,
9896                                                        bool invSrc) const {
9897   // For the atomic bitwise operator, we generate
9898   //   thisMBB:
9899   //   newMBB:
9900   //     ld  t1 = [bitinstr.addr]
9901   //     op  t2 = t1, [bitinstr.val]
9902   //     mov EAX = t1
9903   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9904   //     bz  newMBB
9905   //     fallthrough -->nextMBB
9906   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9907   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9908   MachineFunction::iterator MBBIter = MBB;
9909   ++MBBIter;
9910
9911   /// First build the CFG
9912   MachineFunction *F = MBB->getParent();
9913   MachineBasicBlock *thisMBB = MBB;
9914   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9915   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9916   F->insert(MBBIter, newMBB);
9917   F->insert(MBBIter, nextMBB);
9918
9919   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9920   nextMBB->splice(nextMBB->begin(), thisMBB,
9921                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9922                   thisMBB->end());
9923   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9924
9925   // Update thisMBB to fall through to newMBB
9926   thisMBB->addSuccessor(newMBB);
9927
9928   // newMBB jumps to itself and fall through to nextMBB
9929   newMBB->addSuccessor(nextMBB);
9930   newMBB->addSuccessor(newMBB);
9931
9932   // Insert instructions into newMBB based on incoming instruction
9933   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9934          "unexpected number of operands");
9935   DebugLoc dl = bInstr->getDebugLoc();
9936   MachineOperand& destOper = bInstr->getOperand(0);
9937   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9938   int numArgs = bInstr->getNumOperands() - 1;
9939   for (int i=0; i < numArgs; ++i)
9940     argOpers[i] = &bInstr->getOperand(i+1);
9941
9942   // x86 address has 4 operands: base, index, scale, and displacement
9943   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9944   int valArgIndx = lastAddrIndx + 1;
9945
9946   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9947   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9948   for (int i=0; i <= lastAddrIndx; ++i)
9949     (*MIB).addOperand(*argOpers[i]);
9950
9951   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9952   if (invSrc) {
9953     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9954   }
9955   else
9956     tt = t1;
9957
9958   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9959   assert((argOpers[valArgIndx]->isReg() ||
9960           argOpers[valArgIndx]->isImm()) &&
9961          "invalid operand");
9962   if (argOpers[valArgIndx]->isReg())
9963     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9964   else
9965     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9966   MIB.addReg(tt);
9967   (*MIB).addOperand(*argOpers[valArgIndx]);
9968
9969   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9970   MIB.addReg(t1);
9971
9972   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9973   for (int i=0; i <= lastAddrIndx; ++i)
9974     (*MIB).addOperand(*argOpers[i]);
9975   MIB.addReg(t2);
9976   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9977   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9978                     bInstr->memoperands_end());
9979
9980   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9981   MIB.addReg(EAXreg);
9982
9983   // insert branch
9984   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9985
9986   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9987   return nextMBB;
9988 }
9989
9990 // private utility function:  64 bit atomics on 32 bit host.
9991 MachineBasicBlock *
9992 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9993                                                        MachineBasicBlock *MBB,
9994                                                        unsigned regOpcL,
9995                                                        unsigned regOpcH,
9996                                                        unsigned immOpcL,
9997                                                        unsigned immOpcH,
9998                                                        bool invSrc) const {
9999   // For the atomic bitwise operator, we generate
10000   //   thisMBB (instructions are in pairs, except cmpxchg8b)
10001   //     ld t1,t2 = [bitinstr.addr]
10002   //   newMBB:
10003   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10004   //     op  t5, t6 <- out1, out2, [bitinstr.val]
10005   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
10006   //     mov ECX, EBX <- t5, t6
10007   //     mov EAX, EDX <- t1, t2
10008   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
10009   //     mov t3, t4 <- EAX, EDX
10010   //     bz  newMBB
10011   //     result in out1, out2
10012   //     fallthrough -->nextMBB
10013
10014   const TargetRegisterClass *RC = X86::GR32RegisterClass;
10015   const unsigned LoadOpc = X86::MOV32rm;
10016   const unsigned NotOpc = X86::NOT32r;
10017   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10018   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10019   MachineFunction::iterator MBBIter = MBB;
10020   ++MBBIter;
10021
10022   /// First build the CFG
10023   MachineFunction *F = MBB->getParent();
10024   MachineBasicBlock *thisMBB = MBB;
10025   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10026   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10027   F->insert(MBBIter, newMBB);
10028   F->insert(MBBIter, nextMBB);
10029
10030   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10031   nextMBB->splice(nextMBB->begin(), thisMBB,
10032                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10033                   thisMBB->end());
10034   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10035
10036   // Update thisMBB to fall through to newMBB
10037   thisMBB->addSuccessor(newMBB);
10038
10039   // newMBB jumps to itself and fall through to nextMBB
10040   newMBB->addSuccessor(nextMBB);
10041   newMBB->addSuccessor(newMBB);
10042
10043   DebugLoc dl = bInstr->getDebugLoc();
10044   // Insert instructions into newMBB based on incoming instruction
10045   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10046   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10047          "unexpected number of operands");
10048   MachineOperand& dest1Oper = bInstr->getOperand(0);
10049   MachineOperand& dest2Oper = bInstr->getOperand(1);
10050   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10051   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10052     argOpers[i] = &bInstr->getOperand(i+2);
10053
10054     // We use some of the operands multiple times, so conservatively just
10055     // clear any kill flags that might be present.
10056     if (argOpers[i]->isReg() && argOpers[i]->isUse())
10057       argOpers[i]->setIsKill(false);
10058   }
10059
10060   // x86 address has 5 operands: base, index, scale, displacement, and segment.
10061   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10062
10063   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10064   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10065   for (int i=0; i <= lastAddrIndx; ++i)
10066     (*MIB).addOperand(*argOpers[i]);
10067   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10068   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10069   // add 4 to displacement.
10070   for (int i=0; i <= lastAddrIndx-2; ++i)
10071     (*MIB).addOperand(*argOpers[i]);
10072   MachineOperand newOp3 = *(argOpers[3]);
10073   if (newOp3.isImm())
10074     newOp3.setImm(newOp3.getImm()+4);
10075   else
10076     newOp3.setOffset(newOp3.getOffset()+4);
10077   (*MIB).addOperand(newOp3);
10078   (*MIB).addOperand(*argOpers[lastAddrIndx]);
10079
10080   // t3/4 are defined later, at the bottom of the loop
10081   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10082   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10083   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10084     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10085   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10086     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10087
10088   // The subsequent operations should be using the destination registers of
10089   //the PHI instructions.
10090   if (invSrc) {
10091     t1 = F->getRegInfo().createVirtualRegister(RC);
10092     t2 = F->getRegInfo().createVirtualRegister(RC);
10093     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10094     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10095   } else {
10096     t1 = dest1Oper.getReg();
10097     t2 = dest2Oper.getReg();
10098   }
10099
10100   int valArgIndx = lastAddrIndx + 1;
10101   assert((argOpers[valArgIndx]->isReg() ||
10102           argOpers[valArgIndx]->isImm()) &&
10103          "invalid operand");
10104   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10105   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10106   if (argOpers[valArgIndx]->isReg())
10107     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10108   else
10109     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10110   if (regOpcL != X86::MOV32rr)
10111     MIB.addReg(t1);
10112   (*MIB).addOperand(*argOpers[valArgIndx]);
10113   assert(argOpers[valArgIndx + 1]->isReg() ==
10114          argOpers[valArgIndx]->isReg());
10115   assert(argOpers[valArgIndx + 1]->isImm() ==
10116          argOpers[valArgIndx]->isImm());
10117   if (argOpers[valArgIndx + 1]->isReg())
10118     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10119   else
10120     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10121   if (regOpcH != X86::MOV32rr)
10122     MIB.addReg(t2);
10123   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10124
10125   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10126   MIB.addReg(t1);
10127   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10128   MIB.addReg(t2);
10129
10130   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10131   MIB.addReg(t5);
10132   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10133   MIB.addReg(t6);
10134
10135   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10136   for (int i=0; i <= lastAddrIndx; ++i)
10137     (*MIB).addOperand(*argOpers[i]);
10138
10139   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10140   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10141                     bInstr->memoperands_end());
10142
10143   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10144   MIB.addReg(X86::EAX);
10145   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10146   MIB.addReg(X86::EDX);
10147
10148   // insert branch
10149   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10150
10151   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10152   return nextMBB;
10153 }
10154
10155 // private utility function
10156 MachineBasicBlock *
10157 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10158                                                       MachineBasicBlock *MBB,
10159                                                       unsigned cmovOpc) const {
10160   // For the atomic min/max operator, we generate
10161   //   thisMBB:
10162   //   newMBB:
10163   //     ld t1 = [min/max.addr]
10164   //     mov t2 = [min/max.val]
10165   //     cmp  t1, t2
10166   //     cmov[cond] t2 = t1
10167   //     mov EAX = t1
10168   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10169   //     bz   newMBB
10170   //     fallthrough -->nextMBB
10171   //
10172   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10173   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10174   MachineFunction::iterator MBBIter = MBB;
10175   ++MBBIter;
10176
10177   /// First build the CFG
10178   MachineFunction *F = MBB->getParent();
10179   MachineBasicBlock *thisMBB = MBB;
10180   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10181   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10182   F->insert(MBBIter, newMBB);
10183   F->insert(MBBIter, nextMBB);
10184
10185   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10186   nextMBB->splice(nextMBB->begin(), thisMBB,
10187                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10188                   thisMBB->end());
10189   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10190
10191   // Update thisMBB to fall through to newMBB
10192   thisMBB->addSuccessor(newMBB);
10193
10194   // newMBB jumps to newMBB and fall through to nextMBB
10195   newMBB->addSuccessor(nextMBB);
10196   newMBB->addSuccessor(newMBB);
10197
10198   DebugLoc dl = mInstr->getDebugLoc();
10199   // Insert instructions into newMBB based on incoming instruction
10200   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10201          "unexpected number of operands");
10202   MachineOperand& destOper = mInstr->getOperand(0);
10203   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10204   int numArgs = mInstr->getNumOperands() - 1;
10205   for (int i=0; i < numArgs; ++i)
10206     argOpers[i] = &mInstr->getOperand(i+1);
10207
10208   // x86 address has 4 operands: base, index, scale, and displacement
10209   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10210   int valArgIndx = lastAddrIndx + 1;
10211
10212   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10213   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10214   for (int i=0; i <= lastAddrIndx; ++i)
10215     (*MIB).addOperand(*argOpers[i]);
10216
10217   // We only support register and immediate values
10218   assert((argOpers[valArgIndx]->isReg() ||
10219           argOpers[valArgIndx]->isImm()) &&
10220          "invalid operand");
10221
10222   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10223   if (argOpers[valArgIndx]->isReg())
10224     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10225   else
10226     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10227   (*MIB).addOperand(*argOpers[valArgIndx]);
10228
10229   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10230   MIB.addReg(t1);
10231
10232   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10233   MIB.addReg(t1);
10234   MIB.addReg(t2);
10235
10236   // Generate movc
10237   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10238   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10239   MIB.addReg(t2);
10240   MIB.addReg(t1);
10241
10242   // Cmp and exchange if none has modified the memory location
10243   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10244   for (int i=0; i <= lastAddrIndx; ++i)
10245     (*MIB).addOperand(*argOpers[i]);
10246   MIB.addReg(t3);
10247   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10248   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10249                     mInstr->memoperands_end());
10250
10251   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10252   MIB.addReg(X86::EAX);
10253
10254   // insert branch
10255   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10256
10257   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10258   return nextMBB;
10259 }
10260
10261 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10262 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10263 // in the .td file.
10264 MachineBasicBlock *
10265 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10266                             unsigned numArgs, bool memArg) const {
10267   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10268          "Target must have SSE4.2 or AVX features enabled");
10269
10270   DebugLoc dl = MI->getDebugLoc();
10271   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10272   unsigned Opc;
10273   if (!Subtarget->hasAVX()) {
10274     if (memArg)
10275       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10276     else
10277       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10278   } else {
10279     if (memArg)
10280       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10281     else
10282       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10283   }
10284
10285   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10286   for (unsigned i = 0; i < numArgs; ++i) {
10287     MachineOperand &Op = MI->getOperand(i+1);
10288     if (!(Op.isReg() && Op.isImplicit()))
10289       MIB.addOperand(Op);
10290   }
10291   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10292     .addReg(X86::XMM0);
10293
10294   MI->eraseFromParent();
10295   return BB;
10296 }
10297
10298 MachineBasicBlock *
10299 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10300   DebugLoc dl = MI->getDebugLoc();
10301   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10302
10303   // Address into RAX/EAX, other two args into ECX, EDX.
10304   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10305   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10306   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10307   for (int i = 0; i < X86::AddrNumOperands; ++i)
10308     MIB.addOperand(MI->getOperand(i));
10309
10310   unsigned ValOps = X86::AddrNumOperands;
10311   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10312     .addReg(MI->getOperand(ValOps).getReg());
10313   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10314     .addReg(MI->getOperand(ValOps+1).getReg());
10315
10316   // The instruction doesn't actually take any operands though.
10317   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10318
10319   MI->eraseFromParent(); // The pseudo is gone now.
10320   return BB;
10321 }
10322
10323 MachineBasicBlock *
10324 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10325   DebugLoc dl = MI->getDebugLoc();
10326   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10327
10328   // First arg in ECX, the second in EAX.
10329   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10330     .addReg(MI->getOperand(0).getReg());
10331   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10332     .addReg(MI->getOperand(1).getReg());
10333
10334   // The instruction doesn't actually take any operands though.
10335   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10336
10337   MI->eraseFromParent(); // The pseudo is gone now.
10338   return BB;
10339 }
10340
10341 MachineBasicBlock *
10342 X86TargetLowering::EmitVAARG64WithCustomInserter(
10343                    MachineInstr *MI,
10344                    MachineBasicBlock *MBB) const {
10345   // Emit va_arg instruction on X86-64.
10346
10347   // Operands to this pseudo-instruction:
10348   // 0  ) Output        : destination address (reg)
10349   // 1-5) Input         : va_list address (addr, i64mem)
10350   // 6  ) ArgSize       : Size (in bytes) of vararg type
10351   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10352   // 8  ) Align         : Alignment of type
10353   // 9  ) EFLAGS (implicit-def)
10354
10355   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10356   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10357
10358   unsigned DestReg = MI->getOperand(0).getReg();
10359   MachineOperand &Base = MI->getOperand(1);
10360   MachineOperand &Scale = MI->getOperand(2);
10361   MachineOperand &Index = MI->getOperand(3);
10362   MachineOperand &Disp = MI->getOperand(4);
10363   MachineOperand &Segment = MI->getOperand(5);
10364   unsigned ArgSize = MI->getOperand(6).getImm();
10365   unsigned ArgMode = MI->getOperand(7).getImm();
10366   unsigned Align = MI->getOperand(8).getImm();
10367
10368   // Memory Reference
10369   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10370   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10371   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10372
10373   // Machine Information
10374   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10375   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10376   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10377   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10378   DebugLoc DL = MI->getDebugLoc();
10379
10380   // struct va_list {
10381   //   i32   gp_offset
10382   //   i32   fp_offset
10383   //   i64   overflow_area (address)
10384   //   i64   reg_save_area (address)
10385   // }
10386   // sizeof(va_list) = 24
10387   // alignment(va_list) = 8
10388
10389   unsigned TotalNumIntRegs = 6;
10390   unsigned TotalNumXMMRegs = 8;
10391   bool UseGPOffset = (ArgMode == 1);
10392   bool UseFPOffset = (ArgMode == 2);
10393   unsigned MaxOffset = TotalNumIntRegs * 8 +
10394                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10395
10396   /* Align ArgSize to a multiple of 8 */
10397   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10398   bool NeedsAlign = (Align > 8);
10399
10400   MachineBasicBlock *thisMBB = MBB;
10401   MachineBasicBlock *overflowMBB;
10402   MachineBasicBlock *offsetMBB;
10403   MachineBasicBlock *endMBB;
10404
10405   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10406   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10407   unsigned OffsetReg = 0;
10408
10409   if (!UseGPOffset && !UseFPOffset) {
10410     // If we only pull from the overflow region, we don't create a branch.
10411     // We don't need to alter control flow.
10412     OffsetDestReg = 0; // unused
10413     OverflowDestReg = DestReg;
10414
10415     offsetMBB = NULL;
10416     overflowMBB = thisMBB;
10417     endMBB = thisMBB;
10418   } else {
10419     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10420     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10421     // If not, pull from overflow_area. (branch to overflowMBB)
10422     //
10423     //       thisMBB
10424     //         |     .
10425     //         |        .
10426     //     offsetMBB   overflowMBB
10427     //         |        .
10428     //         |     .
10429     //        endMBB
10430
10431     // Registers for the PHI in endMBB
10432     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10433     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10434
10435     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10436     MachineFunction *MF = MBB->getParent();
10437     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10438     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10439     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10440
10441     MachineFunction::iterator MBBIter = MBB;
10442     ++MBBIter;
10443
10444     // Insert the new basic blocks
10445     MF->insert(MBBIter, offsetMBB);
10446     MF->insert(MBBIter, overflowMBB);
10447     MF->insert(MBBIter, endMBB);
10448
10449     // Transfer the remainder of MBB and its successor edges to endMBB.
10450     endMBB->splice(endMBB->begin(), thisMBB,
10451                     llvm::next(MachineBasicBlock::iterator(MI)),
10452                     thisMBB->end());
10453     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10454
10455     // Make offsetMBB and overflowMBB successors of thisMBB
10456     thisMBB->addSuccessor(offsetMBB);
10457     thisMBB->addSuccessor(overflowMBB);
10458
10459     // endMBB is a successor of both offsetMBB and overflowMBB
10460     offsetMBB->addSuccessor(endMBB);
10461     overflowMBB->addSuccessor(endMBB);
10462
10463     // Load the offset value into a register
10464     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10465     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10466       .addOperand(Base)
10467       .addOperand(Scale)
10468       .addOperand(Index)
10469       .addDisp(Disp, UseFPOffset ? 4 : 0)
10470       .addOperand(Segment)
10471       .setMemRefs(MMOBegin, MMOEnd);
10472
10473     // Check if there is enough room left to pull this argument.
10474     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10475       .addReg(OffsetReg)
10476       .addImm(MaxOffset + 8 - ArgSizeA8);
10477
10478     // Branch to "overflowMBB" if offset >= max
10479     // Fall through to "offsetMBB" otherwise
10480     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10481       .addMBB(overflowMBB);
10482   }
10483
10484   // In offsetMBB, emit code to use the reg_save_area.
10485   if (offsetMBB) {
10486     assert(OffsetReg != 0);
10487
10488     // Read the reg_save_area address.
10489     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10490     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10491       .addOperand(Base)
10492       .addOperand(Scale)
10493       .addOperand(Index)
10494       .addDisp(Disp, 16)
10495       .addOperand(Segment)
10496       .setMemRefs(MMOBegin, MMOEnd);
10497
10498     // Zero-extend the offset
10499     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10500       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10501         .addImm(0)
10502         .addReg(OffsetReg)
10503         .addImm(X86::sub_32bit);
10504
10505     // Add the offset to the reg_save_area to get the final address.
10506     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10507       .addReg(OffsetReg64)
10508       .addReg(RegSaveReg);
10509
10510     // Compute the offset for the next argument
10511     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10512     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10513       .addReg(OffsetReg)
10514       .addImm(UseFPOffset ? 16 : 8);
10515
10516     // Store it back into the va_list.
10517     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10518       .addOperand(Base)
10519       .addOperand(Scale)
10520       .addOperand(Index)
10521       .addDisp(Disp, UseFPOffset ? 4 : 0)
10522       .addOperand(Segment)
10523       .addReg(NextOffsetReg)
10524       .setMemRefs(MMOBegin, MMOEnd);
10525
10526     // Jump to endMBB
10527     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10528       .addMBB(endMBB);
10529   }
10530
10531   //
10532   // Emit code to use overflow area
10533   //
10534
10535   // Load the overflow_area address into a register.
10536   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10537   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10538     .addOperand(Base)
10539     .addOperand(Scale)
10540     .addOperand(Index)
10541     .addDisp(Disp, 8)
10542     .addOperand(Segment)
10543     .setMemRefs(MMOBegin, MMOEnd);
10544
10545   // If we need to align it, do so. Otherwise, just copy the address
10546   // to OverflowDestReg.
10547   if (NeedsAlign) {
10548     // Align the overflow address
10549     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10550     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10551
10552     // aligned_addr = (addr + (align-1)) & ~(align-1)
10553     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10554       .addReg(OverflowAddrReg)
10555       .addImm(Align-1);
10556
10557     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10558       .addReg(TmpReg)
10559       .addImm(~(uint64_t)(Align-1));
10560   } else {
10561     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10562       .addReg(OverflowAddrReg);
10563   }
10564
10565   // Compute the next overflow address after this argument.
10566   // (the overflow address should be kept 8-byte aligned)
10567   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10568   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10569     .addReg(OverflowDestReg)
10570     .addImm(ArgSizeA8);
10571
10572   // Store the new overflow address.
10573   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10574     .addOperand(Base)
10575     .addOperand(Scale)
10576     .addOperand(Index)
10577     .addDisp(Disp, 8)
10578     .addOperand(Segment)
10579     .addReg(NextAddrReg)
10580     .setMemRefs(MMOBegin, MMOEnd);
10581
10582   // If we branched, emit the PHI to the front of endMBB.
10583   if (offsetMBB) {
10584     BuildMI(*endMBB, endMBB->begin(), DL,
10585             TII->get(X86::PHI), DestReg)
10586       .addReg(OffsetDestReg).addMBB(offsetMBB)
10587       .addReg(OverflowDestReg).addMBB(overflowMBB);
10588   }
10589
10590   // Erase the pseudo instruction
10591   MI->eraseFromParent();
10592
10593   return endMBB;
10594 }
10595
10596 MachineBasicBlock *
10597 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10598                                                  MachineInstr *MI,
10599                                                  MachineBasicBlock *MBB) const {
10600   // Emit code to save XMM registers to the stack. The ABI says that the
10601   // number of registers to save is given in %al, so it's theoretically
10602   // possible to do an indirect jump trick to avoid saving all of them,
10603   // however this code takes a simpler approach and just executes all
10604   // of the stores if %al is non-zero. It's less code, and it's probably
10605   // easier on the hardware branch predictor, and stores aren't all that
10606   // expensive anyway.
10607
10608   // Create the new basic blocks. One block contains all the XMM stores,
10609   // and one block is the final destination regardless of whether any
10610   // stores were performed.
10611   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10612   MachineFunction *F = MBB->getParent();
10613   MachineFunction::iterator MBBIter = MBB;
10614   ++MBBIter;
10615   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10616   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10617   F->insert(MBBIter, XMMSaveMBB);
10618   F->insert(MBBIter, EndMBB);
10619
10620   // Transfer the remainder of MBB and its successor edges to EndMBB.
10621   EndMBB->splice(EndMBB->begin(), MBB,
10622                  llvm::next(MachineBasicBlock::iterator(MI)),
10623                  MBB->end());
10624   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10625
10626   // The original block will now fall through to the XMM save block.
10627   MBB->addSuccessor(XMMSaveMBB);
10628   // The XMMSaveMBB will fall through to the end block.
10629   XMMSaveMBB->addSuccessor(EndMBB);
10630
10631   // Now add the instructions.
10632   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10633   DebugLoc DL = MI->getDebugLoc();
10634
10635   unsigned CountReg = MI->getOperand(0).getReg();
10636   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10637   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10638
10639   if (!Subtarget->isTargetWin64()) {
10640     // If %al is 0, branch around the XMM save block.
10641     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10642     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10643     MBB->addSuccessor(EndMBB);
10644   }
10645
10646   // In the XMM save block, save all the XMM argument registers.
10647   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10648     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10649     MachineMemOperand *MMO =
10650       F->getMachineMemOperand(
10651           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10652         MachineMemOperand::MOStore,
10653         /*Size=*/16, /*Align=*/16);
10654     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10655       .addFrameIndex(RegSaveFrameIndex)
10656       .addImm(/*Scale=*/1)
10657       .addReg(/*IndexReg=*/0)
10658       .addImm(/*Disp=*/Offset)
10659       .addReg(/*Segment=*/0)
10660       .addReg(MI->getOperand(i).getReg())
10661       .addMemOperand(MMO);
10662   }
10663
10664   MI->eraseFromParent();   // The pseudo instruction is gone now.
10665
10666   return EndMBB;
10667 }
10668
10669 MachineBasicBlock *
10670 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10671                                      MachineBasicBlock *BB) const {
10672   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10673   DebugLoc DL = MI->getDebugLoc();
10674
10675   // To "insert" a SELECT_CC instruction, we actually have to insert the
10676   // diamond control-flow pattern.  The incoming instruction knows the
10677   // destination vreg to set, the condition code register to branch on, the
10678   // true/false values to select between, and a branch opcode to use.
10679   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10680   MachineFunction::iterator It = BB;
10681   ++It;
10682
10683   //  thisMBB:
10684   //  ...
10685   //   TrueVal = ...
10686   //   cmpTY ccX, r1, r2
10687   //   bCC copy1MBB
10688   //   fallthrough --> copy0MBB
10689   MachineBasicBlock *thisMBB = BB;
10690   MachineFunction *F = BB->getParent();
10691   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10692   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10693   F->insert(It, copy0MBB);
10694   F->insert(It, sinkMBB);
10695
10696   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10697   // live into the sink and copy blocks.
10698   const MachineFunction *MF = BB->getParent();
10699   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10700   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10701
10702   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10703     const MachineOperand &MO = MI->getOperand(I);
10704     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10705     unsigned Reg = MO.getReg();
10706     if (Reg != X86::EFLAGS) continue;
10707     copy0MBB->addLiveIn(Reg);
10708     sinkMBB->addLiveIn(Reg);
10709   }
10710
10711   // Transfer the remainder of BB and its successor edges to sinkMBB.
10712   sinkMBB->splice(sinkMBB->begin(), BB,
10713                   llvm::next(MachineBasicBlock::iterator(MI)),
10714                   BB->end());
10715   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10716
10717   // Add the true and fallthrough blocks as its successors.
10718   BB->addSuccessor(copy0MBB);
10719   BB->addSuccessor(sinkMBB);
10720
10721   // Create the conditional branch instruction.
10722   unsigned Opc =
10723     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10724   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10725
10726   //  copy0MBB:
10727   //   %FalseValue = ...
10728   //   # fallthrough to sinkMBB
10729   copy0MBB->addSuccessor(sinkMBB);
10730
10731   //  sinkMBB:
10732   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10733   //  ...
10734   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10735           TII->get(X86::PHI), MI->getOperand(0).getReg())
10736     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10737     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10738
10739   MI->eraseFromParent();   // The pseudo instruction is gone now.
10740   return sinkMBB;
10741 }
10742
10743 MachineBasicBlock *
10744 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10745                                           MachineBasicBlock *BB) const {
10746   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10747   DebugLoc DL = MI->getDebugLoc();
10748
10749   assert(!Subtarget->isTargetEnvMacho());
10750
10751   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10752   // non-trivial part is impdef of ESP.
10753
10754   if (Subtarget->isTargetWin64()) {
10755     if (Subtarget->isTargetCygMing()) {
10756       // ___chkstk(Mingw64):
10757       // Clobbers R10, R11, RAX and EFLAGS.
10758       // Updates RSP.
10759       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10760         .addExternalSymbol("___chkstk")
10761         .addReg(X86::RAX, RegState::Implicit)
10762         .addReg(X86::RSP, RegState::Implicit)
10763         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10764         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10765         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10766     } else {
10767       // __chkstk(MSVCRT): does not update stack pointer.
10768       // Clobbers R10, R11 and EFLAGS.
10769       // FIXME: RAX(allocated size) might be reused and not killed.
10770       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10771         .addExternalSymbol("__chkstk")
10772         .addReg(X86::RAX, RegState::Implicit)
10773         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10774       // RAX has the offset to subtracted from RSP.
10775       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10776         .addReg(X86::RSP)
10777         .addReg(X86::RAX);
10778     }
10779   } else {
10780     const char *StackProbeSymbol =
10781       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10782
10783     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10784       .addExternalSymbol(StackProbeSymbol)
10785       .addReg(X86::EAX, RegState::Implicit)
10786       .addReg(X86::ESP, RegState::Implicit)
10787       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10788       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10789       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10790   }
10791
10792   MI->eraseFromParent();   // The pseudo instruction is gone now.
10793   return BB;
10794 }
10795
10796 MachineBasicBlock *
10797 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10798                                       MachineBasicBlock *BB) const {
10799   // This is pretty easy.  We're taking the value that we received from
10800   // our load from the relocation, sticking it in either RDI (x86-64)
10801   // or EAX and doing an indirect call.  The return value will then
10802   // be in the normal return register.
10803   const X86InstrInfo *TII
10804     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10805   DebugLoc DL = MI->getDebugLoc();
10806   MachineFunction *F = BB->getParent();
10807
10808   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10809   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10810
10811   if (Subtarget->is64Bit()) {
10812     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10813                                       TII->get(X86::MOV64rm), X86::RDI)
10814     .addReg(X86::RIP)
10815     .addImm(0).addReg(0)
10816     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10817                       MI->getOperand(3).getTargetFlags())
10818     .addReg(0);
10819     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10820     addDirectMem(MIB, X86::RDI);
10821   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10822     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10823                                       TII->get(X86::MOV32rm), X86::EAX)
10824     .addReg(0)
10825     .addImm(0).addReg(0)
10826     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10827                       MI->getOperand(3).getTargetFlags())
10828     .addReg(0);
10829     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10830     addDirectMem(MIB, X86::EAX);
10831   } else {
10832     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10833                                       TII->get(X86::MOV32rm), X86::EAX)
10834     .addReg(TII->getGlobalBaseReg(F))
10835     .addImm(0).addReg(0)
10836     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10837                       MI->getOperand(3).getTargetFlags())
10838     .addReg(0);
10839     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10840     addDirectMem(MIB, X86::EAX);
10841   }
10842
10843   MI->eraseFromParent(); // The pseudo instruction is gone now.
10844   return BB;
10845 }
10846
10847 MachineBasicBlock *
10848 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10849                                                MachineBasicBlock *BB) const {
10850   switch (MI->getOpcode()) {
10851   default: assert(false && "Unexpected instr type to insert");
10852   case X86::TAILJMPd64:
10853   case X86::TAILJMPr64:
10854   case X86::TAILJMPm64:
10855     assert(!"TAILJMP64 would not be touched here.");
10856   case X86::TCRETURNdi64:
10857   case X86::TCRETURNri64:
10858   case X86::TCRETURNmi64:
10859     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10860     // On AMD64, additional defs should be added before register allocation.
10861     if (!Subtarget->isTargetWin64()) {
10862       MI->addRegisterDefined(X86::RSI);
10863       MI->addRegisterDefined(X86::RDI);
10864       MI->addRegisterDefined(X86::XMM6);
10865       MI->addRegisterDefined(X86::XMM7);
10866       MI->addRegisterDefined(X86::XMM8);
10867       MI->addRegisterDefined(X86::XMM9);
10868       MI->addRegisterDefined(X86::XMM10);
10869       MI->addRegisterDefined(X86::XMM11);
10870       MI->addRegisterDefined(X86::XMM12);
10871       MI->addRegisterDefined(X86::XMM13);
10872       MI->addRegisterDefined(X86::XMM14);
10873       MI->addRegisterDefined(X86::XMM15);
10874     }
10875     return BB;
10876   case X86::WIN_ALLOCA:
10877     return EmitLoweredWinAlloca(MI, BB);
10878   case X86::TLSCall_32:
10879   case X86::TLSCall_64:
10880     return EmitLoweredTLSCall(MI, BB);
10881   case X86::CMOV_GR8:
10882   case X86::CMOV_FR32:
10883   case X86::CMOV_FR64:
10884   case X86::CMOV_V4F32:
10885   case X86::CMOV_V2F64:
10886   case X86::CMOV_V2I64:
10887   case X86::CMOV_GR16:
10888   case X86::CMOV_GR32:
10889   case X86::CMOV_RFP32:
10890   case X86::CMOV_RFP64:
10891   case X86::CMOV_RFP80:
10892     return EmitLoweredSelect(MI, BB);
10893
10894   case X86::FP32_TO_INT16_IN_MEM:
10895   case X86::FP32_TO_INT32_IN_MEM:
10896   case X86::FP32_TO_INT64_IN_MEM:
10897   case X86::FP64_TO_INT16_IN_MEM:
10898   case X86::FP64_TO_INT32_IN_MEM:
10899   case X86::FP64_TO_INT64_IN_MEM:
10900   case X86::FP80_TO_INT16_IN_MEM:
10901   case X86::FP80_TO_INT32_IN_MEM:
10902   case X86::FP80_TO_INT64_IN_MEM: {
10903     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10904     DebugLoc DL = MI->getDebugLoc();
10905
10906     // Change the floating point control register to use "round towards zero"
10907     // mode when truncating to an integer value.
10908     MachineFunction *F = BB->getParent();
10909     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10910     addFrameReference(BuildMI(*BB, MI, DL,
10911                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10912
10913     // Load the old value of the high byte of the control word...
10914     unsigned OldCW =
10915       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10916     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10917                       CWFrameIdx);
10918
10919     // Set the high part to be round to zero...
10920     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10921       .addImm(0xC7F);
10922
10923     // Reload the modified control word now...
10924     addFrameReference(BuildMI(*BB, MI, DL,
10925                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10926
10927     // Restore the memory image of control word to original value
10928     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10929       .addReg(OldCW);
10930
10931     // Get the X86 opcode to use.
10932     unsigned Opc;
10933     switch (MI->getOpcode()) {
10934     default: llvm_unreachable("illegal opcode!");
10935     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10936     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10937     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10938     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10939     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10940     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10941     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10942     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10943     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10944     }
10945
10946     X86AddressMode AM;
10947     MachineOperand &Op = MI->getOperand(0);
10948     if (Op.isReg()) {
10949       AM.BaseType = X86AddressMode::RegBase;
10950       AM.Base.Reg = Op.getReg();
10951     } else {
10952       AM.BaseType = X86AddressMode::FrameIndexBase;
10953       AM.Base.FrameIndex = Op.getIndex();
10954     }
10955     Op = MI->getOperand(1);
10956     if (Op.isImm())
10957       AM.Scale = Op.getImm();
10958     Op = MI->getOperand(2);
10959     if (Op.isImm())
10960       AM.IndexReg = Op.getImm();
10961     Op = MI->getOperand(3);
10962     if (Op.isGlobal()) {
10963       AM.GV = Op.getGlobal();
10964     } else {
10965       AM.Disp = Op.getImm();
10966     }
10967     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10968                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10969
10970     // Reload the original control word now.
10971     addFrameReference(BuildMI(*BB, MI, DL,
10972                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10973
10974     MI->eraseFromParent();   // The pseudo instruction is gone now.
10975     return BB;
10976   }
10977     // String/text processing lowering.
10978   case X86::PCMPISTRM128REG:
10979   case X86::VPCMPISTRM128REG:
10980     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10981   case X86::PCMPISTRM128MEM:
10982   case X86::VPCMPISTRM128MEM:
10983     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10984   case X86::PCMPESTRM128REG:
10985   case X86::VPCMPESTRM128REG:
10986     return EmitPCMP(MI, BB, 5, false /* in mem */);
10987   case X86::PCMPESTRM128MEM:
10988   case X86::VPCMPESTRM128MEM:
10989     return EmitPCMP(MI, BB, 5, true /* in mem */);
10990
10991     // Thread synchronization.
10992   case X86::MONITOR:
10993     return EmitMonitor(MI, BB);
10994   case X86::MWAIT:
10995     return EmitMwait(MI, BB);
10996
10997     // Atomic Lowering.
10998   case X86::ATOMAND32:
10999     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11000                                                X86::AND32ri, X86::MOV32rm,
11001                                                X86::LCMPXCHG32,
11002                                                X86::NOT32r, X86::EAX,
11003                                                X86::GR32RegisterClass);
11004   case X86::ATOMOR32:
11005     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
11006                                                X86::OR32ri, X86::MOV32rm,
11007                                                X86::LCMPXCHG32,
11008                                                X86::NOT32r, X86::EAX,
11009                                                X86::GR32RegisterClass);
11010   case X86::ATOMXOR32:
11011     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
11012                                                X86::XOR32ri, X86::MOV32rm,
11013                                                X86::LCMPXCHG32,
11014                                                X86::NOT32r, X86::EAX,
11015                                                X86::GR32RegisterClass);
11016   case X86::ATOMNAND32:
11017     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11018                                                X86::AND32ri, X86::MOV32rm,
11019                                                X86::LCMPXCHG32,
11020                                                X86::NOT32r, X86::EAX,
11021                                                X86::GR32RegisterClass, true);
11022   case X86::ATOMMIN32:
11023     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11024   case X86::ATOMMAX32:
11025     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11026   case X86::ATOMUMIN32:
11027     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11028   case X86::ATOMUMAX32:
11029     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11030
11031   case X86::ATOMAND16:
11032     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11033                                                X86::AND16ri, X86::MOV16rm,
11034                                                X86::LCMPXCHG16,
11035                                                X86::NOT16r, X86::AX,
11036                                                X86::GR16RegisterClass);
11037   case X86::ATOMOR16:
11038     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11039                                                X86::OR16ri, X86::MOV16rm,
11040                                                X86::LCMPXCHG16,
11041                                                X86::NOT16r, X86::AX,
11042                                                X86::GR16RegisterClass);
11043   case X86::ATOMXOR16:
11044     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11045                                                X86::XOR16ri, X86::MOV16rm,
11046                                                X86::LCMPXCHG16,
11047                                                X86::NOT16r, X86::AX,
11048                                                X86::GR16RegisterClass);
11049   case X86::ATOMNAND16:
11050     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11051                                                X86::AND16ri, X86::MOV16rm,
11052                                                X86::LCMPXCHG16,
11053                                                X86::NOT16r, X86::AX,
11054                                                X86::GR16RegisterClass, true);
11055   case X86::ATOMMIN16:
11056     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11057   case X86::ATOMMAX16:
11058     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11059   case X86::ATOMUMIN16:
11060     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11061   case X86::ATOMUMAX16:
11062     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11063
11064   case X86::ATOMAND8:
11065     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11066                                                X86::AND8ri, X86::MOV8rm,
11067                                                X86::LCMPXCHG8,
11068                                                X86::NOT8r, X86::AL,
11069                                                X86::GR8RegisterClass);
11070   case X86::ATOMOR8:
11071     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11072                                                X86::OR8ri, X86::MOV8rm,
11073                                                X86::LCMPXCHG8,
11074                                                X86::NOT8r, X86::AL,
11075                                                X86::GR8RegisterClass);
11076   case X86::ATOMXOR8:
11077     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11078                                                X86::XOR8ri, X86::MOV8rm,
11079                                                X86::LCMPXCHG8,
11080                                                X86::NOT8r, X86::AL,
11081                                                X86::GR8RegisterClass);
11082   case X86::ATOMNAND8:
11083     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11084                                                X86::AND8ri, X86::MOV8rm,
11085                                                X86::LCMPXCHG8,
11086                                                X86::NOT8r, X86::AL,
11087                                                X86::GR8RegisterClass, true);
11088   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11089   // This group is for 64-bit host.
11090   case X86::ATOMAND64:
11091     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11092                                                X86::AND64ri32, X86::MOV64rm,
11093                                                X86::LCMPXCHG64,
11094                                                X86::NOT64r, X86::RAX,
11095                                                X86::GR64RegisterClass);
11096   case X86::ATOMOR64:
11097     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11098                                                X86::OR64ri32, X86::MOV64rm,
11099                                                X86::LCMPXCHG64,
11100                                                X86::NOT64r, X86::RAX,
11101                                                X86::GR64RegisterClass);
11102   case X86::ATOMXOR64:
11103     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11104                                                X86::XOR64ri32, X86::MOV64rm,
11105                                                X86::LCMPXCHG64,
11106                                                X86::NOT64r, X86::RAX,
11107                                                X86::GR64RegisterClass);
11108   case X86::ATOMNAND64:
11109     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11110                                                X86::AND64ri32, X86::MOV64rm,
11111                                                X86::LCMPXCHG64,
11112                                                X86::NOT64r, X86::RAX,
11113                                                X86::GR64RegisterClass, true);
11114   case X86::ATOMMIN64:
11115     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11116   case X86::ATOMMAX64:
11117     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11118   case X86::ATOMUMIN64:
11119     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11120   case X86::ATOMUMAX64:
11121     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11122
11123   // This group does 64-bit operations on a 32-bit host.
11124   case X86::ATOMAND6432:
11125     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11126                                                X86::AND32rr, X86::AND32rr,
11127                                                X86::AND32ri, X86::AND32ri,
11128                                                false);
11129   case X86::ATOMOR6432:
11130     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11131                                                X86::OR32rr, X86::OR32rr,
11132                                                X86::OR32ri, X86::OR32ri,
11133                                                false);
11134   case X86::ATOMXOR6432:
11135     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11136                                                X86::XOR32rr, X86::XOR32rr,
11137                                                X86::XOR32ri, X86::XOR32ri,
11138                                                false);
11139   case X86::ATOMNAND6432:
11140     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11141                                                X86::AND32rr, X86::AND32rr,
11142                                                X86::AND32ri, X86::AND32ri,
11143                                                true);
11144   case X86::ATOMADD6432:
11145     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11146                                                X86::ADD32rr, X86::ADC32rr,
11147                                                X86::ADD32ri, X86::ADC32ri,
11148                                                false);
11149   case X86::ATOMSUB6432:
11150     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11151                                                X86::SUB32rr, X86::SBB32rr,
11152                                                X86::SUB32ri, X86::SBB32ri,
11153                                                false);
11154   case X86::ATOMSWAP6432:
11155     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11156                                                X86::MOV32rr, X86::MOV32rr,
11157                                                X86::MOV32ri, X86::MOV32ri,
11158                                                false);
11159   case X86::VASTART_SAVE_XMM_REGS:
11160     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11161
11162   case X86::VAARG_64:
11163     return EmitVAARG64WithCustomInserter(MI, BB);
11164   }
11165 }
11166
11167 //===----------------------------------------------------------------------===//
11168 //                           X86 Optimization Hooks
11169 //===----------------------------------------------------------------------===//
11170
11171 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11172                                                        const APInt &Mask,
11173                                                        APInt &KnownZero,
11174                                                        APInt &KnownOne,
11175                                                        const SelectionDAG &DAG,
11176                                                        unsigned Depth) const {
11177   unsigned Opc = Op.getOpcode();
11178   assert((Opc >= ISD::BUILTIN_OP_END ||
11179           Opc == ISD::INTRINSIC_WO_CHAIN ||
11180           Opc == ISD::INTRINSIC_W_CHAIN ||
11181           Opc == ISD::INTRINSIC_VOID) &&
11182          "Should use MaskedValueIsZero if you don't know whether Op"
11183          " is a target node!");
11184
11185   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11186   switch (Opc) {
11187   default: break;
11188   case X86ISD::ADD:
11189   case X86ISD::SUB:
11190   case X86ISD::ADC:
11191   case X86ISD::SBB:
11192   case X86ISD::SMUL:
11193   case X86ISD::UMUL:
11194   case X86ISD::INC:
11195   case X86ISD::DEC:
11196   case X86ISD::OR:
11197   case X86ISD::XOR:
11198   case X86ISD::AND:
11199     // These nodes' second result is a boolean.
11200     if (Op.getResNo() == 0)
11201       break;
11202     // Fallthrough
11203   case X86ISD::SETCC:
11204     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11205                                        Mask.getBitWidth() - 1);
11206     break;
11207   }
11208 }
11209
11210 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11211                                                          unsigned Depth) const {
11212   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11213   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11214     return Op.getValueType().getScalarType().getSizeInBits();
11215
11216   // Fallback case.
11217   return 1;
11218 }
11219
11220 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11221 /// node is a GlobalAddress + offset.
11222 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11223                                        const GlobalValue* &GA,
11224                                        int64_t &Offset) const {
11225   if (N->getOpcode() == X86ISD::Wrapper) {
11226     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11227       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11228       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11229       return true;
11230     }
11231   }
11232   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11233 }
11234
11235 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11236 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11237 /// if the load addresses are consecutive, non-overlapping, and in the right
11238 /// order.
11239 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11240                                      TargetLowering::DAGCombinerInfo &DCI) {
11241   DebugLoc dl = N->getDebugLoc();
11242   EVT VT = N->getValueType(0);
11243
11244   if (VT.getSizeInBits() != 128)
11245     return SDValue();
11246
11247   // Don't create instructions with illegal types after legalize types has run.
11248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11249   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11250     return SDValue();
11251
11252   SmallVector<SDValue, 16> Elts;
11253   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11254     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11255
11256   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11257 }
11258
11259 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11260 /// generation and convert it from being a bunch of shuffles and extracts
11261 /// to a simple store and scalar loads to extract the elements.
11262 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11263                                                 const TargetLowering &TLI) {
11264   SDValue InputVector = N->getOperand(0);
11265
11266   // Only operate on vectors of 4 elements, where the alternative shuffling
11267   // gets to be more expensive.
11268   if (InputVector.getValueType() != MVT::v4i32)
11269     return SDValue();
11270
11271   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11272   // single use which is a sign-extend or zero-extend, and all elements are
11273   // used.
11274   SmallVector<SDNode *, 4> Uses;
11275   unsigned ExtractedElements = 0;
11276   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11277        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11278     if (UI.getUse().getResNo() != InputVector.getResNo())
11279       return SDValue();
11280
11281     SDNode *Extract = *UI;
11282     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11283       return SDValue();
11284
11285     if (Extract->getValueType(0) != MVT::i32)
11286       return SDValue();
11287     if (!Extract->hasOneUse())
11288       return SDValue();
11289     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11290         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11291       return SDValue();
11292     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11293       return SDValue();
11294
11295     // Record which element was extracted.
11296     ExtractedElements |=
11297       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11298
11299     Uses.push_back(Extract);
11300   }
11301
11302   // If not all the elements were used, this may not be worthwhile.
11303   if (ExtractedElements != 15)
11304     return SDValue();
11305
11306   // Ok, we've now decided to do the transformation.
11307   DebugLoc dl = InputVector.getDebugLoc();
11308
11309   // Store the value to a temporary stack slot.
11310   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11311   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11312                             MachinePointerInfo(), false, false, 0);
11313
11314   // Replace each use (extract) with a load of the appropriate element.
11315   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11316        UE = Uses.end(); UI != UE; ++UI) {
11317     SDNode *Extract = *UI;
11318
11319     // cOMpute the element's address.
11320     SDValue Idx = Extract->getOperand(1);
11321     unsigned EltSize =
11322         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11323     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11324     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11325
11326     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11327                                      StackPtr, OffsetVal);
11328
11329     // Load the scalar.
11330     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11331                                      ScalarAddr, MachinePointerInfo(),
11332                                      false, false, 0);
11333
11334     // Replace the exact with the load.
11335     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11336   }
11337
11338   // The replacement was made in place; don't return anything.
11339   return SDValue();
11340 }
11341
11342 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11343 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11344                                     const X86Subtarget *Subtarget) {
11345   DebugLoc DL = N->getDebugLoc();
11346   SDValue Cond = N->getOperand(0);
11347   // Get the LHS/RHS of the select.
11348   SDValue LHS = N->getOperand(1);
11349   SDValue RHS = N->getOperand(2);
11350
11351   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11352   // instructions match the semantics of the common C idiom x<y?x:y but not
11353   // x<=y?x:y, because of how they handle negative zero (which can be
11354   // ignored in unsafe-math mode).
11355   if (Subtarget->hasSSE2() &&
11356       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11357       Cond.getOpcode() == ISD::SETCC) {
11358     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11359
11360     unsigned Opcode = 0;
11361     // Check for x CC y ? x : y.
11362     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11363         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11364       switch (CC) {
11365       default: break;
11366       case ISD::SETULT:
11367         // Converting this to a min would handle NaNs incorrectly, and swapping
11368         // the operands would cause it to handle comparisons between positive
11369         // and negative zero incorrectly.
11370         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11371           if (!UnsafeFPMath &&
11372               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11373             break;
11374           std::swap(LHS, RHS);
11375         }
11376         Opcode = X86ISD::FMIN;
11377         break;
11378       case ISD::SETOLE:
11379         // Converting this to a min would handle comparisons between positive
11380         // and negative zero incorrectly.
11381         if (!UnsafeFPMath &&
11382             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11383           break;
11384         Opcode = X86ISD::FMIN;
11385         break;
11386       case ISD::SETULE:
11387         // Converting this to a min would handle both negative zeros and NaNs
11388         // incorrectly, but we can swap the operands to fix both.
11389         std::swap(LHS, RHS);
11390       case ISD::SETOLT:
11391       case ISD::SETLT:
11392       case ISD::SETLE:
11393         Opcode = X86ISD::FMIN;
11394         break;
11395
11396       case ISD::SETOGE:
11397         // Converting this to a max would handle comparisons between positive
11398         // and negative zero incorrectly.
11399         if (!UnsafeFPMath &&
11400             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11401           break;
11402         Opcode = X86ISD::FMAX;
11403         break;
11404       case ISD::SETUGT:
11405         // Converting this to a max would handle NaNs incorrectly, and swapping
11406         // the operands would cause it to handle comparisons between positive
11407         // and negative zero incorrectly.
11408         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11409           if (!UnsafeFPMath &&
11410               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11411             break;
11412           std::swap(LHS, RHS);
11413         }
11414         Opcode = X86ISD::FMAX;
11415         break;
11416       case ISD::SETUGE:
11417         // Converting this to a max would handle both negative zeros and NaNs
11418         // incorrectly, but we can swap the operands to fix both.
11419         std::swap(LHS, RHS);
11420       case ISD::SETOGT:
11421       case ISD::SETGT:
11422       case ISD::SETGE:
11423         Opcode = X86ISD::FMAX;
11424         break;
11425       }
11426     // Check for x CC y ? y : x -- a min/max with reversed arms.
11427     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11428                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11429       switch (CC) {
11430       default: break;
11431       case ISD::SETOGE:
11432         // Converting this to a min would handle comparisons between positive
11433         // and negative zero incorrectly, and swapping the operands would
11434         // cause it to handle NaNs incorrectly.
11435         if (!UnsafeFPMath &&
11436             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11437           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11438             break;
11439           std::swap(LHS, RHS);
11440         }
11441         Opcode = X86ISD::FMIN;
11442         break;
11443       case ISD::SETUGT:
11444         // Converting this to a min would handle NaNs incorrectly.
11445         if (!UnsafeFPMath &&
11446             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11447           break;
11448         Opcode = X86ISD::FMIN;
11449         break;
11450       case ISD::SETUGE:
11451         // Converting this to a min would handle both negative zeros and NaNs
11452         // incorrectly, but we can swap the operands to fix both.
11453         std::swap(LHS, RHS);
11454       case ISD::SETOGT:
11455       case ISD::SETGT:
11456       case ISD::SETGE:
11457         Opcode = X86ISD::FMIN;
11458         break;
11459
11460       case ISD::SETULT:
11461         // Converting this to a max would handle NaNs incorrectly.
11462         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11463           break;
11464         Opcode = X86ISD::FMAX;
11465         break;
11466       case ISD::SETOLE:
11467         // Converting this to a max would handle comparisons between positive
11468         // and negative zero incorrectly, and swapping the operands would
11469         // cause it to handle NaNs incorrectly.
11470         if (!UnsafeFPMath &&
11471             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11472           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11473             break;
11474           std::swap(LHS, RHS);
11475         }
11476         Opcode = X86ISD::FMAX;
11477         break;
11478       case ISD::SETULE:
11479         // Converting this to a max would handle both negative zeros and NaNs
11480         // incorrectly, but we can swap the operands to fix both.
11481         std::swap(LHS, RHS);
11482       case ISD::SETOLT:
11483       case ISD::SETLT:
11484       case ISD::SETLE:
11485         Opcode = X86ISD::FMAX;
11486         break;
11487       }
11488     }
11489
11490     if (Opcode)
11491       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11492   }
11493
11494   // If this is a select between two integer constants, try to do some
11495   // optimizations.
11496   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11497     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11498       // Don't do this for crazy integer types.
11499       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11500         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11501         // so that TrueC (the true value) is larger than FalseC.
11502         bool NeedsCondInvert = false;
11503
11504         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11505             // Efficiently invertible.
11506             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11507              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11508               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11509           NeedsCondInvert = true;
11510           std::swap(TrueC, FalseC);
11511         }
11512
11513         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11514         if (FalseC->getAPIntValue() == 0 &&
11515             TrueC->getAPIntValue().isPowerOf2()) {
11516           if (NeedsCondInvert) // Invert the condition if needed.
11517             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11518                                DAG.getConstant(1, Cond.getValueType()));
11519
11520           // Zero extend the condition if needed.
11521           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11522
11523           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11524           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11525                              DAG.getConstant(ShAmt, MVT::i8));
11526         }
11527
11528         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11529         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11530           if (NeedsCondInvert) // Invert the condition if needed.
11531             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11532                                DAG.getConstant(1, Cond.getValueType()));
11533
11534           // Zero extend the condition if needed.
11535           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11536                              FalseC->getValueType(0), Cond);
11537           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11538                              SDValue(FalseC, 0));
11539         }
11540
11541         // Optimize cases that will turn into an LEA instruction.  This requires
11542         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11543         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11544           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11545           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11546
11547           bool isFastMultiplier = false;
11548           if (Diff < 10) {
11549             switch ((unsigned char)Diff) {
11550               default: break;
11551               case 1:  // result = add base, cond
11552               case 2:  // result = lea base(    , cond*2)
11553               case 3:  // result = lea base(cond, cond*2)
11554               case 4:  // result = lea base(    , cond*4)
11555               case 5:  // result = lea base(cond, cond*4)
11556               case 8:  // result = lea base(    , cond*8)
11557               case 9:  // result = lea base(cond, cond*8)
11558                 isFastMultiplier = true;
11559                 break;
11560             }
11561           }
11562
11563           if (isFastMultiplier) {
11564             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11565             if (NeedsCondInvert) // Invert the condition if needed.
11566               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11567                                  DAG.getConstant(1, Cond.getValueType()));
11568
11569             // Zero extend the condition if needed.
11570             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11571                                Cond);
11572             // Scale the condition by the difference.
11573             if (Diff != 1)
11574               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11575                                  DAG.getConstant(Diff, Cond.getValueType()));
11576
11577             // Add the base if non-zero.
11578             if (FalseC->getAPIntValue() != 0)
11579               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11580                                  SDValue(FalseC, 0));
11581             return Cond;
11582           }
11583         }
11584       }
11585   }
11586
11587   return SDValue();
11588 }
11589
11590 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11591 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11592                                   TargetLowering::DAGCombinerInfo &DCI) {
11593   DebugLoc DL = N->getDebugLoc();
11594
11595   // If the flag operand isn't dead, don't touch this CMOV.
11596   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11597     return SDValue();
11598
11599   SDValue FalseOp = N->getOperand(0);
11600   SDValue TrueOp = N->getOperand(1);
11601   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11602   SDValue Cond = N->getOperand(3);
11603   if (CC == X86::COND_E || CC == X86::COND_NE) {
11604     switch (Cond.getOpcode()) {
11605     default: break;
11606     case X86ISD::BSR:
11607     case X86ISD::BSF:
11608       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11609       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11610         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11611     }
11612   }
11613
11614   // If this is a select between two integer constants, try to do some
11615   // optimizations.  Note that the operands are ordered the opposite of SELECT
11616   // operands.
11617   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11618     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11619       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11620       // larger than FalseC (the false value).
11621       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11622         CC = X86::GetOppositeBranchCondition(CC);
11623         std::swap(TrueC, FalseC);
11624       }
11625
11626       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11627       // This is efficient for any integer data type (including i8/i16) and
11628       // shift amount.
11629       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11630         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11631                            DAG.getConstant(CC, MVT::i8), Cond);
11632
11633         // Zero extend the condition if needed.
11634         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11635
11636         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11637         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11638                            DAG.getConstant(ShAmt, MVT::i8));
11639         if (N->getNumValues() == 2)  // Dead flag value?
11640           return DCI.CombineTo(N, Cond, SDValue());
11641         return Cond;
11642       }
11643
11644       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11645       // for any integer data type, including i8/i16.
11646       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11647         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11648                            DAG.getConstant(CC, MVT::i8), Cond);
11649
11650         // Zero extend the condition if needed.
11651         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11652                            FalseC->getValueType(0), Cond);
11653         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11654                            SDValue(FalseC, 0));
11655
11656         if (N->getNumValues() == 2)  // Dead flag value?
11657           return DCI.CombineTo(N, Cond, SDValue());
11658         return Cond;
11659       }
11660
11661       // Optimize cases that will turn into an LEA instruction.  This requires
11662       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11663       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11664         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11665         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11666
11667         bool isFastMultiplier = false;
11668         if (Diff < 10) {
11669           switch ((unsigned char)Diff) {
11670           default: break;
11671           case 1:  // result = add base, cond
11672           case 2:  // result = lea base(    , cond*2)
11673           case 3:  // result = lea base(cond, cond*2)
11674           case 4:  // result = lea base(    , cond*4)
11675           case 5:  // result = lea base(cond, cond*4)
11676           case 8:  // result = lea base(    , cond*8)
11677           case 9:  // result = lea base(cond, cond*8)
11678             isFastMultiplier = true;
11679             break;
11680           }
11681         }
11682
11683         if (isFastMultiplier) {
11684           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11685           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11686                              DAG.getConstant(CC, MVT::i8), Cond);
11687           // Zero extend the condition if needed.
11688           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11689                              Cond);
11690           // Scale the condition by the difference.
11691           if (Diff != 1)
11692             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11693                                DAG.getConstant(Diff, Cond.getValueType()));
11694
11695           // Add the base if non-zero.
11696           if (FalseC->getAPIntValue() != 0)
11697             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11698                                SDValue(FalseC, 0));
11699           if (N->getNumValues() == 2)  // Dead flag value?
11700             return DCI.CombineTo(N, Cond, SDValue());
11701           return Cond;
11702         }
11703       }
11704     }
11705   }
11706   return SDValue();
11707 }
11708
11709
11710 /// PerformMulCombine - Optimize a single multiply with constant into two
11711 /// in order to implement it with two cheaper instructions, e.g.
11712 /// LEA + SHL, LEA + LEA.
11713 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11714                                  TargetLowering::DAGCombinerInfo &DCI) {
11715   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11716     return SDValue();
11717
11718   EVT VT = N->getValueType(0);
11719   if (VT != MVT::i64)
11720     return SDValue();
11721
11722   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11723   if (!C)
11724     return SDValue();
11725   uint64_t MulAmt = C->getZExtValue();
11726   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11727     return SDValue();
11728
11729   uint64_t MulAmt1 = 0;
11730   uint64_t MulAmt2 = 0;
11731   if ((MulAmt % 9) == 0) {
11732     MulAmt1 = 9;
11733     MulAmt2 = MulAmt / 9;
11734   } else if ((MulAmt % 5) == 0) {
11735     MulAmt1 = 5;
11736     MulAmt2 = MulAmt / 5;
11737   } else if ((MulAmt % 3) == 0) {
11738     MulAmt1 = 3;
11739     MulAmt2 = MulAmt / 3;
11740   }
11741   if (MulAmt2 &&
11742       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11743     DebugLoc DL = N->getDebugLoc();
11744
11745     if (isPowerOf2_64(MulAmt2) &&
11746         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11747       // If second multiplifer is pow2, issue it first. We want the multiply by
11748       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11749       // is an add.
11750       std::swap(MulAmt1, MulAmt2);
11751
11752     SDValue NewMul;
11753     if (isPowerOf2_64(MulAmt1))
11754       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11755                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11756     else
11757       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11758                            DAG.getConstant(MulAmt1, VT));
11759
11760     if (isPowerOf2_64(MulAmt2))
11761       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11762                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11763     else
11764       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11765                            DAG.getConstant(MulAmt2, VT));
11766
11767     // Do not add new nodes to DAG combiner worklist.
11768     DCI.CombineTo(N, NewMul, false);
11769   }
11770   return SDValue();
11771 }
11772
11773 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11774   SDValue N0 = N->getOperand(0);
11775   SDValue N1 = N->getOperand(1);
11776   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11777   EVT VT = N0.getValueType();
11778
11779   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11780   // since the result of setcc_c is all zero's or all ones.
11781   if (N1C && N0.getOpcode() == ISD::AND &&
11782       N0.getOperand(1).getOpcode() == ISD::Constant) {
11783     SDValue N00 = N0.getOperand(0);
11784     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11785         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11786           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11787          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11788       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11789       APInt ShAmt = N1C->getAPIntValue();
11790       Mask = Mask.shl(ShAmt);
11791       if (Mask != 0)
11792         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11793                            N00, DAG.getConstant(Mask, VT));
11794     }
11795   }
11796
11797   return SDValue();
11798 }
11799
11800 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11801 ///                       when possible.
11802 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11803                                    const X86Subtarget *Subtarget) {
11804   EVT VT = N->getValueType(0);
11805   if (!VT.isVector() && VT.isInteger() &&
11806       N->getOpcode() == ISD::SHL)
11807     return PerformSHLCombine(N, DAG);
11808
11809   // On X86 with SSE2 support, we can transform this to a vector shift if
11810   // all elements are shifted by the same amount.  We can't do this in legalize
11811   // because the a constant vector is typically transformed to a constant pool
11812   // so we have no knowledge of the shift amount.
11813   if (!Subtarget->hasSSE2())
11814     return SDValue();
11815
11816   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11817     return SDValue();
11818
11819   SDValue ShAmtOp = N->getOperand(1);
11820   EVT EltVT = VT.getVectorElementType();
11821   DebugLoc DL = N->getDebugLoc();
11822   SDValue BaseShAmt = SDValue();
11823   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11824     unsigned NumElts = VT.getVectorNumElements();
11825     unsigned i = 0;
11826     for (; i != NumElts; ++i) {
11827       SDValue Arg = ShAmtOp.getOperand(i);
11828       if (Arg.getOpcode() == ISD::UNDEF) continue;
11829       BaseShAmt = Arg;
11830       break;
11831     }
11832     for (; i != NumElts; ++i) {
11833       SDValue Arg = ShAmtOp.getOperand(i);
11834       if (Arg.getOpcode() == ISD::UNDEF) continue;
11835       if (Arg != BaseShAmt) {
11836         return SDValue();
11837       }
11838     }
11839   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11840              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11841     SDValue InVec = ShAmtOp.getOperand(0);
11842     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11843       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11844       unsigned i = 0;
11845       for (; i != NumElts; ++i) {
11846         SDValue Arg = InVec.getOperand(i);
11847         if (Arg.getOpcode() == ISD::UNDEF) continue;
11848         BaseShAmt = Arg;
11849         break;
11850       }
11851     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11852        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11853          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11854          if (C->getZExtValue() == SplatIdx)
11855            BaseShAmt = InVec.getOperand(1);
11856        }
11857     }
11858     if (BaseShAmt.getNode() == 0)
11859       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11860                               DAG.getIntPtrConstant(0));
11861   } else
11862     return SDValue();
11863
11864   // The shift amount is an i32.
11865   if (EltVT.bitsGT(MVT::i32))
11866     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11867   else if (EltVT.bitsLT(MVT::i32))
11868     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11869
11870   // The shift amount is identical so we can do a vector shift.
11871   SDValue  ValOp = N->getOperand(0);
11872   switch (N->getOpcode()) {
11873   default:
11874     llvm_unreachable("Unknown shift opcode!");
11875     break;
11876   case ISD::SHL:
11877     if (VT == MVT::v2i64)
11878       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11879                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11880                          ValOp, BaseShAmt);
11881     if (VT == MVT::v4i32)
11882       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11883                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11884                          ValOp, BaseShAmt);
11885     if (VT == MVT::v8i16)
11886       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11887                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11888                          ValOp, BaseShAmt);
11889     break;
11890   case ISD::SRA:
11891     if (VT == MVT::v4i32)
11892       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11893                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11894                          ValOp, BaseShAmt);
11895     if (VT == MVT::v8i16)
11896       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11897                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11898                          ValOp, BaseShAmt);
11899     break;
11900   case ISD::SRL:
11901     if (VT == MVT::v2i64)
11902       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11903                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11904                          ValOp, BaseShAmt);
11905     if (VT == MVT::v4i32)
11906       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11907                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11908                          ValOp, BaseShAmt);
11909     if (VT ==  MVT::v8i16)
11910       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11911                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11912                          ValOp, BaseShAmt);
11913     break;
11914   }
11915   return SDValue();
11916 }
11917
11918
11919 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11920 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11921 // and friends.  Likewise for OR -> CMPNEQSS.
11922 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11923                             TargetLowering::DAGCombinerInfo &DCI,
11924                             const X86Subtarget *Subtarget) {
11925   unsigned opcode;
11926
11927   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11928   // we're requiring SSE2 for both.
11929   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11930     SDValue N0 = N->getOperand(0);
11931     SDValue N1 = N->getOperand(1);
11932     SDValue CMP0 = N0->getOperand(1);
11933     SDValue CMP1 = N1->getOperand(1);
11934     DebugLoc DL = N->getDebugLoc();
11935
11936     // The SETCCs should both refer to the same CMP.
11937     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11938       return SDValue();
11939
11940     SDValue CMP00 = CMP0->getOperand(0);
11941     SDValue CMP01 = CMP0->getOperand(1);
11942     EVT     VT    = CMP00.getValueType();
11943
11944     if (VT == MVT::f32 || VT == MVT::f64) {
11945       bool ExpectingFlags = false;
11946       // Check for any users that want flags:
11947       for (SDNode::use_iterator UI = N->use_begin(),
11948              UE = N->use_end();
11949            !ExpectingFlags && UI != UE; ++UI)
11950         switch (UI->getOpcode()) {
11951         default:
11952         case ISD::BR_CC:
11953         case ISD::BRCOND:
11954         case ISD::SELECT:
11955           ExpectingFlags = true;
11956           break;
11957         case ISD::CopyToReg:
11958         case ISD::SIGN_EXTEND:
11959         case ISD::ZERO_EXTEND:
11960         case ISD::ANY_EXTEND:
11961           break;
11962         }
11963
11964       if (!ExpectingFlags) {
11965         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11966         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11967
11968         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11969           X86::CondCode tmp = cc0;
11970           cc0 = cc1;
11971           cc1 = tmp;
11972         }
11973
11974         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11975             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11976           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11977           X86ISD::NodeType NTOperator = is64BitFP ?
11978             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11979           // FIXME: need symbolic constants for these magic numbers.
11980           // See X86ATTInstPrinter.cpp:printSSECC().
11981           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11982           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11983                                               DAG.getConstant(x86cc, MVT::i8));
11984           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11985                                               OnesOrZeroesF);
11986           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11987                                       DAG.getConstant(1, MVT::i32));
11988           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11989           return OneBitOfTruth;
11990         }
11991       }
11992     }
11993   }
11994   return SDValue();
11995 }
11996
11997 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11998                                  TargetLowering::DAGCombinerInfo &DCI,
11999                                  const X86Subtarget *Subtarget) {
12000   if (DCI.isBeforeLegalizeOps())
12001     return SDValue();
12002
12003   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12004   if (R.getNode())
12005     return R;
12006
12007   // Want to form ANDNP nodes:
12008   // 1) In the hopes of then easily combining them with OR and AND nodes
12009   //    to form PBLEND/PSIGN.
12010   // 2) To match ANDN packed intrinsics
12011   EVT VT = N->getValueType(0);
12012   if (VT != MVT::v2i64 && VT != MVT::v4i64)
12013     return SDValue();
12014
12015   SDValue N0 = N->getOperand(0);
12016   SDValue N1 = N->getOperand(1);
12017   DebugLoc DL = N->getDebugLoc();
12018
12019   // Check LHS for vnot
12020   if (N0.getOpcode() == ISD::XOR &&
12021       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12022     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12023
12024   // Check RHS for vnot
12025   if (N1.getOpcode() == ISD::XOR &&
12026       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12027     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12028
12029   return SDValue();
12030 }
12031
12032 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12033                                 TargetLowering::DAGCombinerInfo &DCI,
12034                                 const X86Subtarget *Subtarget) {
12035   if (DCI.isBeforeLegalizeOps())
12036     return SDValue();
12037
12038   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12039   if (R.getNode())
12040     return R;
12041
12042   EVT VT = N->getValueType(0);
12043   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12044     return SDValue();
12045
12046   SDValue N0 = N->getOperand(0);
12047   SDValue N1 = N->getOperand(1);
12048
12049   // look for psign/blend
12050   if (Subtarget->hasSSSE3()) {
12051     if (VT == MVT::v2i64) {
12052       // Canonicalize pandn to RHS
12053       if (N0.getOpcode() == X86ISD::ANDNP)
12054         std::swap(N0, N1);
12055       // or (and (m, x), (pandn m, y))
12056       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12057         SDValue Mask = N1.getOperand(0);
12058         SDValue X    = N1.getOperand(1);
12059         SDValue Y;
12060         if (N0.getOperand(0) == Mask)
12061           Y = N0.getOperand(1);
12062         if (N0.getOperand(1) == Mask)
12063           Y = N0.getOperand(0);
12064
12065         // Check to see if the mask appeared in both the AND and ANDNP and
12066         if (!Y.getNode())
12067           return SDValue();
12068
12069         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12070         if (Mask.getOpcode() != ISD::BITCAST ||
12071             X.getOpcode() != ISD::BITCAST ||
12072             Y.getOpcode() != ISD::BITCAST)
12073           return SDValue();
12074
12075         // Look through mask bitcast.
12076         Mask = Mask.getOperand(0);
12077         EVT MaskVT = Mask.getValueType();
12078
12079         // Validate that the Mask operand is a vector sra node.  The sra node
12080         // will be an intrinsic.
12081         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12082           return SDValue();
12083
12084         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12085         // there is no psrai.b
12086         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12087         case Intrinsic::x86_sse2_psrai_w:
12088         case Intrinsic::x86_sse2_psrai_d:
12089           break;
12090         default: return SDValue();
12091         }
12092
12093         // Check that the SRA is all signbits.
12094         SDValue SraC = Mask.getOperand(2);
12095         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
12096         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12097         if ((SraAmt + 1) != EltBits)
12098           return SDValue();
12099
12100         DebugLoc DL = N->getDebugLoc();
12101
12102         // Now we know we at least have a plendvb with the mask val.  See if
12103         // we can form a psignb/w/d.
12104         // psign = x.type == y.type == mask.type && y = sub(0, x);
12105         X = X.getOperand(0);
12106         Y = Y.getOperand(0);
12107         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12108             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12109             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12110           unsigned Opc = 0;
12111           switch (EltBits) {
12112           case 8: Opc = X86ISD::PSIGNB; break;
12113           case 16: Opc = X86ISD::PSIGNW; break;
12114           case 32: Opc = X86ISD::PSIGND; break;
12115           default: break;
12116           }
12117           if (Opc) {
12118             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12119             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12120           }
12121         }
12122         // PBLENDVB only available on SSE 4.1
12123         if (!Subtarget->hasSSE41())
12124           return SDValue();
12125
12126         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12127         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12128         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12129         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12130         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12131       }
12132     }
12133   }
12134
12135   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12136   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12137     std::swap(N0, N1);
12138   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12139     return SDValue();
12140   if (!N0.hasOneUse() || !N1.hasOneUse())
12141     return SDValue();
12142
12143   SDValue ShAmt0 = N0.getOperand(1);
12144   if (ShAmt0.getValueType() != MVT::i8)
12145     return SDValue();
12146   SDValue ShAmt1 = N1.getOperand(1);
12147   if (ShAmt1.getValueType() != MVT::i8)
12148     return SDValue();
12149   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12150     ShAmt0 = ShAmt0.getOperand(0);
12151   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12152     ShAmt1 = ShAmt1.getOperand(0);
12153
12154   DebugLoc DL = N->getDebugLoc();
12155   unsigned Opc = X86ISD::SHLD;
12156   SDValue Op0 = N0.getOperand(0);
12157   SDValue Op1 = N1.getOperand(0);
12158   if (ShAmt0.getOpcode() == ISD::SUB) {
12159     Opc = X86ISD::SHRD;
12160     std::swap(Op0, Op1);
12161     std::swap(ShAmt0, ShAmt1);
12162   }
12163
12164   unsigned Bits = VT.getSizeInBits();
12165   if (ShAmt1.getOpcode() == ISD::SUB) {
12166     SDValue Sum = ShAmt1.getOperand(0);
12167     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12168       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12169       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12170         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12171       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12172         return DAG.getNode(Opc, DL, VT,
12173                            Op0, Op1,
12174                            DAG.getNode(ISD::TRUNCATE, DL,
12175                                        MVT::i8, ShAmt0));
12176     }
12177   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12178     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12179     if (ShAmt0C &&
12180         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12181       return DAG.getNode(Opc, DL, VT,
12182                          N0.getOperand(0), N1.getOperand(0),
12183                          DAG.getNode(ISD::TRUNCATE, DL,
12184                                        MVT::i8, ShAmt0));
12185   }
12186
12187   return SDValue();
12188 }
12189
12190 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12191 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12192                                    const X86Subtarget *Subtarget) {
12193   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12194   // the FP state in cases where an emms may be missing.
12195   // A preferable solution to the general problem is to figure out the right
12196   // places to insert EMMS.  This qualifies as a quick hack.
12197
12198   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12199   StoreSDNode *St = cast<StoreSDNode>(N);
12200   EVT VT = St->getValue().getValueType();
12201   if (VT.getSizeInBits() != 64)
12202     return SDValue();
12203
12204   const Function *F = DAG.getMachineFunction().getFunction();
12205   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12206   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12207     && Subtarget->hasSSE2();
12208   if ((VT.isVector() ||
12209        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12210       isa<LoadSDNode>(St->getValue()) &&
12211       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12212       St->getChain().hasOneUse() && !St->isVolatile()) {
12213     SDNode* LdVal = St->getValue().getNode();
12214     LoadSDNode *Ld = 0;
12215     int TokenFactorIndex = -1;
12216     SmallVector<SDValue, 8> Ops;
12217     SDNode* ChainVal = St->getChain().getNode();
12218     // Must be a store of a load.  We currently handle two cases:  the load
12219     // is a direct child, and it's under an intervening TokenFactor.  It is
12220     // possible to dig deeper under nested TokenFactors.
12221     if (ChainVal == LdVal)
12222       Ld = cast<LoadSDNode>(St->getChain());
12223     else if (St->getValue().hasOneUse() &&
12224              ChainVal->getOpcode() == ISD::TokenFactor) {
12225       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12226         if (ChainVal->getOperand(i).getNode() == LdVal) {
12227           TokenFactorIndex = i;
12228           Ld = cast<LoadSDNode>(St->getValue());
12229         } else
12230           Ops.push_back(ChainVal->getOperand(i));
12231       }
12232     }
12233
12234     if (!Ld || !ISD::isNormalLoad(Ld))
12235       return SDValue();
12236
12237     // If this is not the MMX case, i.e. we are just turning i64 load/store
12238     // into f64 load/store, avoid the transformation if there are multiple
12239     // uses of the loaded value.
12240     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12241       return SDValue();
12242
12243     DebugLoc LdDL = Ld->getDebugLoc();
12244     DebugLoc StDL = N->getDebugLoc();
12245     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12246     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12247     // pair instead.
12248     if (Subtarget->is64Bit() || F64IsLegal) {
12249       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12250       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12251                                   Ld->getPointerInfo(), Ld->isVolatile(),
12252                                   Ld->isNonTemporal(), Ld->getAlignment());
12253       SDValue NewChain = NewLd.getValue(1);
12254       if (TokenFactorIndex != -1) {
12255         Ops.push_back(NewChain);
12256         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12257                                Ops.size());
12258       }
12259       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12260                           St->getPointerInfo(),
12261                           St->isVolatile(), St->isNonTemporal(),
12262                           St->getAlignment());
12263     }
12264
12265     // Otherwise, lower to two pairs of 32-bit loads / stores.
12266     SDValue LoAddr = Ld->getBasePtr();
12267     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12268                                  DAG.getConstant(4, MVT::i32));
12269
12270     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12271                                Ld->getPointerInfo(),
12272                                Ld->isVolatile(), Ld->isNonTemporal(),
12273                                Ld->getAlignment());
12274     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12275                                Ld->getPointerInfo().getWithOffset(4),
12276                                Ld->isVolatile(), Ld->isNonTemporal(),
12277                                MinAlign(Ld->getAlignment(), 4));
12278
12279     SDValue NewChain = LoLd.getValue(1);
12280     if (TokenFactorIndex != -1) {
12281       Ops.push_back(LoLd);
12282       Ops.push_back(HiLd);
12283       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12284                              Ops.size());
12285     }
12286
12287     LoAddr = St->getBasePtr();
12288     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12289                          DAG.getConstant(4, MVT::i32));
12290
12291     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12292                                 St->getPointerInfo(),
12293                                 St->isVolatile(), St->isNonTemporal(),
12294                                 St->getAlignment());
12295     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12296                                 St->getPointerInfo().getWithOffset(4),
12297                                 St->isVolatile(),
12298                                 St->isNonTemporal(),
12299                                 MinAlign(St->getAlignment(), 4));
12300     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12301   }
12302   return SDValue();
12303 }
12304
12305 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12306 /// X86ISD::FXOR nodes.
12307 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12308   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12309   // F[X]OR(0.0, x) -> x
12310   // F[X]OR(x, 0.0) -> x
12311   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12312     if (C->getValueAPF().isPosZero())
12313       return N->getOperand(1);
12314   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12315     if (C->getValueAPF().isPosZero())
12316       return N->getOperand(0);
12317   return SDValue();
12318 }
12319
12320 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12321 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12322   // FAND(0.0, x) -> 0.0
12323   // FAND(x, 0.0) -> 0.0
12324   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12325     if (C->getValueAPF().isPosZero())
12326       return N->getOperand(0);
12327   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12328     if (C->getValueAPF().isPosZero())
12329       return N->getOperand(1);
12330   return SDValue();
12331 }
12332
12333 static SDValue PerformBTCombine(SDNode *N,
12334                                 SelectionDAG &DAG,
12335                                 TargetLowering::DAGCombinerInfo &DCI) {
12336   // BT ignores high bits in the bit index operand.
12337   SDValue Op1 = N->getOperand(1);
12338   if (Op1.hasOneUse()) {
12339     unsigned BitWidth = Op1.getValueSizeInBits();
12340     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12341     APInt KnownZero, KnownOne;
12342     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12343                                           !DCI.isBeforeLegalizeOps());
12344     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12345     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12346         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12347       DCI.CommitTargetLoweringOpt(TLO);
12348   }
12349   return SDValue();
12350 }
12351
12352 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12353   SDValue Op = N->getOperand(0);
12354   if (Op.getOpcode() == ISD::BITCAST)
12355     Op = Op.getOperand(0);
12356   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12357   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12358       VT.getVectorElementType().getSizeInBits() ==
12359       OpVT.getVectorElementType().getSizeInBits()) {
12360     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12361   }
12362   return SDValue();
12363 }
12364
12365 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12366   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12367   //           (and (i32 x86isd::setcc_carry), 1)
12368   // This eliminates the zext. This transformation is necessary because
12369   // ISD::SETCC is always legalized to i8.
12370   DebugLoc dl = N->getDebugLoc();
12371   SDValue N0 = N->getOperand(0);
12372   EVT VT = N->getValueType(0);
12373   if (N0.getOpcode() == ISD::AND &&
12374       N0.hasOneUse() &&
12375       N0.getOperand(0).hasOneUse()) {
12376     SDValue N00 = N0.getOperand(0);
12377     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12378       return SDValue();
12379     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12380     if (!C || C->getZExtValue() != 1)
12381       return SDValue();
12382     return DAG.getNode(ISD::AND, dl, VT,
12383                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12384                                    N00.getOperand(0), N00.getOperand(1)),
12385                        DAG.getConstant(1, VT));
12386   }
12387
12388   return SDValue();
12389 }
12390
12391 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12392 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12393   unsigned X86CC = N->getConstantOperandVal(0);
12394   SDValue EFLAG = N->getOperand(1);
12395   DebugLoc DL = N->getDebugLoc();
12396
12397   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12398   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12399   // cases.
12400   if (X86CC == X86::COND_B)
12401     return DAG.getNode(ISD::AND, DL, MVT::i8,
12402                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12403                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12404                        DAG.getConstant(1, MVT::i8));
12405
12406   return SDValue();
12407 }
12408
12409 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12410                                         const X86TargetLowering *XTLI) {
12411   SDValue Op0 = N->getOperand(0);
12412   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12413   // a 32-bit target where SSE doesn't support i64->FP operations.
12414   if (Op0.getOpcode() == ISD::LOAD) {
12415     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12416     EVT VT = Ld->getValueType(0);
12417     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12418         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12419         !XTLI->getSubtarget()->is64Bit() &&
12420         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12421       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12422                                           Ld->getChain(), Op0, DAG);
12423       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12424       return FILDChain;
12425     }
12426   }
12427   return SDValue();
12428 }
12429
12430 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12431 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12432                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12433   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12434   // the result is either zero or one (depending on the input carry bit).
12435   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12436   if (X86::isZeroNode(N->getOperand(0)) &&
12437       X86::isZeroNode(N->getOperand(1)) &&
12438       // We don't have a good way to replace an EFLAGS use, so only do this when
12439       // dead right now.
12440       SDValue(N, 1).use_empty()) {
12441     DebugLoc DL = N->getDebugLoc();
12442     EVT VT = N->getValueType(0);
12443     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12444     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12445                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12446                                            DAG.getConstant(X86::COND_B,MVT::i8),
12447                                            N->getOperand(2)),
12448                                DAG.getConstant(1, VT));
12449     return DCI.CombineTo(N, Res1, CarryOut);
12450   }
12451
12452   return SDValue();
12453 }
12454
12455 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12456 //      (add Y, (setne X, 0)) -> sbb -1, Y
12457 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12458 //      (sub (setne X, 0), Y) -> adc -1, Y
12459 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12460   DebugLoc DL = N->getDebugLoc();
12461
12462   // Look through ZExts.
12463   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12464   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12465     return SDValue();
12466
12467   SDValue SetCC = Ext.getOperand(0);
12468   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12469     return SDValue();
12470
12471   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12472   if (CC != X86::COND_E && CC != X86::COND_NE)
12473     return SDValue();
12474
12475   SDValue Cmp = SetCC.getOperand(1);
12476   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12477       !X86::isZeroNode(Cmp.getOperand(1)) ||
12478       !Cmp.getOperand(0).getValueType().isInteger())
12479     return SDValue();
12480
12481   SDValue CmpOp0 = Cmp.getOperand(0);
12482   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12483                                DAG.getConstant(1, CmpOp0.getValueType()));
12484
12485   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12486   if (CC == X86::COND_NE)
12487     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12488                        DL, OtherVal.getValueType(), OtherVal,
12489                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12490   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12491                      DL, OtherVal.getValueType(), OtherVal,
12492                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12493 }
12494
12495 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12496                                              DAGCombinerInfo &DCI) const {
12497   SelectionDAG &DAG = DCI.DAG;
12498   switch (N->getOpcode()) {
12499   default: break;
12500   case ISD::EXTRACT_VECTOR_ELT:
12501     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12502   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12503   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12504   case ISD::ADD:
12505   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12506   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12507   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12508   case ISD::SHL:
12509   case ISD::SRA:
12510   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12511   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12512   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12513   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12514   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12515   case X86ISD::FXOR:
12516   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12517   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12518   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12519   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12520   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12521   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12522   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12523   case X86ISD::SHUFPD:
12524   case X86ISD::PALIGN:
12525   case X86ISD::PUNPCKHBW:
12526   case X86ISD::PUNPCKHWD:
12527   case X86ISD::PUNPCKHDQ:
12528   case X86ISD::PUNPCKHQDQ:
12529   case X86ISD::UNPCKHPS:
12530   case X86ISD::UNPCKHPD:
12531   case X86ISD::PUNPCKLBW:
12532   case X86ISD::PUNPCKLWD:
12533   case X86ISD::PUNPCKLDQ:
12534   case X86ISD::PUNPCKLQDQ:
12535   case X86ISD::UNPCKLPS:
12536   case X86ISD::UNPCKLPD:
12537   case X86ISD::VUNPCKLPS:
12538   case X86ISD::VUNPCKLPD:
12539   case X86ISD::VUNPCKLPSY:
12540   case X86ISD::VUNPCKLPDY:
12541   case X86ISD::MOVHLPS:
12542   case X86ISD::MOVLHPS:
12543   case X86ISD::PSHUFD:
12544   case X86ISD::PSHUFHW:
12545   case X86ISD::PSHUFLW:
12546   case X86ISD::MOVSS:
12547   case X86ISD::MOVSD:
12548   case X86ISD::VPERMIL:
12549   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12550   }
12551
12552   return SDValue();
12553 }
12554
12555 /// isTypeDesirableForOp - Return true if the target has native support for
12556 /// the specified value type and it is 'desirable' to use the type for the
12557 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12558 /// instruction encodings are longer and some i16 instructions are slow.
12559 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12560   if (!isTypeLegal(VT))
12561     return false;
12562   if (VT != MVT::i16)
12563     return true;
12564
12565   switch (Opc) {
12566   default:
12567     return true;
12568   case ISD::LOAD:
12569   case ISD::SIGN_EXTEND:
12570   case ISD::ZERO_EXTEND:
12571   case ISD::ANY_EXTEND:
12572   case ISD::SHL:
12573   case ISD::SRL:
12574   case ISD::SUB:
12575   case ISD::ADD:
12576   case ISD::MUL:
12577   case ISD::AND:
12578   case ISD::OR:
12579   case ISD::XOR:
12580     return false;
12581   }
12582 }
12583
12584 /// IsDesirableToPromoteOp - This method query the target whether it is
12585 /// beneficial for dag combiner to promote the specified node. If true, it
12586 /// should return the desired promotion type by reference.
12587 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12588   EVT VT = Op.getValueType();
12589   if (VT != MVT::i16)
12590     return false;
12591
12592   bool Promote = false;
12593   bool Commute = false;
12594   switch (Op.getOpcode()) {
12595   default: break;
12596   case ISD::LOAD: {
12597     LoadSDNode *LD = cast<LoadSDNode>(Op);
12598     // If the non-extending load has a single use and it's not live out, then it
12599     // might be folded.
12600     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12601                                                      Op.hasOneUse()*/) {
12602       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12603              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12604         // The only case where we'd want to promote LOAD (rather then it being
12605         // promoted as an operand is when it's only use is liveout.
12606         if (UI->getOpcode() != ISD::CopyToReg)
12607           return false;
12608       }
12609     }
12610     Promote = true;
12611     break;
12612   }
12613   case ISD::SIGN_EXTEND:
12614   case ISD::ZERO_EXTEND:
12615   case ISD::ANY_EXTEND:
12616     Promote = true;
12617     break;
12618   case ISD::SHL:
12619   case ISD::SRL: {
12620     SDValue N0 = Op.getOperand(0);
12621     // Look out for (store (shl (load), x)).
12622     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12623       return false;
12624     Promote = true;
12625     break;
12626   }
12627   case ISD::ADD:
12628   case ISD::MUL:
12629   case ISD::AND:
12630   case ISD::OR:
12631   case ISD::XOR:
12632     Commute = true;
12633     // fallthrough
12634   case ISD::SUB: {
12635     SDValue N0 = Op.getOperand(0);
12636     SDValue N1 = Op.getOperand(1);
12637     if (!Commute && MayFoldLoad(N1))
12638       return false;
12639     // Avoid disabling potential load folding opportunities.
12640     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12641       return false;
12642     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12643       return false;
12644     Promote = true;
12645   }
12646   }
12647
12648   PVT = MVT::i32;
12649   return Promote;
12650 }
12651
12652 //===----------------------------------------------------------------------===//
12653 //                           X86 Inline Assembly Support
12654 //===----------------------------------------------------------------------===//
12655
12656 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12657   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12658
12659   std::string AsmStr = IA->getAsmString();
12660
12661   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12662   SmallVector<StringRef, 4> AsmPieces;
12663   SplitString(AsmStr, AsmPieces, ";\n");
12664
12665   switch (AsmPieces.size()) {
12666   default: return false;
12667   case 1:
12668     AsmStr = AsmPieces[0];
12669     AsmPieces.clear();
12670     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12671
12672     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12673     // we will turn this bswap into something that will be lowered to logical ops
12674     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12675     // so don't worry about this.
12676     // bswap $0
12677     if (AsmPieces.size() == 2 &&
12678         (AsmPieces[0] == "bswap" ||
12679          AsmPieces[0] == "bswapq" ||
12680          AsmPieces[0] == "bswapl") &&
12681         (AsmPieces[1] == "$0" ||
12682          AsmPieces[1] == "${0:q}")) {
12683       // No need to check constraints, nothing other than the equivalent of
12684       // "=r,0" would be valid here.
12685       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12686       if (!Ty || Ty->getBitWidth() % 16 != 0)
12687         return false;
12688       return IntrinsicLowering::LowerToByteSwap(CI);
12689     }
12690     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12691     if (CI->getType()->isIntegerTy(16) &&
12692         AsmPieces.size() == 3 &&
12693         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12694         AsmPieces[1] == "$$8," &&
12695         AsmPieces[2] == "${0:w}" &&
12696         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12697       AsmPieces.clear();
12698       const std::string &ConstraintsStr = IA->getConstraintString();
12699       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12700       std::sort(AsmPieces.begin(), AsmPieces.end());
12701       if (AsmPieces.size() == 4 &&
12702           AsmPieces[0] == "~{cc}" &&
12703           AsmPieces[1] == "~{dirflag}" &&
12704           AsmPieces[2] == "~{flags}" &&
12705           AsmPieces[3] == "~{fpsr}") {
12706         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12707         if (!Ty || Ty->getBitWidth() % 16 != 0)
12708           return false;
12709         return IntrinsicLowering::LowerToByteSwap(CI);
12710       }
12711     }
12712     break;
12713   case 3:
12714     if (CI->getType()->isIntegerTy(32) &&
12715         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12716       SmallVector<StringRef, 4> Words;
12717       SplitString(AsmPieces[0], Words, " \t,");
12718       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12719           Words[2] == "${0:w}") {
12720         Words.clear();
12721         SplitString(AsmPieces[1], Words, " \t,");
12722         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12723             Words[2] == "$0") {
12724           Words.clear();
12725           SplitString(AsmPieces[2], Words, " \t,");
12726           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12727               Words[2] == "${0:w}") {
12728             AsmPieces.clear();
12729             const std::string &ConstraintsStr = IA->getConstraintString();
12730             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12731             std::sort(AsmPieces.begin(), AsmPieces.end());
12732             if (AsmPieces.size() == 4 &&
12733                 AsmPieces[0] == "~{cc}" &&
12734                 AsmPieces[1] == "~{dirflag}" &&
12735                 AsmPieces[2] == "~{flags}" &&
12736                 AsmPieces[3] == "~{fpsr}") {
12737               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12738               if (!Ty || Ty->getBitWidth() % 16 != 0)
12739                 return false;
12740               return IntrinsicLowering::LowerToByteSwap(CI);
12741             }
12742           }
12743         }
12744       }
12745     }
12746
12747     if (CI->getType()->isIntegerTy(64)) {
12748       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12749       if (Constraints.size() >= 2 &&
12750           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12751           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12752         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12753         SmallVector<StringRef, 4> Words;
12754         SplitString(AsmPieces[0], Words, " \t");
12755         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12756           Words.clear();
12757           SplitString(AsmPieces[1], Words, " \t");
12758           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12759             Words.clear();
12760             SplitString(AsmPieces[2], Words, " \t,");
12761             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12762                 Words[2] == "%edx") {
12763               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12764               if (!Ty || Ty->getBitWidth() % 16 != 0)
12765                 return false;
12766               return IntrinsicLowering::LowerToByteSwap(CI);
12767             }
12768           }
12769         }
12770       }
12771     }
12772     break;
12773   }
12774   return false;
12775 }
12776
12777
12778
12779 /// getConstraintType - Given a constraint letter, return the type of
12780 /// constraint it is for this target.
12781 X86TargetLowering::ConstraintType
12782 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12783   if (Constraint.size() == 1) {
12784     switch (Constraint[0]) {
12785     case 'R':
12786     case 'q':
12787     case 'Q':
12788     case 'f':
12789     case 't':
12790     case 'u':
12791     case 'y':
12792     case 'x':
12793     case 'Y':
12794     case 'l':
12795       return C_RegisterClass;
12796     case 'a':
12797     case 'b':
12798     case 'c':
12799     case 'd':
12800     case 'S':
12801     case 'D':
12802     case 'A':
12803       return C_Register;
12804     case 'I':
12805     case 'J':
12806     case 'K':
12807     case 'L':
12808     case 'M':
12809     case 'N':
12810     case 'G':
12811     case 'C':
12812     case 'e':
12813     case 'Z':
12814       return C_Other;
12815     default:
12816       break;
12817     }
12818   }
12819   return TargetLowering::getConstraintType(Constraint);
12820 }
12821
12822 /// Examine constraint type and operand type and determine a weight value.
12823 /// This object must already have been set up with the operand type
12824 /// and the current alternative constraint selected.
12825 TargetLowering::ConstraintWeight
12826   X86TargetLowering::getSingleConstraintMatchWeight(
12827     AsmOperandInfo &info, const char *constraint) const {
12828   ConstraintWeight weight = CW_Invalid;
12829   Value *CallOperandVal = info.CallOperandVal;
12830     // If we don't have a value, we can't do a match,
12831     // but allow it at the lowest weight.
12832   if (CallOperandVal == NULL)
12833     return CW_Default;
12834   Type *type = CallOperandVal->getType();
12835   // Look at the constraint type.
12836   switch (*constraint) {
12837   default:
12838     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12839   case 'R':
12840   case 'q':
12841   case 'Q':
12842   case 'a':
12843   case 'b':
12844   case 'c':
12845   case 'd':
12846   case 'S':
12847   case 'D':
12848   case 'A':
12849     if (CallOperandVal->getType()->isIntegerTy())
12850       weight = CW_SpecificReg;
12851     break;
12852   case 'f':
12853   case 't':
12854   case 'u':
12855       if (type->isFloatingPointTy())
12856         weight = CW_SpecificReg;
12857       break;
12858   case 'y':
12859       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12860         weight = CW_SpecificReg;
12861       break;
12862   case 'x':
12863   case 'Y':
12864     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12865       weight = CW_Register;
12866     break;
12867   case 'I':
12868     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12869       if (C->getZExtValue() <= 31)
12870         weight = CW_Constant;
12871     }
12872     break;
12873   case 'J':
12874     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12875       if (C->getZExtValue() <= 63)
12876         weight = CW_Constant;
12877     }
12878     break;
12879   case 'K':
12880     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12881       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12882         weight = CW_Constant;
12883     }
12884     break;
12885   case 'L':
12886     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12887       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12888         weight = CW_Constant;
12889     }
12890     break;
12891   case 'M':
12892     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12893       if (C->getZExtValue() <= 3)
12894         weight = CW_Constant;
12895     }
12896     break;
12897   case 'N':
12898     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12899       if (C->getZExtValue() <= 0xff)
12900         weight = CW_Constant;
12901     }
12902     break;
12903   case 'G':
12904   case 'C':
12905     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12906       weight = CW_Constant;
12907     }
12908     break;
12909   case 'e':
12910     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12911       if ((C->getSExtValue() >= -0x80000000LL) &&
12912           (C->getSExtValue() <= 0x7fffffffLL))
12913         weight = CW_Constant;
12914     }
12915     break;
12916   case 'Z':
12917     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12918       if (C->getZExtValue() <= 0xffffffff)
12919         weight = CW_Constant;
12920     }
12921     break;
12922   }
12923   return weight;
12924 }
12925
12926 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12927 /// with another that has more specific requirements based on the type of the
12928 /// corresponding operand.
12929 const char *X86TargetLowering::
12930 LowerXConstraint(EVT ConstraintVT) const {
12931   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12932   // 'f' like normal targets.
12933   if (ConstraintVT.isFloatingPoint()) {
12934     if (Subtarget->hasXMMInt())
12935       return "Y";
12936     if (Subtarget->hasXMM())
12937       return "x";
12938   }
12939
12940   return TargetLowering::LowerXConstraint(ConstraintVT);
12941 }
12942
12943 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12944 /// vector.  If it is invalid, don't add anything to Ops.
12945 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12946                                                      std::string &Constraint,
12947                                                      std::vector<SDValue>&Ops,
12948                                                      SelectionDAG &DAG) const {
12949   SDValue Result(0, 0);
12950
12951   // Only support length 1 constraints for now.
12952   if (Constraint.length() > 1) return;
12953
12954   char ConstraintLetter = Constraint[0];
12955   switch (ConstraintLetter) {
12956   default: break;
12957   case 'I':
12958     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12959       if (C->getZExtValue() <= 31) {
12960         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12961         break;
12962       }
12963     }
12964     return;
12965   case 'J':
12966     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12967       if (C->getZExtValue() <= 63) {
12968         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12969         break;
12970       }
12971     }
12972     return;
12973   case 'K':
12974     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12975       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12976         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12977         break;
12978       }
12979     }
12980     return;
12981   case 'N':
12982     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12983       if (C->getZExtValue() <= 255) {
12984         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12985         break;
12986       }
12987     }
12988     return;
12989   case 'e': {
12990     // 32-bit signed value
12991     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12992       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12993                                            C->getSExtValue())) {
12994         // Widen to 64 bits here to get it sign extended.
12995         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12996         break;
12997       }
12998     // FIXME gcc accepts some relocatable values here too, but only in certain
12999     // memory models; it's complicated.
13000     }
13001     return;
13002   }
13003   case 'Z': {
13004     // 32-bit unsigned value
13005     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13006       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13007                                            C->getZExtValue())) {
13008         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13009         break;
13010       }
13011     }
13012     // FIXME gcc accepts some relocatable values here too, but only in certain
13013     // memory models; it's complicated.
13014     return;
13015   }
13016   case 'i': {
13017     // Literal immediates are always ok.
13018     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13019       // Widen to 64 bits here to get it sign extended.
13020       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13021       break;
13022     }
13023
13024     // In any sort of PIC mode addresses need to be computed at runtime by
13025     // adding in a register or some sort of table lookup.  These can't
13026     // be used as immediates.
13027     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13028       return;
13029
13030     // If we are in non-pic codegen mode, we allow the address of a global (with
13031     // an optional displacement) to be used with 'i'.
13032     GlobalAddressSDNode *GA = 0;
13033     int64_t Offset = 0;
13034
13035     // Match either (GA), (GA+C), (GA+C1+C2), etc.
13036     while (1) {
13037       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13038         Offset += GA->getOffset();
13039         break;
13040       } else if (Op.getOpcode() == ISD::ADD) {
13041         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13042           Offset += C->getZExtValue();
13043           Op = Op.getOperand(0);
13044           continue;
13045         }
13046       } else if (Op.getOpcode() == ISD::SUB) {
13047         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13048           Offset += -C->getZExtValue();
13049           Op = Op.getOperand(0);
13050           continue;
13051         }
13052       }
13053
13054       // Otherwise, this isn't something we can handle, reject it.
13055       return;
13056     }
13057
13058     const GlobalValue *GV = GA->getGlobal();
13059     // If we require an extra load to get this address, as in PIC mode, we
13060     // can't accept it.
13061     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
13062                                                         getTargetMachine())))
13063       return;
13064
13065     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
13066                                         GA->getValueType(0), Offset);
13067     break;
13068   }
13069   }
13070
13071   if (Result.getNode()) {
13072     Ops.push_back(Result);
13073     return;
13074   }
13075   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13076 }
13077
13078 std::pair<unsigned, const TargetRegisterClass*>
13079 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
13080                                                 EVT VT) const {
13081   // First, see if this is a constraint that directly corresponds to an LLVM
13082   // register class.
13083   if (Constraint.size() == 1) {
13084     // GCC Constraint Letters
13085     switch (Constraint[0]) {
13086     default: break;
13087       // TODO: Slight differences here in allocation order and leaving
13088       // RIP in the class. Do they matter any more here than they do
13089       // in the normal allocation?
13090     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
13091       if (Subtarget->is64Bit()) {
13092         if (VT == MVT::i32 || VT == MVT::f32)
13093           return std::make_pair(0U, X86::GR32RegisterClass);
13094         else if (VT == MVT::i16)
13095           return std::make_pair(0U, X86::GR16RegisterClass);
13096         else if (VT == MVT::i8 || VT == MVT::i1)
13097           return std::make_pair(0U, X86::GR8RegisterClass);
13098         else if (VT == MVT::i64 || VT == MVT::f64)
13099           return std::make_pair(0U, X86::GR64RegisterClass);
13100         break;
13101       }
13102       // 32-bit fallthrough
13103     case 'Q':   // Q_REGS
13104       if (VT == MVT::i32 || VT == MVT::f32)
13105         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
13106       else if (VT == MVT::i16)
13107         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
13108       else if (VT == MVT::i8 || VT == MVT::i1)
13109         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
13110       else if (VT == MVT::i64)
13111         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
13112       break;
13113     case 'r':   // GENERAL_REGS
13114     case 'l':   // INDEX_REGS
13115       if (VT == MVT::i8 || VT == MVT::i1)
13116         return std::make_pair(0U, X86::GR8RegisterClass);
13117       if (VT == MVT::i16)
13118         return std::make_pair(0U, X86::GR16RegisterClass);
13119       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
13120         return std::make_pair(0U, X86::GR32RegisterClass);
13121       return std::make_pair(0U, X86::GR64RegisterClass);
13122     case 'R':   // LEGACY_REGS
13123       if (VT == MVT::i8 || VT == MVT::i1)
13124         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
13125       if (VT == MVT::i16)
13126         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
13127       if (VT == MVT::i32 || !Subtarget->is64Bit())
13128         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
13129       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
13130     case 'f':  // FP Stack registers.
13131       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13132       // value to the correct fpstack register class.
13133       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13134         return std::make_pair(0U, X86::RFP32RegisterClass);
13135       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13136         return std::make_pair(0U, X86::RFP64RegisterClass);
13137       return std::make_pair(0U, X86::RFP80RegisterClass);
13138     case 'y':   // MMX_REGS if MMX allowed.
13139       if (!Subtarget->hasMMX()) break;
13140       return std::make_pair(0U, X86::VR64RegisterClass);
13141     case 'Y':   // SSE_REGS if SSE2 allowed
13142       if (!Subtarget->hasXMMInt()) break;
13143       // FALL THROUGH.
13144     case 'x':   // SSE_REGS if SSE1 allowed
13145       if (!Subtarget->hasXMM()) break;
13146
13147       switch (VT.getSimpleVT().SimpleTy) {
13148       default: break;
13149       // Scalar SSE types.
13150       case MVT::f32:
13151       case MVT::i32:
13152         return std::make_pair(0U, X86::FR32RegisterClass);
13153       case MVT::f64:
13154       case MVT::i64:
13155         return std::make_pair(0U, X86::FR64RegisterClass);
13156       // Vector types.
13157       case MVT::v16i8:
13158       case MVT::v8i16:
13159       case MVT::v4i32:
13160       case MVT::v2i64:
13161       case MVT::v4f32:
13162       case MVT::v2f64:
13163         return std::make_pair(0U, X86::VR128RegisterClass);
13164       }
13165       break;
13166     }
13167   }
13168
13169   // Use the default implementation in TargetLowering to convert the register
13170   // constraint into a member of a register class.
13171   std::pair<unsigned, const TargetRegisterClass*> Res;
13172   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13173
13174   // Not found as a standard register?
13175   if (Res.second == 0) {
13176     // Map st(0) -> st(7) -> ST0
13177     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13178         tolower(Constraint[1]) == 's' &&
13179         tolower(Constraint[2]) == 't' &&
13180         Constraint[3] == '(' &&
13181         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13182         Constraint[5] == ')' &&
13183         Constraint[6] == '}') {
13184
13185       Res.first = X86::ST0+Constraint[4]-'0';
13186       Res.second = X86::RFP80RegisterClass;
13187       return Res;
13188     }
13189
13190     // GCC allows "st(0)" to be called just plain "st".
13191     if (StringRef("{st}").equals_lower(Constraint)) {
13192       Res.first = X86::ST0;
13193       Res.second = X86::RFP80RegisterClass;
13194       return Res;
13195     }
13196
13197     // flags -> EFLAGS
13198     if (StringRef("{flags}").equals_lower(Constraint)) {
13199       Res.first = X86::EFLAGS;
13200       Res.second = X86::CCRRegisterClass;
13201       return Res;
13202     }
13203
13204     // 'A' means EAX + EDX.
13205     if (Constraint == "A") {
13206       Res.first = X86::EAX;
13207       Res.second = X86::GR32_ADRegisterClass;
13208       return Res;
13209     }
13210     return Res;
13211   }
13212
13213   // Otherwise, check to see if this is a register class of the wrong value
13214   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13215   // turn into {ax},{dx}.
13216   if (Res.second->hasType(VT))
13217     return Res;   // Correct type already, nothing to do.
13218
13219   // All of the single-register GCC register classes map their values onto
13220   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13221   // really want an 8-bit or 32-bit register, map to the appropriate register
13222   // class and return the appropriate register.
13223   if (Res.second == X86::GR16RegisterClass) {
13224     if (VT == MVT::i8) {
13225       unsigned DestReg = 0;
13226       switch (Res.first) {
13227       default: break;
13228       case X86::AX: DestReg = X86::AL; break;
13229       case X86::DX: DestReg = X86::DL; break;
13230       case X86::CX: DestReg = X86::CL; break;
13231       case X86::BX: DestReg = X86::BL; break;
13232       }
13233       if (DestReg) {
13234         Res.first = DestReg;
13235         Res.second = X86::GR8RegisterClass;
13236       }
13237     } else if (VT == MVT::i32) {
13238       unsigned DestReg = 0;
13239       switch (Res.first) {
13240       default: break;
13241       case X86::AX: DestReg = X86::EAX; break;
13242       case X86::DX: DestReg = X86::EDX; break;
13243       case X86::CX: DestReg = X86::ECX; break;
13244       case X86::BX: DestReg = X86::EBX; break;
13245       case X86::SI: DestReg = X86::ESI; break;
13246       case X86::DI: DestReg = X86::EDI; break;
13247       case X86::BP: DestReg = X86::EBP; break;
13248       case X86::SP: DestReg = X86::ESP; break;
13249       }
13250       if (DestReg) {
13251         Res.first = DestReg;
13252         Res.second = X86::GR32RegisterClass;
13253       }
13254     } else if (VT == MVT::i64) {
13255       unsigned DestReg = 0;
13256       switch (Res.first) {
13257       default: break;
13258       case X86::AX: DestReg = X86::RAX; break;
13259       case X86::DX: DestReg = X86::RDX; break;
13260       case X86::CX: DestReg = X86::RCX; break;
13261       case X86::BX: DestReg = X86::RBX; break;
13262       case X86::SI: DestReg = X86::RSI; break;
13263       case X86::DI: DestReg = X86::RDI; break;
13264       case X86::BP: DestReg = X86::RBP; break;
13265       case X86::SP: DestReg = X86::RSP; break;
13266       }
13267       if (DestReg) {
13268         Res.first = DestReg;
13269         Res.second = X86::GR64RegisterClass;
13270       }
13271     }
13272   } else if (Res.second == X86::FR32RegisterClass ||
13273              Res.second == X86::FR64RegisterClass ||
13274              Res.second == X86::VR128RegisterClass) {
13275     // Handle references to XMM physical registers that got mapped into the
13276     // wrong class.  This can happen with constraints like {xmm0} where the
13277     // target independent register mapper will just pick the first match it can
13278     // find, ignoring the required type.
13279     if (VT == MVT::f32)
13280       Res.second = X86::FR32RegisterClass;
13281     else if (VT == MVT::f64)
13282       Res.second = X86::FR64RegisterClass;
13283     else if (X86::VR128RegisterClass->hasType(VT))
13284       Res.second = X86::VR128RegisterClass;
13285   }
13286
13287   return Res;
13288 }