ff4a283b58318462d18207fe84c8e06d31fc2f49
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference.  Idx is an index in the 128 bits we
80 /// want.  It need not be aligned to a 128-bit bounday.  That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
83                                    SDValue Idx,
84                                    SelectionDAG &DAG,
85                                    DebugLoc dl) {
86   EVT VT = Vec.getValueType();
87   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88
89   EVT ElVT = VT.getVectorElementType();
90
91   int Factor = VT.getSizeInBits() / 128;
92
93   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94                                   ElVT,
95                                   VT.getVectorNumElements() / Factor);
96
97   // Extract from UNDEF is UNDEF.
98   if (Vec.getOpcode() == ISD::UNDEF)
99     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100
101   if (isa<ConstantSDNode>(Idx)) {
102     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103
104     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
105     // we can match to VEXTRACTF128.
106     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107
108     // This is the index of the first element of the 128-bit chunk
109     // we want.
110     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
111                                  * ElemsPerChunk);
112
113     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114
115     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116                                  VecIdx);
117
118     return Result;
119   }
120
121   return SDValue();
122 }
123
124 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference.  Idx is an index in the 128 bits
127 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
130                                   SDValue Vec,
131                                   SDValue Idx,
132                                   SelectionDAG &DAG,
133                                   DebugLoc dl) {
134   if (isa<ConstantSDNode>(Idx)) {
135     EVT VT = Vec.getValueType();
136     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138     EVT ElVT = VT.getVectorElementType();
139
140     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142     EVT ResultVT = Result.getValueType();
143
144     // Insert the relevant 128 bits.
145     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147     // This is the index of the first element of the 128-bit chunk
148     // we want.
149     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                  * ElemsPerChunk);
151
152     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                          VecIdx);
156     return Result;
157   }
158
159   return SDValue();
160 }
161
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164   DebugLoc dl = Lower.getDebugLoc();
165
166   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168   EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                             Lower.getValueType().getVectorElementType(),
170                             Lower.getValueType().getVectorNumElements() * 2);
171
172   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175   // Insert the upper subvector.
176   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                    DAG.getConstant(
178                                      // This is half the length of the result
179                                      // vector.  Start inserting the upper 128
180                                      // bits here.
181                                      Lower.getValueType().getVectorNumElements(),
182                                      MVT::i32),
183                                    DAG, dl);
184
185   // Insert the lower subvector.
186   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187   return Vec;
188 }
189
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192   bool is64Bit = Subtarget->is64Bit();
193
194   if (Subtarget->isTargetEnvMacho()) {
195     if (is64Bit)
196       return new X8664_MachoTargetObjectFile();
197     return new TargetLoweringObjectFileMachO();
198   }
199
200   if (Subtarget->isTargetELF()) {
201     if (is64Bit)
202       return new X8664_ELFTargetObjectFile(TM);
203     return new X8632_ELFTargetObjectFile(TM);
204   }
205   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206     return new TargetLoweringObjectFileCOFF();
207   llvm_unreachable("unknown subtarget type");
208 }
209
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211   : TargetLowering(TM, createTLOF(TM)) {
212   Subtarget = &TM.getSubtarget<X86Subtarget>();
213   X86ScalarSSEf64 = Subtarget->hasXMMInt();
214   X86ScalarSSEf32 = Subtarget->hasXMM();
215   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217   RegInfo = TM.getRegisterInfo();
218   TD = getTargetData();
219
220   // Set up the TargetLowering object.
221   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223   // X86 is weird, it always uses i8 for shift amounts and setcc results.
224   setBooleanContents(ZeroOrOneBooleanContent);
225     
226   // For 64-bit since we have so many registers use the ILP scheduler, for
227   // 32-bit code use the register pressure specific scheduling.
228   if (Subtarget->is64Bit())
229     setSchedulingPreference(Sched::ILP);
230   else
231     setSchedulingPreference(Sched::RegPressure);
232   setStackPointerRegisterToSaveRestore(X86StackPtr);
233
234   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235     // Setup Windows compiler runtime calls.
236     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
244   }
245
246   if (Subtarget->isTargetDarwin()) {
247     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248     setUseUnderscoreSetJmp(false);
249     setUseUnderscoreLongJmp(false);
250   } else if (Subtarget->isTargetMingw()) {
251     // MS runtime is weird: it exports _setjmp, but longjmp!
252     setUseUnderscoreSetJmp(true);
253     setUseUnderscoreLongJmp(false);
254   } else {
255     setUseUnderscoreSetJmp(true);
256     setUseUnderscoreLongJmp(true);
257   }
258
259   // Set up the register classes.
260   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263   if (Subtarget->is64Bit())
264     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265
266   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267
268   // We don't accept any truncstore of integer registers.
269   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
275
276   // SETOEQ and SETUNE require checking two conditions.
277   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283
284   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285   // operation.
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
288   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
289
290   if (Subtarget->is64Bit()) {
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
292     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
293   } else if (!UseSoftFloat) {
294     // We have an algorithm for SSE2->double, and we turn this into a
295     // 64-bit FILD followed by conditional FADD for other targets.
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
297     // We have an algorithm for SSE2, and we turn this into a 64-bit
298     // FILD for other targets.
299     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
300   }
301
302   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303   // this operation.
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
305   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
306
307   if (!UseSoftFloat) {
308     // SSE has no i16 to fp conversion, only i32
309     if (X86ScalarSSEf32) {
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
311       // f32 and f64 cases are Legal, f80 case is not
312       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
313     } else {
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
316     }
317   } else {
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
319     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
320   }
321
322   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
323   // are Legal, f80 is custom lowered.
324   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
325   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
326
327   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328   // this operation.
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
330   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
331
332   if (X86ScalarSSEf32) {
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
334     // f32 and f64 cases are Legal, f80 case is not
335     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
336   } else {
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
339   }
340
341   // Handle FP_TO_UINT by promoting the destination to a larger signed
342   // conversion.
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
345   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
346
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
349     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
350   } else if (!UseSoftFloat) {
351     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352       // Expand FP_TO_UINT into a select.
353       // FIXME: We would like to use a Custom expander here eventually to do
354       // the optimal thing for SSE vs. the default expansion in the legalizer.
355       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
356     else
357       // With SSE3 we can use fisttpll to convert to a signed i64; without
358       // SSE, we're stuck with a fistpll.
359       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
360   }
361
362   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363   if (!X86ScalarSSEf64) {
364     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
365     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
366     if (Subtarget->is64Bit()) {
367       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
368       // Without SSE, i64->f64 goes through memory.
369       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
370     }
371   }
372
373   // Scalar integer divide and remainder are lowered to use operations that
374   // produce two results, to match the available instructions. This exposes
375   // the two-result form to trivial CSE, which is able to combine x/y and x%y
376   // into a single instruction.
377   //
378   // Scalar integer multiply-high is also lowered to use two-result
379   // operations, to match the available instructions. However, plain multiply
380   // (low) operations are left as Legal, as there are single-result
381   // instructions for this in x86. Using the two-result multiply instructions
382   // when both high and low results are needed must be arranged by dagcombine.
383   for (unsigned i = 0, e = 4; i != e; ++i) {
384     MVT VT = IntVTs[i];
385     setOperationAction(ISD::MULHS, VT, Expand);
386     setOperationAction(ISD::MULHU, VT, Expand);
387     setOperationAction(ISD::SDIV, VT, Expand);
388     setOperationAction(ISD::UDIV, VT, Expand);
389     setOperationAction(ISD::SREM, VT, Expand);
390     setOperationAction(ISD::UREM, VT, Expand);
391
392     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393     setOperationAction(ISD::ADDC, VT, Custom);
394     setOperationAction(ISD::ADDE, VT, Custom);
395     setOperationAction(ISD::SUBC, VT, Custom);
396     setOperationAction(ISD::SUBE, VT, Custom);
397   }
398
399   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
400   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
401   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
408   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
412   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
413
414   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
416   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
418   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
419   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
420   if (Subtarget->is64Bit()) {
421     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
422     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
423   }
424
425   if (Subtarget->hasPOPCNT()) {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
427   } else {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
433   }
434
435   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
436   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
437
438   // These should be promoted to a larger select which is supported.
439   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
440   // X86 wants to expand cmov itself.
441   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
455     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
456   }
457   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
458
459   // Darwin ABI issue.
460   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
461   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
463   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
464   if (Subtarget->is64Bit())
465     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
467   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
470     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
471     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
472     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
473     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
474   }
475   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
478   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
479   if (Subtarget->is64Bit()) {
480     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
482     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
483   }
484
485   if (Subtarget->hasXMM())
486     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
487
488   // We may not have a libcall for MEMBARRIER so we should lower this.
489   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
490
491   // On X86 and X86-64, atomic operations are lowered to locked instructions.
492   // Locked instructions, in turn, have implicit fence semantics (all memory
493   // operations are flushed before issuing the locked instruction, and they
494   // are not buffered), so we can fold away the common pattern of
495   // fence-atomic-fence.
496   setShouldFoldAtomicFences(true);
497
498   // Expand certain atomics
499   for (unsigned i = 0, e = 4; i != e; ++i) {
500     MVT VT = IntVTs[i];
501     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
503   }
504
505   if (!Subtarget->is64Bit()) {
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   // FIXME - use subtarget debug flags
516   if (!Subtarget->isTargetDarwin() &&
517       !Subtarget->isTargetELF() &&
518       !Subtarget->isTargetCygMing()) {
519     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526   if (Subtarget->is64Bit()) {
527     setExceptionPointerRegister(X86::RAX);
528     setExceptionSelectorRegister(X86::RDX);
529   } else {
530     setExceptionPointerRegister(X86::EAX);
531     setExceptionSelectorRegister(X86::EDX);
532   }
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539
540   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   if (Subtarget->is64Bit()) {
544     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
545     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
546   } else {
547     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
548     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
549   }
550
551   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
552   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
553   setOperationAction(ISD::DYNAMIC_STACKALLOC,
554                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555                      (Subtarget->isTargetCOFF()
556                       && !Subtarget->isTargetEnvMacho()
557                       ? Custom : Expand));
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN , MVT::f64, Expand);
579     setOperationAction(ISD::FCOS , MVT::f64, Expand);
580     setOperationAction(ISD::FSIN , MVT::f32, Expand);
581     setOperationAction(ISD::FCOS , MVT::f32, Expand);
582
583     // Expand FP immediates into loads from the stack, except for the special
584     // cases we handle.
585     addLegalFPImmediate(APFloat(+0.0)); // xorpd
586     addLegalFPImmediate(APFloat(+0.0f)); // xorps
587   } else if (!UseSoftFloat && X86ScalarSSEf32) {
588     // Use SSE for f32, x87 for f64.
589     // Set up the FP register classes.
590     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592
593     // Use ANDPS to simulate FABS.
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
600
601     // Use ANDPS and ORPS to simulate FCOPYSIGN.
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604
605     // We don't support sin/cos/fmod
606     setOperationAction(ISD::FSIN , MVT::f32, Expand);
607     setOperationAction(ISD::FCOS , MVT::f32, Expand);
608
609     // Special cases we handle for FP constants.
610     addLegalFPImmediate(APFloat(+0.0f)); // xorps
611     addLegalFPImmediate(APFloat(+0.0)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
615
616     if (!UnsafeFPMath) {
617       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
618       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
619     }
620   } else if (!UseSoftFloat) {
621     // f32 and f64 in x87.
622     // Set up the FP register classes.
623     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
625
626     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
627     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
630
631     if (!UnsafeFPMath) {
632       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
633       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
634     }
635     addLegalFPImmediate(APFloat(+0.0)); // FLD0
636     addLegalFPImmediate(APFloat(+1.0)); // FLD1
637     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
643   }
644
645   // Long double always uses X87.
646   if (!UseSoftFloat) {
647     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
649     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
650     {
651       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652       addLegalFPImmediate(TmpFlt);  // FLD0
653       TmpFlt.changeSign();
654       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
655
656       bool ignored;
657       APFloat TmpFlt2(+1.0);
658       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
659                       &ignored);
660       addLegalFPImmediate(TmpFlt2);  // FLD1
661       TmpFlt2.changeSign();
662       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
663     }
664
665     if (!UnsafeFPMath) {
666       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
667       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
668     }
669   }
670
671   // Always use a library call for pow.
672   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
674   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
675
676   setOperationAction(ISD::FLOG, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP, MVT::f80, Expand);
680   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
834     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
835     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
836     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     // i8 and i16 vectors are custom , because the source register and source
932     // source memory operand types are not the same width.  f32 vectors are
933     // custom since the immediate controlling the insert encodes additional
934     // information.
935     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
944
945     if (Subtarget->is64Bit()) {
946       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
947       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
948     }
949   }
950
951   if (Subtarget->hasSSE2()) {
952     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
953     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
954     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
955
956     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
957     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
959
960     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
961     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
962   }
963
964   if (Subtarget->hasSSE42())
965     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
966
967   if (!UseSoftFloat && Subtarget->hasAVX()) {
968     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
969     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
970     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
971     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
972     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
973
974     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
975     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
976     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
977     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
978
979     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
980     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
981     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
982     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
983     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
984     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
985
986     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
987     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
988     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
989     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
990     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
991     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
992
993     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
994     // insert_vector_elt extract_subvector and extract_vector_elt for
995     // 256-bit types.
996     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
997          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
998          ++i) {
999       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1000       // Do not attempt to custom lower non-256-bit vectors
1001       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1002           || (MVT(VT).getSizeInBits() < 256))
1003         continue;
1004       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1005       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1006       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1007       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1008       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1009     }
1010     // Custom-lower insert_subvector and extract_subvector based on
1011     // the result type.
1012     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1013          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1014          ++i) {
1015       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1016       // Do not attempt to custom lower non-256-bit vectors
1017       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1018         continue;
1019
1020       if (MVT(VT).getSizeInBits() == 128) {
1021         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1022       }
1023       else if (MVT(VT).getSizeInBits() == 256) {
1024         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1025       }
1026     }
1027
1028     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1029     // Don't promote loads because we need them for VPERM vector index versions.
1030
1031     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1032          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1033          VT++) {
1034       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1035           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1036         continue;
1037       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1038       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1039       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1040       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1041       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1042       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1043       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1044       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1045       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1046       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1047     }
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   if (Subtarget->is64Bit())
1097     setTargetDAGCombine(ISD::MUL);
1098
1099   computeRegisterProperties();
1100
1101   // On Darwin, -Os means optimize for size without hurting performance,
1102   // do not reduce the limit.
1103   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1104   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1105   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1106   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1107   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1108   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1109   setPrefLoopAlignment(16);
1110   benefitFromCodePlacementOpt = true;
1111
1112   setPrefFunctionAlignment(4);
1113 }
1114
1115
1116 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1117   return MVT::i8;
1118 }
1119
1120
1121 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1122 /// the desired ByVal argument alignment.
1123 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1124   if (MaxAlign == 16)
1125     return;
1126   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1127     if (VTy->getBitWidth() == 128)
1128       MaxAlign = 16;
1129   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1130     unsigned EltAlign = 0;
1131     getMaxByValAlign(ATy->getElementType(), EltAlign);
1132     if (EltAlign > MaxAlign)
1133       MaxAlign = EltAlign;
1134   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1135     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1136       unsigned EltAlign = 0;
1137       getMaxByValAlign(STy->getElementType(i), EltAlign);
1138       if (EltAlign > MaxAlign)
1139         MaxAlign = EltAlign;
1140       if (MaxAlign == 16)
1141         break;
1142     }
1143   }
1144   return;
1145 }
1146
1147 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1148 /// function arguments in the caller parameter area. For X86, aggregates
1149 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1150 /// are at 4-byte boundaries.
1151 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1152   if (Subtarget->is64Bit()) {
1153     // Max of 8 and alignment of type.
1154     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1155     if (TyAlign > 8)
1156       return TyAlign;
1157     return 8;
1158   }
1159
1160   unsigned Align = 4;
1161   if (Subtarget->hasXMM())
1162     getMaxByValAlign(Ty, Align);
1163   return Align;
1164 }
1165
1166 /// getOptimalMemOpType - Returns the target specific optimal type for load
1167 /// and store operations as a result of memset, memcpy, and memmove
1168 /// lowering. If DstAlign is zero that means it's safe to destination
1169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1170 /// means there isn't a need to check it against alignment requirement,
1171 /// probably because the source does not need to be loaded. If
1172 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1173 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1174 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1175 /// constant so it does not need to be loaded.
1176 /// It returns EVT::Other if the type should be determined using generic
1177 /// target-independent logic.
1178 EVT
1179 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1180                                        unsigned DstAlign, unsigned SrcAlign,
1181                                        bool NonScalarIntSafe,
1182                                        bool MemcpyStrSrc,
1183                                        MachineFunction &MF) const {
1184   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1185   // linux.  This is because the stack realignment code can't handle certain
1186   // cases like PR2962.  This should be removed when PR2962 is fixed.
1187   const Function *F = MF.getFunction();
1188   if (NonScalarIntSafe &&
1189       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1190     if (Size >= 16 &&
1191         (Subtarget->isUnalignedMemAccessFast() ||
1192          ((DstAlign == 0 || DstAlign >= 16) &&
1193           (SrcAlign == 0 || SrcAlign >= 16))) &&
1194         Subtarget->getStackAlignment() >= 16) {
1195       if (Subtarget->hasSSE2())
1196         return MVT::v4i32;
1197       if (Subtarget->hasSSE1())
1198         return MVT::v4f32;
1199     } else if (!MemcpyStrSrc && Size >= 8 &&
1200                !Subtarget->is64Bit() &&
1201                Subtarget->getStackAlignment() >= 8 &&
1202                Subtarget->hasXMMInt()) {
1203       // Do not use f64 to lower memcpy if source is string constant. It's
1204       // better to use i32 to avoid the loads.
1205       return MVT::f64;
1206     }
1207   }
1208   if (Subtarget->is64Bit() && Size >= 8)
1209     return MVT::i64;
1210   return MVT::i32;
1211 }
1212
1213 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1214 /// current function.  The returned value is a member of the
1215 /// MachineJumpTableInfo::JTEntryKind enum.
1216 unsigned X86TargetLowering::getJumpTableEncoding() const {
1217   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1218   // symbol.
1219   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1220       Subtarget->isPICStyleGOT())
1221     return MachineJumpTableInfo::EK_Custom32;
1222
1223   // Otherwise, use the normal jump table encoding heuristics.
1224   return TargetLowering::getJumpTableEncoding();
1225 }
1226
1227 const MCExpr *
1228 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1229                                              const MachineBasicBlock *MBB,
1230                                              unsigned uid,MCContext &Ctx) const{
1231   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1232          Subtarget->isPICStyleGOT());
1233   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1234   // entries.
1235   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1236                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1237 }
1238
1239 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1240 /// jumptable.
1241 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1242                                                     SelectionDAG &DAG) const {
1243   if (!Subtarget->is64Bit())
1244     // This doesn't have DebugLoc associated with it, but is not really the
1245     // same as a Register.
1246     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1247   return Table;
1248 }
1249
1250 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1251 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1252 /// MCExpr.
1253 const MCExpr *X86TargetLowering::
1254 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1255                              MCContext &Ctx) const {
1256   // X86-64 uses RIP relative addressing based on the jump table label.
1257   if (Subtarget->isPICStyleRIPRel())
1258     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1259
1260   // Otherwise, the reference is relative to the PIC base.
1261   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1262 }
1263
1264 // FIXME: Why this routine is here? Move to RegInfo!
1265 std::pair<const TargetRegisterClass*, uint8_t>
1266 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1267   const TargetRegisterClass *RRC = 0;
1268   uint8_t Cost = 1;
1269   switch (VT.getSimpleVT().SimpleTy) {
1270   default:
1271     return TargetLowering::findRepresentativeClass(VT);
1272   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1273     RRC = (Subtarget->is64Bit()
1274            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1275     break;
1276   case MVT::x86mmx:
1277     RRC = X86::VR64RegisterClass;
1278     break;
1279   case MVT::f32: case MVT::f64:
1280   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1281   case MVT::v4f32: case MVT::v2f64:
1282   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1283   case MVT::v4f64:
1284     RRC = X86::VR128RegisterClass;
1285     break;
1286   }
1287   return std::make_pair(RRC, Cost);
1288 }
1289
1290 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1291                                                unsigned &Offset) const {
1292   if (!Subtarget->isTargetLinux())
1293     return false;
1294
1295   if (Subtarget->is64Bit()) {
1296     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1297     Offset = 0x28;
1298     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1299       AddressSpace = 256;
1300     else
1301       AddressSpace = 257;
1302   } else {
1303     // %gs:0x14 on i386
1304     Offset = 0x14;
1305     AddressSpace = 256;
1306   }
1307   return true;
1308 }
1309
1310
1311 //===----------------------------------------------------------------------===//
1312 //               Return Value Calling Convention Implementation
1313 //===----------------------------------------------------------------------===//
1314
1315 #include "X86GenCallingConv.inc"
1316
1317 bool
1318 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1319                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1320                         LLVMContext &Context) const {
1321   SmallVector<CCValAssign, 16> RVLocs;
1322   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1323                  RVLocs, Context);
1324   return CCInfo.CheckReturn(Outs, RetCC_X86);
1325 }
1326
1327 SDValue
1328 X86TargetLowering::LowerReturn(SDValue Chain,
1329                                CallingConv::ID CallConv, bool isVarArg,
1330                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1331                                const SmallVectorImpl<SDValue> &OutVals,
1332                                DebugLoc dl, SelectionDAG &DAG) const {
1333   MachineFunction &MF = DAG.getMachineFunction();
1334   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1335
1336   SmallVector<CCValAssign, 16> RVLocs;
1337   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1338                  RVLocs, *DAG.getContext());
1339   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1340
1341   // Add the regs to the liveout set for the function.
1342   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1343   for (unsigned i = 0; i != RVLocs.size(); ++i)
1344     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1345       MRI.addLiveOut(RVLocs[i].getLocReg());
1346
1347   SDValue Flag;
1348
1349   SmallVector<SDValue, 6> RetOps;
1350   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1351   // Operand #1 = Bytes To Pop
1352   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1353                    MVT::i16));
1354
1355   // Copy the result values into the output registers.
1356   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1357     CCValAssign &VA = RVLocs[i];
1358     assert(VA.isRegLoc() && "Can only return in registers!");
1359     SDValue ValToCopy = OutVals[i];
1360     EVT ValVT = ValToCopy.getValueType();
1361
1362     // If this is x86-64, and we disabled SSE, we can't return FP values,
1363     // or SSE or MMX vectors.
1364     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1365          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1366           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1367       report_fatal_error("SSE register return with SSE disabled");
1368     }
1369     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1370     // llvm-gcc has never done it right and no one has noticed, so this
1371     // should be OK for now.
1372     if (ValVT == MVT::f64 &&
1373         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1374       report_fatal_error("SSE2 register return with SSE2 disabled");
1375
1376     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1377     // the RET instruction and handled by the FP Stackifier.
1378     if (VA.getLocReg() == X86::ST0 ||
1379         VA.getLocReg() == X86::ST1) {
1380       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1381       // change the value to the FP stack register class.
1382       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1383         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1384       RetOps.push_back(ValToCopy);
1385       // Don't emit a copytoreg.
1386       continue;
1387     }
1388
1389     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1390     // which is returned in RAX / RDX.
1391     if (Subtarget->is64Bit()) {
1392       if (ValVT == MVT::x86mmx) {
1393         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1394           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1395           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1396                                   ValToCopy);
1397           // If we don't have SSE2 available, convert to v4f32 so the generated
1398           // register is legal.
1399           if (!Subtarget->hasSSE2())
1400             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1401         }
1402       }
1403     }
1404
1405     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1406     Flag = Chain.getValue(1);
1407   }
1408
1409   // The x86-64 ABI for returning structs by value requires that we copy
1410   // the sret argument into %rax for the return. We saved the argument into
1411   // a virtual register in the entry block, so now we copy the value out
1412   // and into %rax.
1413   if (Subtarget->is64Bit() &&
1414       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1415     MachineFunction &MF = DAG.getMachineFunction();
1416     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1417     unsigned Reg = FuncInfo->getSRetReturnReg();
1418     assert(Reg &&
1419            "SRetReturnReg should have been set in LowerFormalArguments().");
1420     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1421
1422     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1423     Flag = Chain.getValue(1);
1424
1425     // RAX now acts like a return value.
1426     MRI.addLiveOut(X86::RAX);
1427   }
1428
1429   RetOps[0] = Chain;  // Update chain.
1430
1431   // Add the flag if we have it.
1432   if (Flag.getNode())
1433     RetOps.push_back(Flag);
1434
1435   return DAG.getNode(X86ISD::RET_FLAG, dl,
1436                      MVT::Other, &RetOps[0], RetOps.size());
1437 }
1438
1439 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1440   if (N->getNumValues() != 1)
1441     return false;
1442   if (!N->hasNUsesOfValue(1, 0))
1443     return false;
1444
1445   SDNode *Copy = *N->use_begin();
1446   if (Copy->getOpcode() != ISD::CopyToReg &&
1447       Copy->getOpcode() != ISD::FP_EXTEND)
1448     return false;
1449
1450   bool HasRet = false;
1451   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1452        UI != UE; ++UI) {
1453     if (UI->getOpcode() != X86ISD::RET_FLAG)
1454       return false;
1455     HasRet = true;
1456   }
1457
1458   return HasRet;
1459 }
1460
1461 EVT
1462 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1463                                             ISD::NodeType ExtendKind) const {
1464   MVT ReturnMVT;
1465   // TODO: Is this also valid on 32-bit?
1466   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1467     ReturnMVT = MVT::i8;
1468   else
1469     ReturnMVT = MVT::i32;
1470
1471   EVT MinVT = getRegisterType(Context, ReturnMVT);
1472   return VT.bitsLT(MinVT) ? MinVT : VT;
1473 }
1474
1475 /// LowerCallResult - Lower the result values of a call into the
1476 /// appropriate copies out of appropriate physical registers.
1477 ///
1478 SDValue
1479 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1480                                    CallingConv::ID CallConv, bool isVarArg,
1481                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1482                                    DebugLoc dl, SelectionDAG &DAG,
1483                                    SmallVectorImpl<SDValue> &InVals) const {
1484
1485   // Assign locations to each value returned by this call.
1486   SmallVector<CCValAssign, 16> RVLocs;
1487   bool Is64Bit = Subtarget->is64Bit();
1488   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1489                  RVLocs, *DAG.getContext());
1490   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1491
1492   // Copy all of the result registers out of their specified physreg.
1493   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1494     CCValAssign &VA = RVLocs[i];
1495     EVT CopyVT = VA.getValVT();
1496
1497     // If this is x86-64, and we disabled SSE, we can't return FP values
1498     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1499         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1500       report_fatal_error("SSE register return with SSE disabled");
1501     }
1502
1503     SDValue Val;
1504
1505     // If this is a call to a function that returns an fp value on the floating
1506     // point stack, we must guarantee the the value is popped from the stack, so
1507     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1508     // if the return value is not used. We use the FpGET_ST0 instructions
1509     // instead.
1510     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1511       // If we prefer to use the value in xmm registers, copy it out as f80 and
1512       // use a truncate to move it from fp stack reg to xmm reg.
1513       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1514       bool isST0 = VA.getLocReg() == X86::ST0;
1515       unsigned Opc = 0;
1516       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1517       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1518       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1519       SDValue Ops[] = { Chain, InFlag };
1520       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1521                                          Ops, 2), 1);
1522       Val = Chain.getValue(0);
1523
1524       // Round the f80 to the right size, which also moves it to the appropriate
1525       // xmm register.
1526       if (CopyVT != VA.getValVT())
1527         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1528                           // This truncation won't change the value.
1529                           DAG.getIntPtrConstant(1));
1530     } else {
1531       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1532                                  CopyVT, InFlag).getValue(1);
1533       Val = Chain.getValue(0);
1534     }
1535     InFlag = Chain.getValue(2);
1536     InVals.push_back(Val);
1537   }
1538
1539   return Chain;
1540 }
1541
1542
1543 //===----------------------------------------------------------------------===//
1544 //                C & StdCall & Fast Calling Convention implementation
1545 //===----------------------------------------------------------------------===//
1546 //  StdCall calling convention seems to be standard for many Windows' API
1547 //  routines and around. It differs from C calling convention just a little:
1548 //  callee should clean up the stack, not caller. Symbols should be also
1549 //  decorated in some fancy way :) It doesn't support any vector arguments.
1550 //  For info on fast calling convention see Fast Calling Convention (tail call)
1551 //  implementation LowerX86_32FastCCCallTo.
1552
1553 /// CallIsStructReturn - Determines whether a call uses struct return
1554 /// semantics.
1555 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1556   if (Outs.empty())
1557     return false;
1558
1559   return Outs[0].Flags.isSRet();
1560 }
1561
1562 /// ArgsAreStructReturn - Determines whether a function uses struct
1563 /// return semantics.
1564 static bool
1565 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1566   if (Ins.empty())
1567     return false;
1568
1569   return Ins[0].Flags.isSRet();
1570 }
1571
1572 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1573 /// by "Src" to address "Dst" with size and alignment information specified by
1574 /// the specific parameter attribute. The copy will be passed as a byval
1575 /// function parameter.
1576 static SDValue
1577 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1578                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1579                           DebugLoc dl) {
1580   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1581
1582   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1583                        /*isVolatile*/false, /*AlwaysInline=*/true,
1584                        MachinePointerInfo(), MachinePointerInfo());
1585 }
1586
1587 /// IsTailCallConvention - Return true if the calling convention is one that
1588 /// supports tail call optimization.
1589 static bool IsTailCallConvention(CallingConv::ID CC) {
1590   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1591 }
1592
1593 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1594   if (!CI->isTailCall())
1595     return false;
1596
1597   CallSite CS(CI);
1598   CallingConv::ID CalleeCC = CS.getCallingConv();
1599   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1600     return false;
1601
1602   return true;
1603 }
1604
1605 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1606 /// a tailcall target by changing its ABI.
1607 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1608   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1609 }
1610
1611 SDValue
1612 X86TargetLowering::LowerMemArgument(SDValue Chain,
1613                                     CallingConv::ID CallConv,
1614                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1615                                     DebugLoc dl, SelectionDAG &DAG,
1616                                     const CCValAssign &VA,
1617                                     MachineFrameInfo *MFI,
1618                                     unsigned i) const {
1619   // Create the nodes corresponding to a load from this parameter slot.
1620   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1621   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1622   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1623   EVT ValVT;
1624
1625   // If value is passed by pointer we have address passed instead of the value
1626   // itself.
1627   if (VA.getLocInfo() == CCValAssign::Indirect)
1628     ValVT = VA.getLocVT();
1629   else
1630     ValVT = VA.getValVT();
1631
1632   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1633   // changed with more analysis.
1634   // In case of tail call optimization mark all arguments mutable. Since they
1635   // could be overwritten by lowering of arguments in case of a tail call.
1636   if (Flags.isByVal()) {
1637     unsigned Bytes = Flags.getByValSize();
1638     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1639     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1640     return DAG.getFrameIndex(FI, getPointerTy());
1641   } else {
1642     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1643                                     VA.getLocMemOffset(), isImmutable);
1644     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1645     return DAG.getLoad(ValVT, dl, Chain, FIN,
1646                        MachinePointerInfo::getFixedStack(FI),
1647                        false, false, 0);
1648   }
1649 }
1650
1651 SDValue
1652 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1653                                         CallingConv::ID CallConv,
1654                                         bool isVarArg,
1655                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1656                                         DebugLoc dl,
1657                                         SelectionDAG &DAG,
1658                                         SmallVectorImpl<SDValue> &InVals)
1659                                           const {
1660   MachineFunction &MF = DAG.getMachineFunction();
1661   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1662
1663   const Function* Fn = MF.getFunction();
1664   if (Fn->hasExternalLinkage() &&
1665       Subtarget->isTargetCygMing() &&
1666       Fn->getName() == "main")
1667     FuncInfo->setForceFramePointer(true);
1668
1669   MachineFrameInfo *MFI = MF.getFrameInfo();
1670   bool Is64Bit = Subtarget->is64Bit();
1671   bool IsWin64 = Subtarget->isTargetWin64();
1672
1673   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1674          "Var args not supported with calling convention fastcc or ghc");
1675
1676   // Assign locations to all of the incoming arguments.
1677   SmallVector<CCValAssign, 16> ArgLocs;
1678   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1679                  ArgLocs, *DAG.getContext());
1680
1681   // Allocate shadow area for Win64
1682   if (IsWin64) {
1683     CCInfo.AllocateStack(32, 8);
1684   }
1685
1686   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1687
1688   unsigned LastVal = ~0U;
1689   SDValue ArgValue;
1690   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1691     CCValAssign &VA = ArgLocs[i];
1692     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1693     // places.
1694     assert(VA.getValNo() != LastVal &&
1695            "Don't support value assigned to multiple locs yet");
1696     LastVal = VA.getValNo();
1697
1698     if (VA.isRegLoc()) {
1699       EVT RegVT = VA.getLocVT();
1700       TargetRegisterClass *RC = NULL;
1701       if (RegVT == MVT::i32)
1702         RC = X86::GR32RegisterClass;
1703       else if (Is64Bit && RegVT == MVT::i64)
1704         RC = X86::GR64RegisterClass;
1705       else if (RegVT == MVT::f32)
1706         RC = X86::FR32RegisterClass;
1707       else if (RegVT == MVT::f64)
1708         RC = X86::FR64RegisterClass;
1709       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1710         RC = X86::VR256RegisterClass;
1711       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1712         RC = X86::VR128RegisterClass;
1713       else if (RegVT == MVT::x86mmx)
1714         RC = X86::VR64RegisterClass;
1715       else
1716         llvm_unreachable("Unknown argument type!");
1717
1718       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1719       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1720
1721       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1722       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1723       // right size.
1724       if (VA.getLocInfo() == CCValAssign::SExt)
1725         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1726                                DAG.getValueType(VA.getValVT()));
1727       else if (VA.getLocInfo() == CCValAssign::ZExt)
1728         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1729                                DAG.getValueType(VA.getValVT()));
1730       else if (VA.getLocInfo() == CCValAssign::BCvt)
1731         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1732
1733       if (VA.isExtInLoc()) {
1734         // Handle MMX values passed in XMM regs.
1735         if (RegVT.isVector()) {
1736           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1737                                  ArgValue);
1738         } else
1739           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1740       }
1741     } else {
1742       assert(VA.isMemLoc());
1743       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1744     }
1745
1746     // If value is passed via pointer - do a load.
1747     if (VA.getLocInfo() == CCValAssign::Indirect)
1748       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1749                              MachinePointerInfo(), false, false, 0);
1750
1751     InVals.push_back(ArgValue);
1752   }
1753
1754   // The x86-64 ABI for returning structs by value requires that we copy
1755   // the sret argument into %rax for the return. Save the argument into
1756   // a virtual register so that we can access it from the return points.
1757   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1758     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1759     unsigned Reg = FuncInfo->getSRetReturnReg();
1760     if (!Reg) {
1761       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1762       FuncInfo->setSRetReturnReg(Reg);
1763     }
1764     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1765     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1766   }
1767
1768   unsigned StackSize = CCInfo.getNextStackOffset();
1769   // Align stack specially for tail calls.
1770   if (FuncIsMadeTailCallSafe(CallConv))
1771     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1772
1773   // If the function takes variable number of arguments, make a frame index for
1774   // the start of the first vararg value... for expansion of llvm.va_start.
1775   if (isVarArg) {
1776     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1777                     CallConv != CallingConv::X86_ThisCall)) {
1778       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1779     }
1780     if (Is64Bit) {
1781       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1782
1783       // FIXME: We should really autogenerate these arrays
1784       static const unsigned GPR64ArgRegsWin64[] = {
1785         X86::RCX, X86::RDX, X86::R8,  X86::R9
1786       };
1787       static const unsigned GPR64ArgRegs64Bit[] = {
1788         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1789       };
1790       static const unsigned XMMArgRegs64Bit[] = {
1791         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1792         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1793       };
1794       const unsigned *GPR64ArgRegs;
1795       unsigned NumXMMRegs = 0;
1796
1797       if (IsWin64) {
1798         // The XMM registers which might contain var arg parameters are shadowed
1799         // in their paired GPR.  So we only need to save the GPR to their home
1800         // slots.
1801         TotalNumIntRegs = 4;
1802         GPR64ArgRegs = GPR64ArgRegsWin64;
1803       } else {
1804         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1805         GPR64ArgRegs = GPR64ArgRegs64Bit;
1806
1807         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1808       }
1809       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1810                                                        TotalNumIntRegs);
1811
1812       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1813       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1814              "SSE register cannot be used when SSE is disabled!");
1815       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1816              "SSE register cannot be used when SSE is disabled!");
1817       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1818         // Kernel mode asks for SSE to be disabled, so don't push them
1819         // on the stack.
1820         TotalNumXMMRegs = 0;
1821
1822       if (IsWin64) {
1823         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1824         // Get to the caller-allocated home save location.  Add 8 to account
1825         // for the return address.
1826         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1827         FuncInfo->setRegSaveFrameIndex(
1828           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1829         // Fixup to set vararg frame on shadow area (4 x i64).
1830         if (NumIntRegs < 4)
1831           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1832       } else {
1833         // For X86-64, if there are vararg parameters that are passed via
1834         // registers, then we must store them to their spots on the stack so they
1835         // may be loaded by deferencing the result of va_next.
1836         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1837         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1838         FuncInfo->setRegSaveFrameIndex(
1839           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1840                                false));
1841       }
1842
1843       // Store the integer parameter registers.
1844       SmallVector<SDValue, 8> MemOps;
1845       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1846                                         getPointerTy());
1847       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1848       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1849         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1850                                   DAG.getIntPtrConstant(Offset));
1851         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1852                                      X86::GR64RegisterClass);
1853         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1854         SDValue Store =
1855           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1856                        MachinePointerInfo::getFixedStack(
1857                          FuncInfo->getRegSaveFrameIndex(), Offset),
1858                        false, false, 0);
1859         MemOps.push_back(Store);
1860         Offset += 8;
1861       }
1862
1863       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1864         // Now store the XMM (fp + vector) parameter registers.
1865         SmallVector<SDValue, 11> SaveXMMOps;
1866         SaveXMMOps.push_back(Chain);
1867
1868         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1869         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1870         SaveXMMOps.push_back(ALVal);
1871
1872         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1873                                FuncInfo->getRegSaveFrameIndex()));
1874         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1875                                FuncInfo->getVarArgsFPOffset()));
1876
1877         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1878           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1879                                        X86::VR128RegisterClass);
1880           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1881           SaveXMMOps.push_back(Val);
1882         }
1883         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1884                                      MVT::Other,
1885                                      &SaveXMMOps[0], SaveXMMOps.size()));
1886       }
1887
1888       if (!MemOps.empty())
1889         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1890                             &MemOps[0], MemOps.size());
1891     }
1892   }
1893
1894   // Some CCs need callee pop.
1895   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1896     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1897   } else {
1898     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1899     // If this is an sret function, the return should pop the hidden pointer.
1900     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1901       FuncInfo->setBytesToPopOnReturn(4);
1902   }
1903
1904   if (!Is64Bit) {
1905     // RegSaveFrameIndex is X86-64 only.
1906     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1907     if (CallConv == CallingConv::X86_FastCall ||
1908         CallConv == CallingConv::X86_ThisCall)
1909       // fastcc functions can't have varargs.
1910       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1911   }
1912
1913   return Chain;
1914 }
1915
1916 SDValue
1917 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1918                                     SDValue StackPtr, SDValue Arg,
1919                                     DebugLoc dl, SelectionDAG &DAG,
1920                                     const CCValAssign &VA,
1921                                     ISD::ArgFlagsTy Flags) const {
1922   unsigned LocMemOffset = VA.getLocMemOffset();
1923   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1924   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1925   if (Flags.isByVal())
1926     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1927
1928   return DAG.getStore(Chain, dl, Arg, PtrOff,
1929                       MachinePointerInfo::getStack(LocMemOffset),
1930                       false, false, 0);
1931 }
1932
1933 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1934 /// optimization is performed and it is required.
1935 SDValue
1936 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1937                                            SDValue &OutRetAddr, SDValue Chain,
1938                                            bool IsTailCall, bool Is64Bit,
1939                                            int FPDiff, DebugLoc dl) const {
1940   // Adjust the Return address stack slot.
1941   EVT VT = getPointerTy();
1942   OutRetAddr = getReturnAddressFrameIndex(DAG);
1943
1944   // Load the "old" Return address.
1945   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1946                            false, false, 0);
1947   return SDValue(OutRetAddr.getNode(), 1);
1948 }
1949
1950 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1951 /// optimization is performed and it is required (FPDiff!=0).
1952 static SDValue
1953 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1954                          SDValue Chain, SDValue RetAddrFrIdx,
1955                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1956   // Store the return address to the appropriate stack slot.
1957   if (!FPDiff) return Chain;
1958   // Calculate the new stack slot for the return address.
1959   int SlotSize = Is64Bit ? 8 : 4;
1960   int NewReturnAddrFI =
1961     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1962   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1963   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1964   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1965                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1966                        false, false, 0);
1967   return Chain;
1968 }
1969
1970 SDValue
1971 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1972                              CallingConv::ID CallConv, bool isVarArg,
1973                              bool &isTailCall,
1974                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1975                              const SmallVectorImpl<SDValue> &OutVals,
1976                              const SmallVectorImpl<ISD::InputArg> &Ins,
1977                              DebugLoc dl, SelectionDAG &DAG,
1978                              SmallVectorImpl<SDValue> &InVals) const {
1979   MachineFunction &MF = DAG.getMachineFunction();
1980   bool Is64Bit        = Subtarget->is64Bit();
1981   bool IsWin64        = Subtarget->isTargetWin64();
1982   bool IsStructRet    = CallIsStructReturn(Outs);
1983   bool IsSibcall      = false;
1984
1985   if (isTailCall) {
1986     // Check if it's really possible to do a tail call.
1987     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1988                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1989                                                    Outs, OutVals, Ins, DAG);
1990
1991     // Sibcalls are automatically detected tailcalls which do not require
1992     // ABI changes.
1993     if (!GuaranteedTailCallOpt && isTailCall)
1994       IsSibcall = true;
1995
1996     if (isTailCall)
1997       ++NumTailCalls;
1998   }
1999
2000   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2001          "Var args not supported with calling convention fastcc or ghc");
2002
2003   // Analyze operands of the call, assigning locations to each operand.
2004   SmallVector<CCValAssign, 16> ArgLocs;
2005   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2006                  ArgLocs, *DAG.getContext());
2007
2008   // Allocate shadow area for Win64
2009   if (IsWin64) {
2010     CCInfo.AllocateStack(32, 8);
2011   }
2012
2013   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2014
2015   // Get a count of how many bytes are to be pushed on the stack.
2016   unsigned NumBytes = CCInfo.getNextStackOffset();
2017   if (IsSibcall)
2018     // This is a sibcall. The memory operands are available in caller's
2019     // own caller's stack.
2020     NumBytes = 0;
2021   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2022     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2023
2024   int FPDiff = 0;
2025   if (isTailCall && !IsSibcall) {
2026     // Lower arguments at fp - stackoffset + fpdiff.
2027     unsigned NumBytesCallerPushed =
2028       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2029     FPDiff = NumBytesCallerPushed - NumBytes;
2030
2031     // Set the delta of movement of the returnaddr stackslot.
2032     // But only set if delta is greater than previous delta.
2033     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2034       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2035   }
2036
2037   if (!IsSibcall)
2038     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2039
2040   SDValue RetAddrFrIdx;
2041   // Load return address for tail calls.
2042   if (isTailCall && FPDiff)
2043     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2044                                     Is64Bit, FPDiff, dl);
2045
2046   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2047   SmallVector<SDValue, 8> MemOpChains;
2048   SDValue StackPtr;
2049
2050   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2051   // of tail call optimization arguments are handle later.
2052   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2053     CCValAssign &VA = ArgLocs[i];
2054     EVT RegVT = VA.getLocVT();
2055     SDValue Arg = OutVals[i];
2056     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2057     bool isByVal = Flags.isByVal();
2058
2059     // Promote the value if needed.
2060     switch (VA.getLocInfo()) {
2061     default: llvm_unreachable("Unknown loc info!");
2062     case CCValAssign::Full: break;
2063     case CCValAssign::SExt:
2064       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2065       break;
2066     case CCValAssign::ZExt:
2067       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2068       break;
2069     case CCValAssign::AExt:
2070       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2071         // Special case: passing MMX values in XMM registers.
2072         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2073         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2074         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2075       } else
2076         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2077       break;
2078     case CCValAssign::BCvt:
2079       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2080       break;
2081     case CCValAssign::Indirect: {
2082       // Store the argument.
2083       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2084       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2085       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2086                            MachinePointerInfo::getFixedStack(FI),
2087                            false, false, 0);
2088       Arg = SpillSlot;
2089       break;
2090     }
2091     }
2092
2093     if (VA.isRegLoc()) {
2094       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2095       if (isVarArg && IsWin64) {
2096         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2097         // shadow reg if callee is a varargs function.
2098         unsigned ShadowReg = 0;
2099         switch (VA.getLocReg()) {
2100         case X86::XMM0: ShadowReg = X86::RCX; break;
2101         case X86::XMM1: ShadowReg = X86::RDX; break;
2102         case X86::XMM2: ShadowReg = X86::R8; break;
2103         case X86::XMM3: ShadowReg = X86::R9; break;
2104         }
2105         if (ShadowReg)
2106           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2107       }
2108     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2109       assert(VA.isMemLoc());
2110       if (StackPtr.getNode() == 0)
2111         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2112       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2113                                              dl, DAG, VA, Flags));
2114     }
2115   }
2116
2117   if (!MemOpChains.empty())
2118     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2119                         &MemOpChains[0], MemOpChains.size());
2120
2121   // Build a sequence of copy-to-reg nodes chained together with token chain
2122   // and flag operands which copy the outgoing args into registers.
2123   SDValue InFlag;
2124   // Tail call byval lowering might overwrite argument registers so in case of
2125   // tail call optimization the copies to registers are lowered later.
2126   if (!isTailCall)
2127     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2128       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2129                                RegsToPass[i].second, InFlag);
2130       InFlag = Chain.getValue(1);
2131     }
2132
2133   if (Subtarget->isPICStyleGOT()) {
2134     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2135     // GOT pointer.
2136     if (!isTailCall) {
2137       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2138                                DAG.getNode(X86ISD::GlobalBaseReg,
2139                                            DebugLoc(), getPointerTy()),
2140                                InFlag);
2141       InFlag = Chain.getValue(1);
2142     } else {
2143       // If we are tail calling and generating PIC/GOT style code load the
2144       // address of the callee into ECX. The value in ecx is used as target of
2145       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2146       // for tail calls on PIC/GOT architectures. Normally we would just put the
2147       // address of GOT into ebx and then call target@PLT. But for tail calls
2148       // ebx would be restored (since ebx is callee saved) before jumping to the
2149       // target@PLT.
2150
2151       // Note: The actual moving to ECX is done further down.
2152       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2153       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2154           !G->getGlobal()->hasProtectedVisibility())
2155         Callee = LowerGlobalAddress(Callee, DAG);
2156       else if (isa<ExternalSymbolSDNode>(Callee))
2157         Callee = LowerExternalSymbol(Callee, DAG);
2158     }
2159   }
2160
2161   if (Is64Bit && isVarArg && !IsWin64) {
2162     // From AMD64 ABI document:
2163     // For calls that may call functions that use varargs or stdargs
2164     // (prototype-less calls or calls to functions containing ellipsis (...) in
2165     // the declaration) %al is used as hidden argument to specify the number
2166     // of SSE registers used. The contents of %al do not need to match exactly
2167     // the number of registers, but must be an ubound on the number of SSE
2168     // registers used and is in the range 0 - 8 inclusive.
2169
2170     // Count the number of XMM registers allocated.
2171     static const unsigned XMMArgRegs[] = {
2172       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2173       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2174     };
2175     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2176     assert((Subtarget->hasXMM() || !NumXMMRegs)
2177            && "SSE registers cannot be used when SSE is disabled");
2178
2179     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2180                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2181     InFlag = Chain.getValue(1);
2182   }
2183
2184
2185   // For tail calls lower the arguments to the 'real' stack slot.
2186   if (isTailCall) {
2187     // Force all the incoming stack arguments to be loaded from the stack
2188     // before any new outgoing arguments are stored to the stack, because the
2189     // outgoing stack slots may alias the incoming argument stack slots, and
2190     // the alias isn't otherwise explicit. This is slightly more conservative
2191     // than necessary, because it means that each store effectively depends
2192     // on every argument instead of just those arguments it would clobber.
2193     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2194
2195     SmallVector<SDValue, 8> MemOpChains2;
2196     SDValue FIN;
2197     int FI = 0;
2198     // Do not flag preceding copytoreg stuff together with the following stuff.
2199     InFlag = SDValue();
2200     if (GuaranteedTailCallOpt) {
2201       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2202         CCValAssign &VA = ArgLocs[i];
2203         if (VA.isRegLoc())
2204           continue;
2205         assert(VA.isMemLoc());
2206         SDValue Arg = OutVals[i];
2207         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2208         // Create frame index.
2209         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2210         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2211         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2212         FIN = DAG.getFrameIndex(FI, getPointerTy());
2213
2214         if (Flags.isByVal()) {
2215           // Copy relative to framepointer.
2216           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2217           if (StackPtr.getNode() == 0)
2218             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2219                                           getPointerTy());
2220           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2221
2222           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2223                                                            ArgChain,
2224                                                            Flags, DAG, dl));
2225         } else {
2226           // Store relative to framepointer.
2227           MemOpChains2.push_back(
2228             DAG.getStore(ArgChain, dl, Arg, FIN,
2229                          MachinePointerInfo::getFixedStack(FI),
2230                          false, false, 0));
2231         }
2232       }
2233     }
2234
2235     if (!MemOpChains2.empty())
2236       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2237                           &MemOpChains2[0], MemOpChains2.size());
2238
2239     // Copy arguments to their registers.
2240     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2241       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2242                                RegsToPass[i].second, InFlag);
2243       InFlag = Chain.getValue(1);
2244     }
2245     InFlag =SDValue();
2246
2247     // Store the return address to the appropriate stack slot.
2248     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2249                                      FPDiff, dl);
2250   }
2251
2252   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2253     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2254     // In the 64-bit large code model, we have to make all calls
2255     // through a register, since the call instruction's 32-bit
2256     // pc-relative offset may not be large enough to hold the whole
2257     // address.
2258   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2259     // If the callee is a GlobalAddress node (quite common, every direct call
2260     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2261     // it.
2262
2263     // We should use extra load for direct calls to dllimported functions in
2264     // non-JIT mode.
2265     const GlobalValue *GV = G->getGlobal();
2266     if (!GV->hasDLLImportLinkage()) {
2267       unsigned char OpFlags = 0;
2268
2269       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2270       // external symbols most go through the PLT in PIC mode.  If the symbol
2271       // has hidden or protected visibility, or if it is static or local, then
2272       // we don't need to use the PLT - we can directly call it.
2273       if (Subtarget->isTargetELF() &&
2274           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2275           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2276         OpFlags = X86II::MO_PLT;
2277       } else if (Subtarget->isPICStyleStubAny() &&
2278                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2279                  (!Subtarget->getTargetTriple().isMacOSX() ||
2280                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2281         // PC-relative references to external symbols should go through $stub,
2282         // unless we're building with the leopard linker or later, which
2283         // automatically synthesizes these stubs.
2284         OpFlags = X86II::MO_DARWIN_STUB;
2285       }
2286
2287       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2288                                           G->getOffset(), OpFlags);
2289     }
2290   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2291     unsigned char OpFlags = 0;
2292
2293     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2294     // external symbols should go through the PLT.
2295     if (Subtarget->isTargetELF() &&
2296         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2297       OpFlags = X86II::MO_PLT;
2298     } else if (Subtarget->isPICStyleStubAny() &&
2299                (!Subtarget->getTargetTriple().isMacOSX() ||
2300                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2301       // PC-relative references to external symbols should go through $stub,
2302       // unless we're building with the leopard linker or later, which
2303       // automatically synthesizes these stubs.
2304       OpFlags = X86II::MO_DARWIN_STUB;
2305     }
2306
2307     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2308                                          OpFlags);
2309   }
2310
2311   // Returns a chain & a flag for retval copy to use.
2312   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2313   SmallVector<SDValue, 8> Ops;
2314
2315   if (!IsSibcall && isTailCall) {
2316     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2317                            DAG.getIntPtrConstant(0, true), InFlag);
2318     InFlag = Chain.getValue(1);
2319   }
2320
2321   Ops.push_back(Chain);
2322   Ops.push_back(Callee);
2323
2324   if (isTailCall)
2325     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2326
2327   // Add argument registers to the end of the list so that they are known live
2328   // into the call.
2329   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2330     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2331                                   RegsToPass[i].second.getValueType()));
2332
2333   // Add an implicit use GOT pointer in EBX.
2334   if (!isTailCall && Subtarget->isPICStyleGOT())
2335     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2336
2337   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2338   if (Is64Bit && isVarArg && !IsWin64)
2339     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2340
2341   if (InFlag.getNode())
2342     Ops.push_back(InFlag);
2343
2344   if (isTailCall) {
2345     // We used to do:
2346     //// If this is the first return lowered for this function, add the regs
2347     //// to the liveout set for the function.
2348     // This isn't right, although it's probably harmless on x86; liveouts
2349     // should be computed from returns not tail calls.  Consider a void
2350     // function making a tail call to a function returning int.
2351     return DAG.getNode(X86ISD::TC_RETURN, dl,
2352                        NodeTys, &Ops[0], Ops.size());
2353   }
2354
2355   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2356   InFlag = Chain.getValue(1);
2357
2358   // Create the CALLSEQ_END node.
2359   unsigned NumBytesForCalleeToPush;
2360   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2361     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2362   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2363     // If this is a call to a struct-return function, the callee
2364     // pops the hidden struct pointer, so we have to push it back.
2365     // This is common for Darwin/X86, Linux & Mingw32 targets.
2366     NumBytesForCalleeToPush = 4;
2367   else
2368     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2369
2370   // Returns a flag for retval copy to use.
2371   if (!IsSibcall) {
2372     Chain = DAG.getCALLSEQ_END(Chain,
2373                                DAG.getIntPtrConstant(NumBytes, true),
2374                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2375                                                      true),
2376                                InFlag);
2377     InFlag = Chain.getValue(1);
2378   }
2379
2380   // Handle result values, copying them out of physregs into vregs that we
2381   // return.
2382   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2383                          Ins, dl, DAG, InVals);
2384 }
2385
2386
2387 //===----------------------------------------------------------------------===//
2388 //                Fast Calling Convention (tail call) implementation
2389 //===----------------------------------------------------------------------===//
2390
2391 //  Like std call, callee cleans arguments, convention except that ECX is
2392 //  reserved for storing the tail called function address. Only 2 registers are
2393 //  free for argument passing (inreg). Tail call optimization is performed
2394 //  provided:
2395 //                * tailcallopt is enabled
2396 //                * caller/callee are fastcc
2397 //  On X86_64 architecture with GOT-style position independent code only local
2398 //  (within module) calls are supported at the moment.
2399 //  To keep the stack aligned according to platform abi the function
2400 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2401 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2402 //  If a tail called function callee has more arguments than the caller the
2403 //  caller needs to make sure that there is room to move the RETADDR to. This is
2404 //  achieved by reserving an area the size of the argument delta right after the
2405 //  original REtADDR, but before the saved framepointer or the spilled registers
2406 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2407 //  stack layout:
2408 //    arg1
2409 //    arg2
2410 //    RETADDR
2411 //    [ new RETADDR
2412 //      move area ]
2413 //    (possible EBP)
2414 //    ESI
2415 //    EDI
2416 //    local1 ..
2417
2418 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2419 /// for a 16 byte align requirement.
2420 unsigned
2421 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2422                                                SelectionDAG& DAG) const {
2423   MachineFunction &MF = DAG.getMachineFunction();
2424   const TargetMachine &TM = MF.getTarget();
2425   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2426   unsigned StackAlignment = TFI.getStackAlignment();
2427   uint64_t AlignMask = StackAlignment - 1;
2428   int64_t Offset = StackSize;
2429   uint64_t SlotSize = TD->getPointerSize();
2430   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2431     // Number smaller than 12 so just add the difference.
2432     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2433   } else {
2434     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2435     Offset = ((~AlignMask) & Offset) + StackAlignment +
2436       (StackAlignment-SlotSize);
2437   }
2438   return Offset;
2439 }
2440
2441 /// MatchingStackOffset - Return true if the given stack call argument is
2442 /// already available in the same position (relatively) of the caller's
2443 /// incoming argument stack.
2444 static
2445 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2446                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2447                          const X86InstrInfo *TII) {
2448   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2449   int FI = INT_MAX;
2450   if (Arg.getOpcode() == ISD::CopyFromReg) {
2451     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2452     if (!TargetRegisterInfo::isVirtualRegister(VR))
2453       return false;
2454     MachineInstr *Def = MRI->getVRegDef(VR);
2455     if (!Def)
2456       return false;
2457     if (!Flags.isByVal()) {
2458       if (!TII->isLoadFromStackSlot(Def, FI))
2459         return false;
2460     } else {
2461       unsigned Opcode = Def->getOpcode();
2462       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2463           Def->getOperand(1).isFI()) {
2464         FI = Def->getOperand(1).getIndex();
2465         Bytes = Flags.getByValSize();
2466       } else
2467         return false;
2468     }
2469   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2470     if (Flags.isByVal())
2471       // ByVal argument is passed in as a pointer but it's now being
2472       // dereferenced. e.g.
2473       // define @foo(%struct.X* %A) {
2474       //   tail call @bar(%struct.X* byval %A)
2475       // }
2476       return false;
2477     SDValue Ptr = Ld->getBasePtr();
2478     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2479     if (!FINode)
2480       return false;
2481     FI = FINode->getIndex();
2482   } else
2483     return false;
2484
2485   assert(FI != INT_MAX);
2486   if (!MFI->isFixedObjectIndex(FI))
2487     return false;
2488   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2489 }
2490
2491 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2492 /// for tail call optimization. Targets which want to do tail call
2493 /// optimization should implement this function.
2494 bool
2495 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2496                                                      CallingConv::ID CalleeCC,
2497                                                      bool isVarArg,
2498                                                      bool isCalleeStructRet,
2499                                                      bool isCallerStructRet,
2500                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2501                                     const SmallVectorImpl<SDValue> &OutVals,
2502                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2503                                                      SelectionDAG& DAG) const {
2504   if (!IsTailCallConvention(CalleeCC) &&
2505       CalleeCC != CallingConv::C)
2506     return false;
2507
2508   // If -tailcallopt is specified, make fastcc functions tail-callable.
2509   const MachineFunction &MF = DAG.getMachineFunction();
2510   const Function *CallerF = DAG.getMachineFunction().getFunction();
2511   CallingConv::ID CallerCC = CallerF->getCallingConv();
2512   bool CCMatch = CallerCC == CalleeCC;
2513
2514   if (GuaranteedTailCallOpt) {
2515     if (IsTailCallConvention(CalleeCC) && CCMatch)
2516       return true;
2517     return false;
2518   }
2519
2520   // Look for obvious safe cases to perform tail call optimization that do not
2521   // require ABI changes. This is what gcc calls sibcall.
2522
2523   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2524   // emit a special epilogue.
2525   if (RegInfo->needsStackRealignment(MF))
2526     return false;
2527
2528   // Do not sibcall optimize vararg calls unless the call site is not passing
2529   // any arguments.
2530   if (isVarArg && !Outs.empty())
2531     return false;
2532
2533   // Also avoid sibcall optimization if either caller or callee uses struct
2534   // return semantics.
2535   if (isCalleeStructRet || isCallerStructRet)
2536     return false;
2537
2538   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2539   // Therefore if it's not used by the call it is not safe to optimize this into
2540   // a sibcall.
2541   bool Unused = false;
2542   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2543     if (!Ins[i].Used) {
2544       Unused = true;
2545       break;
2546     }
2547   }
2548   if (Unused) {
2549     SmallVector<CCValAssign, 16> RVLocs;
2550     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2551                    RVLocs, *DAG.getContext());
2552     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2553     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2554       CCValAssign &VA = RVLocs[i];
2555       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2556         return false;
2557     }
2558   }
2559
2560   // If the calling conventions do not match, then we'd better make sure the
2561   // results are returned in the same way as what the caller expects.
2562   if (!CCMatch) {
2563     SmallVector<CCValAssign, 16> RVLocs1;
2564     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2565                     RVLocs1, *DAG.getContext());
2566     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2567
2568     SmallVector<CCValAssign, 16> RVLocs2;
2569     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2570                     RVLocs2, *DAG.getContext());
2571     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2572
2573     if (RVLocs1.size() != RVLocs2.size())
2574       return false;
2575     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2576       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2577         return false;
2578       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2579         return false;
2580       if (RVLocs1[i].isRegLoc()) {
2581         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2582           return false;
2583       } else {
2584         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2585           return false;
2586       }
2587     }
2588   }
2589
2590   // If the callee takes no arguments then go on to check the results of the
2591   // call.
2592   if (!Outs.empty()) {
2593     // Check if stack adjustment is needed. For now, do not do this if any
2594     // argument is passed on the stack.
2595     SmallVector<CCValAssign, 16> ArgLocs;
2596     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2597                    ArgLocs, *DAG.getContext());
2598
2599     // Allocate shadow area for Win64
2600     if (Subtarget->isTargetWin64()) {
2601       CCInfo.AllocateStack(32, 8);
2602     }
2603
2604     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2605     if (CCInfo.getNextStackOffset()) {
2606       MachineFunction &MF = DAG.getMachineFunction();
2607       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2608         return false;
2609
2610       // Check if the arguments are already laid out in the right way as
2611       // the caller's fixed stack objects.
2612       MachineFrameInfo *MFI = MF.getFrameInfo();
2613       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2614       const X86InstrInfo *TII =
2615         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2616       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2617         CCValAssign &VA = ArgLocs[i];
2618         SDValue Arg = OutVals[i];
2619         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2620         if (VA.getLocInfo() == CCValAssign::Indirect)
2621           return false;
2622         if (!VA.isRegLoc()) {
2623           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2624                                    MFI, MRI, TII))
2625             return false;
2626         }
2627       }
2628     }
2629
2630     // If the tailcall address may be in a register, then make sure it's
2631     // possible to register allocate for it. In 32-bit, the call address can
2632     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2633     // callee-saved registers are restored. These happen to be the same
2634     // registers used to pass 'inreg' arguments so watch out for those.
2635     if (!Subtarget->is64Bit() &&
2636         !isa<GlobalAddressSDNode>(Callee) &&
2637         !isa<ExternalSymbolSDNode>(Callee)) {
2638       unsigned NumInRegs = 0;
2639       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2640         CCValAssign &VA = ArgLocs[i];
2641         if (!VA.isRegLoc())
2642           continue;
2643         unsigned Reg = VA.getLocReg();
2644         switch (Reg) {
2645         default: break;
2646         case X86::EAX: case X86::EDX: case X86::ECX:
2647           if (++NumInRegs == 3)
2648             return false;
2649           break;
2650         }
2651       }
2652     }
2653   }
2654
2655   // An stdcall caller is expected to clean up its arguments; the callee
2656   // isn't going to do that.
2657   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2658     return false;
2659
2660   return true;
2661 }
2662
2663 FastISel *
2664 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2665   return X86::createFastISel(funcInfo);
2666 }
2667
2668
2669 //===----------------------------------------------------------------------===//
2670 //                           Other Lowering Hooks
2671 //===----------------------------------------------------------------------===//
2672
2673 static bool MayFoldLoad(SDValue Op) {
2674   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2675 }
2676
2677 static bool MayFoldIntoStore(SDValue Op) {
2678   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2679 }
2680
2681 static bool isTargetShuffle(unsigned Opcode) {
2682   switch(Opcode) {
2683   default: return false;
2684   case X86ISD::PSHUFD:
2685   case X86ISD::PSHUFHW:
2686   case X86ISD::PSHUFLW:
2687   case X86ISD::SHUFPD:
2688   case X86ISD::PALIGN:
2689   case X86ISD::SHUFPS:
2690   case X86ISD::MOVLHPS:
2691   case X86ISD::MOVLHPD:
2692   case X86ISD::MOVHLPS:
2693   case X86ISD::MOVLPS:
2694   case X86ISD::MOVLPD:
2695   case X86ISD::MOVSHDUP:
2696   case X86ISD::MOVSLDUP:
2697   case X86ISD::MOVDDUP:
2698   case X86ISD::MOVSS:
2699   case X86ISD::MOVSD:
2700   case X86ISD::UNPCKLPS:
2701   case X86ISD::UNPCKLPD:
2702   case X86ISD::VUNPCKLPS:
2703   case X86ISD::VUNPCKLPD:
2704   case X86ISD::VUNPCKLPSY:
2705   case X86ISD::VUNPCKLPDY:
2706   case X86ISD::PUNPCKLWD:
2707   case X86ISD::PUNPCKLBW:
2708   case X86ISD::PUNPCKLDQ:
2709   case X86ISD::PUNPCKLQDQ:
2710   case X86ISD::UNPCKHPS:
2711   case X86ISD::UNPCKHPD:
2712   case X86ISD::PUNPCKHWD:
2713   case X86ISD::PUNPCKHBW:
2714   case X86ISD::PUNPCKHDQ:
2715   case X86ISD::PUNPCKHQDQ:
2716     return true;
2717   }
2718   return false;
2719 }
2720
2721 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2722                                                SDValue V1, SelectionDAG &DAG) {
2723   switch(Opc) {
2724   default: llvm_unreachable("Unknown x86 shuffle node");
2725   case X86ISD::MOVSHDUP:
2726   case X86ISD::MOVSLDUP:
2727   case X86ISD::MOVDDUP:
2728     return DAG.getNode(Opc, dl, VT, V1);
2729   }
2730
2731   return SDValue();
2732 }
2733
2734 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2735                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2736   switch(Opc) {
2737   default: llvm_unreachable("Unknown x86 shuffle node");
2738   case X86ISD::PSHUFD:
2739   case X86ISD::PSHUFHW:
2740   case X86ISD::PSHUFLW:
2741     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2742   }
2743
2744   return SDValue();
2745 }
2746
2747 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2748                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2749   switch(Opc) {
2750   default: llvm_unreachable("Unknown x86 shuffle node");
2751   case X86ISD::PALIGN:
2752   case X86ISD::SHUFPD:
2753   case X86ISD::SHUFPS:
2754     return DAG.getNode(Opc, dl, VT, V1, V2,
2755                        DAG.getConstant(TargetMask, MVT::i8));
2756   }
2757   return SDValue();
2758 }
2759
2760 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2761                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2762   switch(Opc) {
2763   default: llvm_unreachable("Unknown x86 shuffle node");
2764   case X86ISD::MOVLHPS:
2765   case X86ISD::MOVLHPD:
2766   case X86ISD::MOVHLPS:
2767   case X86ISD::MOVLPS:
2768   case X86ISD::MOVLPD:
2769   case X86ISD::MOVSS:
2770   case X86ISD::MOVSD:
2771   case X86ISD::UNPCKLPS:
2772   case X86ISD::UNPCKLPD:
2773   case X86ISD::VUNPCKLPS:
2774   case X86ISD::VUNPCKLPD:
2775   case X86ISD::VUNPCKLPSY:
2776   case X86ISD::VUNPCKLPDY:
2777   case X86ISD::PUNPCKLWD:
2778   case X86ISD::PUNPCKLBW:
2779   case X86ISD::PUNPCKLDQ:
2780   case X86ISD::PUNPCKLQDQ:
2781   case X86ISD::UNPCKHPS:
2782   case X86ISD::UNPCKHPD:
2783   case X86ISD::PUNPCKHWD:
2784   case X86ISD::PUNPCKHBW:
2785   case X86ISD::PUNPCKHDQ:
2786   case X86ISD::PUNPCKHQDQ:
2787     return DAG.getNode(Opc, dl, VT, V1, V2);
2788   }
2789   return SDValue();
2790 }
2791
2792 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2793   MachineFunction &MF = DAG.getMachineFunction();
2794   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2795   int ReturnAddrIndex = FuncInfo->getRAIndex();
2796
2797   if (ReturnAddrIndex == 0) {
2798     // Set up a frame object for the return address.
2799     uint64_t SlotSize = TD->getPointerSize();
2800     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2801                                                            false);
2802     FuncInfo->setRAIndex(ReturnAddrIndex);
2803   }
2804
2805   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2806 }
2807
2808
2809 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2810                                        bool hasSymbolicDisplacement) {
2811   // Offset should fit into 32 bit immediate field.
2812   if (!isInt<32>(Offset))
2813     return false;
2814
2815   // If we don't have a symbolic displacement - we don't have any extra
2816   // restrictions.
2817   if (!hasSymbolicDisplacement)
2818     return true;
2819
2820   // FIXME: Some tweaks might be needed for medium code model.
2821   if (M != CodeModel::Small && M != CodeModel::Kernel)
2822     return false;
2823
2824   // For small code model we assume that latest object is 16MB before end of 31
2825   // bits boundary. We may also accept pretty large negative constants knowing
2826   // that all objects are in the positive half of address space.
2827   if (M == CodeModel::Small && Offset < 16*1024*1024)
2828     return true;
2829
2830   // For kernel code model we know that all object resist in the negative half
2831   // of 32bits address space. We may not accept negative offsets, since they may
2832   // be just off and we may accept pretty large positive ones.
2833   if (M == CodeModel::Kernel && Offset > 0)
2834     return true;
2835
2836   return false;
2837 }
2838
2839 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2840 /// specific condition code, returning the condition code and the LHS/RHS of the
2841 /// comparison to make.
2842 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2843                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2844   if (!isFP) {
2845     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2846       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2847         // X > -1   -> X == 0, jump !sign.
2848         RHS = DAG.getConstant(0, RHS.getValueType());
2849         return X86::COND_NS;
2850       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2851         // X < 0   -> X == 0, jump on sign.
2852         return X86::COND_S;
2853       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2854         // X < 1   -> X <= 0
2855         RHS = DAG.getConstant(0, RHS.getValueType());
2856         return X86::COND_LE;
2857       }
2858     }
2859
2860     switch (SetCCOpcode) {
2861     default: llvm_unreachable("Invalid integer condition!");
2862     case ISD::SETEQ:  return X86::COND_E;
2863     case ISD::SETGT:  return X86::COND_G;
2864     case ISD::SETGE:  return X86::COND_GE;
2865     case ISD::SETLT:  return X86::COND_L;
2866     case ISD::SETLE:  return X86::COND_LE;
2867     case ISD::SETNE:  return X86::COND_NE;
2868     case ISD::SETULT: return X86::COND_B;
2869     case ISD::SETUGT: return X86::COND_A;
2870     case ISD::SETULE: return X86::COND_BE;
2871     case ISD::SETUGE: return X86::COND_AE;
2872     }
2873   }
2874
2875   // First determine if it is required or is profitable to flip the operands.
2876
2877   // If LHS is a foldable load, but RHS is not, flip the condition.
2878   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2879       !ISD::isNON_EXTLoad(RHS.getNode())) {
2880     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2881     std::swap(LHS, RHS);
2882   }
2883
2884   switch (SetCCOpcode) {
2885   default: break;
2886   case ISD::SETOLT:
2887   case ISD::SETOLE:
2888   case ISD::SETUGT:
2889   case ISD::SETUGE:
2890     std::swap(LHS, RHS);
2891     break;
2892   }
2893
2894   // On a floating point condition, the flags are set as follows:
2895   // ZF  PF  CF   op
2896   //  0 | 0 | 0 | X > Y
2897   //  0 | 0 | 1 | X < Y
2898   //  1 | 0 | 0 | X == Y
2899   //  1 | 1 | 1 | unordered
2900   switch (SetCCOpcode) {
2901   default: llvm_unreachable("Condcode should be pre-legalized away");
2902   case ISD::SETUEQ:
2903   case ISD::SETEQ:   return X86::COND_E;
2904   case ISD::SETOLT:              // flipped
2905   case ISD::SETOGT:
2906   case ISD::SETGT:   return X86::COND_A;
2907   case ISD::SETOLE:              // flipped
2908   case ISD::SETOGE:
2909   case ISD::SETGE:   return X86::COND_AE;
2910   case ISD::SETUGT:              // flipped
2911   case ISD::SETULT:
2912   case ISD::SETLT:   return X86::COND_B;
2913   case ISD::SETUGE:              // flipped
2914   case ISD::SETULE:
2915   case ISD::SETLE:   return X86::COND_BE;
2916   case ISD::SETONE:
2917   case ISD::SETNE:   return X86::COND_NE;
2918   case ISD::SETUO:   return X86::COND_P;
2919   case ISD::SETO:    return X86::COND_NP;
2920   case ISD::SETOEQ:
2921   case ISD::SETUNE:  return X86::COND_INVALID;
2922   }
2923 }
2924
2925 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2926 /// code. Current x86 isa includes the following FP cmov instructions:
2927 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2928 static bool hasFPCMov(unsigned X86CC) {
2929   switch (X86CC) {
2930   default:
2931     return false;
2932   case X86::COND_B:
2933   case X86::COND_BE:
2934   case X86::COND_E:
2935   case X86::COND_P:
2936   case X86::COND_A:
2937   case X86::COND_AE:
2938   case X86::COND_NE:
2939   case X86::COND_NP:
2940     return true;
2941   }
2942 }
2943
2944 /// isFPImmLegal - Returns true if the target can instruction select the
2945 /// specified FP immediate natively. If false, the legalizer will
2946 /// materialize the FP immediate as a load from a constant pool.
2947 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2948   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2949     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2950       return true;
2951   }
2952   return false;
2953 }
2954
2955 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2956 /// the specified range (L, H].
2957 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2958   return (Val < 0) || (Val >= Low && Val < Hi);
2959 }
2960
2961 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2962 /// specified value.
2963 static bool isUndefOrEqual(int Val, int CmpVal) {
2964   if (Val < 0 || Val == CmpVal)
2965     return true;
2966   return false;
2967 }
2968
2969 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2970 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2971 /// the second operand.
2972 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2973   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2974     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2975   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2976     return (Mask[0] < 2 && Mask[1] < 2);
2977   return false;
2978 }
2979
2980 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2981   SmallVector<int, 8> M;
2982   N->getMask(M);
2983   return ::isPSHUFDMask(M, N->getValueType(0));
2984 }
2985
2986 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2987 /// is suitable for input to PSHUFHW.
2988 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2989   if (VT != MVT::v8i16)
2990     return false;
2991
2992   // Lower quadword copied in order or undef.
2993   for (int i = 0; i != 4; ++i)
2994     if (Mask[i] >= 0 && Mask[i] != i)
2995       return false;
2996
2997   // Upper quadword shuffled.
2998   for (int i = 4; i != 8; ++i)
2999     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3000       return false;
3001
3002   return true;
3003 }
3004
3005 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3006   SmallVector<int, 8> M;
3007   N->getMask(M);
3008   return ::isPSHUFHWMask(M, N->getValueType(0));
3009 }
3010
3011 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3012 /// is suitable for input to PSHUFLW.
3013 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3014   if (VT != MVT::v8i16)
3015     return false;
3016
3017   // Upper quadword copied in order.
3018   for (int i = 4; i != 8; ++i)
3019     if (Mask[i] >= 0 && Mask[i] != i)
3020       return false;
3021
3022   // Lower quadword shuffled.
3023   for (int i = 0; i != 4; ++i)
3024     if (Mask[i] >= 4)
3025       return false;
3026
3027   return true;
3028 }
3029
3030 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3031   SmallVector<int, 8> M;
3032   N->getMask(M);
3033   return ::isPSHUFLWMask(M, N->getValueType(0));
3034 }
3035
3036 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3037 /// is suitable for input to PALIGNR.
3038 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3039                           bool hasSSSE3) {
3040   int i, e = VT.getVectorNumElements();
3041
3042   // Do not handle v2i64 / v2f64 shuffles with palignr.
3043   if (e < 4 || !hasSSSE3)
3044     return false;
3045
3046   for (i = 0; i != e; ++i)
3047     if (Mask[i] >= 0)
3048       break;
3049
3050   // All undef, not a palignr.
3051   if (i == e)
3052     return false;
3053
3054   // Determine if it's ok to perform a palignr with only the LHS, since we
3055   // don't have access to the actual shuffle elements to see if RHS is undef.
3056   bool Unary = Mask[i] < (int)e;
3057   bool NeedsUnary = false;
3058
3059   int s = Mask[i] - i;
3060
3061   // Check the rest of the elements to see if they are consecutive.
3062   for (++i; i != e; ++i) {
3063     int m = Mask[i];
3064     if (m < 0)
3065       continue;
3066
3067     Unary = Unary && (m < (int)e);
3068     NeedsUnary = NeedsUnary || (m < s);
3069
3070     if (NeedsUnary && !Unary)
3071       return false;
3072     if (Unary && m != ((s+i) & (e-1)))
3073       return false;
3074     if (!Unary && m != (s+i))
3075       return false;
3076   }
3077   return true;
3078 }
3079
3080 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3081   SmallVector<int, 8> M;
3082   N->getMask(M);
3083   return ::isPALIGNRMask(M, N->getValueType(0), true);
3084 }
3085
3086 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3087 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3088 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3089   int NumElems = VT.getVectorNumElements();
3090   if (NumElems != 2 && NumElems != 4)
3091     return false;
3092
3093   int Half = NumElems / 2;
3094   for (int i = 0; i < Half; ++i)
3095     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3096       return false;
3097   for (int i = Half; i < NumElems; ++i)
3098     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3099       return false;
3100
3101   return true;
3102 }
3103
3104 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3105   SmallVector<int, 8> M;
3106   N->getMask(M);
3107   return ::isSHUFPMask(M, N->getValueType(0));
3108 }
3109
3110 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3111 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3112 /// half elements to come from vector 1 (which would equal the dest.) and
3113 /// the upper half to come from vector 2.
3114 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3115   int NumElems = VT.getVectorNumElements();
3116
3117   if (NumElems != 2 && NumElems != 4)
3118     return false;
3119
3120   int Half = NumElems / 2;
3121   for (int i = 0; i < Half; ++i)
3122     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3123       return false;
3124   for (int i = Half; i < NumElems; ++i)
3125     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3126       return false;
3127   return true;
3128 }
3129
3130 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3131   SmallVector<int, 8> M;
3132   N->getMask(M);
3133   return isCommutedSHUFPMask(M, N->getValueType(0));
3134 }
3135
3136 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3137 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3138 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3139   if (N->getValueType(0).getVectorNumElements() != 4)
3140     return false;
3141
3142   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3143   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3144          isUndefOrEqual(N->getMaskElt(1), 7) &&
3145          isUndefOrEqual(N->getMaskElt(2), 2) &&
3146          isUndefOrEqual(N->getMaskElt(3), 3);
3147 }
3148
3149 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3150 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3151 /// <2, 3, 2, 3>
3152 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3153   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3154
3155   if (NumElems != 4)
3156     return false;
3157
3158   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3159   isUndefOrEqual(N->getMaskElt(1), 3) &&
3160   isUndefOrEqual(N->getMaskElt(2), 2) &&
3161   isUndefOrEqual(N->getMaskElt(3), 3);
3162 }
3163
3164 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3165 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3166 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3167   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3168
3169   if (NumElems != 2 && NumElems != 4)
3170     return false;
3171
3172   for (unsigned i = 0; i < NumElems/2; ++i)
3173     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3174       return false;
3175
3176   for (unsigned i = NumElems/2; i < NumElems; ++i)
3177     if (!isUndefOrEqual(N->getMaskElt(i), i))
3178       return false;
3179
3180   return true;
3181 }
3182
3183 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3184 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3185 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3186   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3187
3188   if ((NumElems != 2 && NumElems != 4)
3189       || N->getValueType(0).getSizeInBits() > 128)
3190     return false;
3191
3192   for (unsigned i = 0; i < NumElems/2; ++i)
3193     if (!isUndefOrEqual(N->getMaskElt(i), i))
3194       return false;
3195
3196   for (unsigned i = 0; i < NumElems/2; ++i)
3197     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3198       return false;
3199
3200   return true;
3201 }
3202
3203 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3204 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3205 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3206                          bool V2IsSplat = false) {
3207   int NumElts = VT.getVectorNumElements();
3208   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3209     return false;
3210
3211   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3212   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3213   // sections.
3214   unsigned NumSections = VT.getSizeInBits() / 128;
3215   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3216   unsigned NumSectionElts = NumElts / NumSections;
3217
3218   unsigned Start = 0;
3219   unsigned End = NumSectionElts;
3220   for (unsigned s = 0; s < NumSections; ++s) {
3221     for (unsigned i = Start, j = s * NumSectionElts;
3222          i != End;
3223          i += 2, ++j) {
3224       int BitI  = Mask[i];
3225       int BitI1 = Mask[i+1];
3226       if (!isUndefOrEqual(BitI, j))
3227         return false;
3228       if (V2IsSplat) {
3229         if (!isUndefOrEqual(BitI1, NumElts))
3230           return false;
3231       } else {
3232         if (!isUndefOrEqual(BitI1, j + NumElts))
3233           return false;
3234       }
3235     }
3236     // Process the next 128 bits.
3237     Start += NumSectionElts;
3238     End += NumSectionElts;
3239   }
3240
3241   return true;
3242 }
3243
3244 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3245   SmallVector<int, 8> M;
3246   N->getMask(M);
3247   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3248 }
3249
3250 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3251 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3252 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3253                          bool V2IsSplat = false) {
3254   int NumElts = VT.getVectorNumElements();
3255   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3256     return false;
3257
3258   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3259     int BitI  = Mask[i];
3260     int BitI1 = Mask[i+1];
3261     if (!isUndefOrEqual(BitI, j + NumElts/2))
3262       return false;
3263     if (V2IsSplat) {
3264       if (isUndefOrEqual(BitI1, NumElts))
3265         return false;
3266     } else {
3267       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3268         return false;
3269     }
3270   }
3271   return true;
3272 }
3273
3274 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3275   SmallVector<int, 8> M;
3276   N->getMask(M);
3277   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3278 }
3279
3280 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3281 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3282 /// <0, 0, 1, 1>
3283 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3284   int NumElems = VT.getVectorNumElements();
3285   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3286     return false;
3287
3288   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3289   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3290   // sections.
3291   unsigned NumSections = VT.getSizeInBits() / 128;
3292   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3293   unsigned NumSectionElts = NumElems / NumSections;
3294
3295   for (unsigned s = 0; s < NumSections; ++s) {
3296     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3297          i != NumSectionElts * (s + 1);
3298          i += 2, ++j) {
3299       int BitI  = Mask[i];
3300       int BitI1 = Mask[i+1];
3301
3302       if (!isUndefOrEqual(BitI, j))
3303         return false;
3304       if (!isUndefOrEqual(BitI1, j))
3305         return false;
3306     }
3307   }
3308
3309   return true;
3310 }
3311
3312 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3313   SmallVector<int, 8> M;
3314   N->getMask(M);
3315   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3316 }
3317
3318 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3319 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3320 /// <2, 2, 3, 3>
3321 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3322   int NumElems = VT.getVectorNumElements();
3323   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3324     return false;
3325
3326   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3327     int BitI  = Mask[i];
3328     int BitI1 = Mask[i+1];
3329     if (!isUndefOrEqual(BitI, j))
3330       return false;
3331     if (!isUndefOrEqual(BitI1, j))
3332       return false;
3333   }
3334   return true;
3335 }
3336
3337 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3338   SmallVector<int, 8> M;
3339   N->getMask(M);
3340   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3341 }
3342
3343 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3344 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3345 /// MOVSD, and MOVD, i.e. setting the lowest element.
3346 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3347   if (VT.getVectorElementType().getSizeInBits() < 32)
3348     return false;
3349
3350   int NumElts = VT.getVectorNumElements();
3351
3352   if (!isUndefOrEqual(Mask[0], NumElts))
3353     return false;
3354
3355   for (int i = 1; i < NumElts; ++i)
3356     if (!isUndefOrEqual(Mask[i], i))
3357       return false;
3358
3359   return true;
3360 }
3361
3362 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3363   SmallVector<int, 8> M;
3364   N->getMask(M);
3365   return ::isMOVLMask(M, N->getValueType(0));
3366 }
3367
3368 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3369 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3370 /// element of vector 2 and the other elements to come from vector 1 in order.
3371 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3372                                bool V2IsSplat = false, bool V2IsUndef = false) {
3373   int NumOps = VT.getVectorNumElements();
3374   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3375     return false;
3376
3377   if (!isUndefOrEqual(Mask[0], 0))
3378     return false;
3379
3380   for (int i = 1; i < NumOps; ++i)
3381     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3382           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3383           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3384       return false;
3385
3386   return true;
3387 }
3388
3389 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3390                            bool V2IsUndef = false) {
3391   SmallVector<int, 8> M;
3392   N->getMask(M);
3393   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3394 }
3395
3396 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3397 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3398 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3399   if (N->getValueType(0).getVectorNumElements() != 4)
3400     return false;
3401
3402   // Expect 1, 1, 3, 3
3403   for (unsigned i = 0; i < 2; ++i) {
3404     int Elt = N->getMaskElt(i);
3405     if (Elt >= 0 && Elt != 1)
3406       return false;
3407   }
3408
3409   bool HasHi = false;
3410   for (unsigned i = 2; i < 4; ++i) {
3411     int Elt = N->getMaskElt(i);
3412     if (Elt >= 0 && Elt != 3)
3413       return false;
3414     if (Elt == 3)
3415       HasHi = true;
3416   }
3417   // Don't use movshdup if it can be done with a shufps.
3418   // FIXME: verify that matching u, u, 3, 3 is what we want.
3419   return HasHi;
3420 }
3421
3422 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3423 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3424 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3425   if (N->getValueType(0).getVectorNumElements() != 4)
3426     return false;
3427
3428   // Expect 0, 0, 2, 2
3429   for (unsigned i = 0; i < 2; ++i)
3430     if (N->getMaskElt(i) > 0)
3431       return false;
3432
3433   bool HasHi = false;
3434   for (unsigned i = 2; i < 4; ++i) {
3435     int Elt = N->getMaskElt(i);
3436     if (Elt >= 0 && Elt != 2)
3437       return false;
3438     if (Elt == 2)
3439       HasHi = true;
3440   }
3441   // Don't use movsldup if it can be done with a shufps.
3442   return HasHi;
3443 }
3444
3445 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3446 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3447 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3448   int e = N->getValueType(0).getVectorNumElements() / 2;
3449
3450   for (int i = 0; i < e; ++i)
3451     if (!isUndefOrEqual(N->getMaskElt(i), i))
3452       return false;
3453   for (int i = 0; i < e; ++i)
3454     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3455       return false;
3456   return true;
3457 }
3458
3459 /// isVEXTRACTF128Index - Return true if the specified
3460 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3461 /// suitable for input to VEXTRACTF128.
3462 bool X86::isVEXTRACTF128Index(SDNode *N) {
3463   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3464     return false;
3465
3466   // The index should be aligned on a 128-bit boundary.
3467   uint64_t Index =
3468     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3469
3470   unsigned VL = N->getValueType(0).getVectorNumElements();
3471   unsigned VBits = N->getValueType(0).getSizeInBits();
3472   unsigned ElSize = VBits / VL;
3473   bool Result = (Index * ElSize) % 128 == 0;
3474
3475   return Result;
3476 }
3477
3478 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3479 /// operand specifies a subvector insert that is suitable for input to
3480 /// VINSERTF128.
3481 bool X86::isVINSERTF128Index(SDNode *N) {
3482   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3483     return false;
3484
3485   // The index should be aligned on a 128-bit boundary.
3486   uint64_t Index =
3487     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3488
3489   unsigned VL = N->getValueType(0).getVectorNumElements();
3490   unsigned VBits = N->getValueType(0).getSizeInBits();
3491   unsigned ElSize = VBits / VL;
3492   bool Result = (Index * ElSize) % 128 == 0;
3493
3494   return Result;
3495 }
3496
3497 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3498 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3499 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3500   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3501   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3502
3503   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3504   unsigned Mask = 0;
3505   for (int i = 0; i < NumOperands; ++i) {
3506     int Val = SVOp->getMaskElt(NumOperands-i-1);
3507     if (Val < 0) Val = 0;
3508     if (Val >= NumOperands) Val -= NumOperands;
3509     Mask |= Val;
3510     if (i != NumOperands - 1)
3511       Mask <<= Shift;
3512   }
3513   return Mask;
3514 }
3515
3516 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3517 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3518 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3519   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3520   unsigned Mask = 0;
3521   // 8 nodes, but we only care about the last 4.
3522   for (unsigned i = 7; i >= 4; --i) {
3523     int Val = SVOp->getMaskElt(i);
3524     if (Val >= 0)
3525       Mask |= (Val - 4);
3526     if (i != 4)
3527       Mask <<= 2;
3528   }
3529   return Mask;
3530 }
3531
3532 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3533 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3534 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3535   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3536   unsigned Mask = 0;
3537   // 8 nodes, but we only care about the first 4.
3538   for (int i = 3; i >= 0; --i) {
3539     int Val = SVOp->getMaskElt(i);
3540     if (Val >= 0)
3541       Mask |= Val;
3542     if (i != 0)
3543       Mask <<= 2;
3544   }
3545   return Mask;
3546 }
3547
3548 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3549 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3550 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3551   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3552   EVT VVT = N->getValueType(0);
3553   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3554   int Val = 0;
3555
3556   unsigned i, e;
3557   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3558     Val = SVOp->getMaskElt(i);
3559     if (Val >= 0)
3560       break;
3561   }
3562   return (Val - i) * EltSize;
3563 }
3564
3565 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3566 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3567 /// instructions.
3568 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3569   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3570     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3571
3572   uint64_t Index =
3573     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3574
3575   EVT VecVT = N->getOperand(0).getValueType();
3576   EVT ElVT = VecVT.getVectorElementType();
3577
3578   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3579
3580   return Index / NumElemsPerChunk;
3581 }
3582
3583 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3584 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3585 /// instructions.
3586 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3587   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3588     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3589
3590   uint64_t Index =
3591     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3592
3593   EVT VecVT = N->getValueType(0);
3594   EVT ElVT = VecVT.getVectorElementType();
3595
3596   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3597
3598   return Index / NumElemsPerChunk;
3599 }
3600
3601 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3602 /// constant +0.0.
3603 bool X86::isZeroNode(SDValue Elt) {
3604   return ((isa<ConstantSDNode>(Elt) &&
3605            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3606           (isa<ConstantFPSDNode>(Elt) &&
3607            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3608 }
3609
3610 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3611 /// their permute mask.
3612 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3613                                     SelectionDAG &DAG) {
3614   EVT VT = SVOp->getValueType(0);
3615   unsigned NumElems = VT.getVectorNumElements();
3616   SmallVector<int, 8> MaskVec;
3617
3618   for (unsigned i = 0; i != NumElems; ++i) {
3619     int idx = SVOp->getMaskElt(i);
3620     if (idx < 0)
3621       MaskVec.push_back(idx);
3622     else if (idx < (int)NumElems)
3623       MaskVec.push_back(idx + NumElems);
3624     else
3625       MaskVec.push_back(idx - NumElems);
3626   }
3627   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3628                               SVOp->getOperand(0), &MaskVec[0]);
3629 }
3630
3631 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3632 /// the two vector operands have swapped position.
3633 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3634   unsigned NumElems = VT.getVectorNumElements();
3635   for (unsigned i = 0; i != NumElems; ++i) {
3636     int idx = Mask[i];
3637     if (idx < 0)
3638       continue;
3639     else if (idx < (int)NumElems)
3640       Mask[i] = idx + NumElems;
3641     else
3642       Mask[i] = idx - NumElems;
3643   }
3644 }
3645
3646 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3647 /// match movhlps. The lower half elements should come from upper half of
3648 /// V1 (and in order), and the upper half elements should come from the upper
3649 /// half of V2 (and in order).
3650 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3651   if (Op->getValueType(0).getVectorNumElements() != 4)
3652     return false;
3653   for (unsigned i = 0, e = 2; i != e; ++i)
3654     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3655       return false;
3656   for (unsigned i = 2; i != 4; ++i)
3657     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3658       return false;
3659   return true;
3660 }
3661
3662 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3663 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3664 /// required.
3665 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3666   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3667     return false;
3668   N = N->getOperand(0).getNode();
3669   if (!ISD::isNON_EXTLoad(N))
3670     return false;
3671   if (LD)
3672     *LD = cast<LoadSDNode>(N);
3673   return true;
3674 }
3675
3676 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3677 /// match movlp{s|d}. The lower half elements should come from lower half of
3678 /// V1 (and in order), and the upper half elements should come from the upper
3679 /// half of V2 (and in order). And since V1 will become the source of the
3680 /// MOVLP, it must be either a vector load or a scalar load to vector.
3681 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3682                                ShuffleVectorSDNode *Op) {
3683   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3684     return false;
3685   // Is V2 is a vector load, don't do this transformation. We will try to use
3686   // load folding shufps op.
3687   if (ISD::isNON_EXTLoad(V2))
3688     return false;
3689
3690   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3691
3692   if (NumElems != 2 && NumElems != 4)
3693     return false;
3694   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3695     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3696       return false;
3697   for (unsigned i = NumElems/2; i != NumElems; ++i)
3698     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3699       return false;
3700   return true;
3701 }
3702
3703 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3704 /// all the same.
3705 static bool isSplatVector(SDNode *N) {
3706   if (N->getOpcode() != ISD::BUILD_VECTOR)
3707     return false;
3708
3709   SDValue SplatValue = N->getOperand(0);
3710   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3711     if (N->getOperand(i) != SplatValue)
3712       return false;
3713   return true;
3714 }
3715
3716 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3717 /// to an zero vector.
3718 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3719 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3720   SDValue V1 = N->getOperand(0);
3721   SDValue V2 = N->getOperand(1);
3722   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3723   for (unsigned i = 0; i != NumElems; ++i) {
3724     int Idx = N->getMaskElt(i);
3725     if (Idx >= (int)NumElems) {
3726       unsigned Opc = V2.getOpcode();
3727       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3728         continue;
3729       if (Opc != ISD::BUILD_VECTOR ||
3730           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3731         return false;
3732     } else if (Idx >= 0) {
3733       unsigned Opc = V1.getOpcode();
3734       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3735         continue;
3736       if (Opc != ISD::BUILD_VECTOR ||
3737           !X86::isZeroNode(V1.getOperand(Idx)))
3738         return false;
3739     }
3740   }
3741   return true;
3742 }
3743
3744 /// getZeroVector - Returns a vector of specified type with all zero elements.
3745 ///
3746 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3747                              DebugLoc dl) {
3748   assert(VT.isVector() && "Expected a vector type");
3749
3750   // Always build SSE zero vectors as <4 x i32> bitcasted
3751   // to their dest type. This ensures they get CSE'd.
3752   SDValue Vec;
3753   if (VT.getSizeInBits() == 128) {  // SSE
3754     if (HasSSE2) {  // SSE2
3755       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3756       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3757     } else { // SSE1
3758       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3759       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3760     }
3761   } else if (VT.getSizeInBits() == 256) { // AVX
3762     // 256-bit logic and arithmetic instructions in AVX are
3763     // all floating-point, no support for integer ops. Default
3764     // to emitting fp zeroed vectors then.
3765     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3766     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3767     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3768   }
3769   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3770 }
3771
3772 /// getOnesVector - Returns a vector of specified type with all bits set.
3773 ///
3774 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3775   assert(VT.isVector() && "Expected a vector type");
3776
3777   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3778   // type.  This ensures they get CSE'd.
3779   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3780   SDValue Vec;
3781   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3782   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3783 }
3784
3785
3786 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3787 /// that point to V2 points to its first element.
3788 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3789   EVT VT = SVOp->getValueType(0);
3790   unsigned NumElems = VT.getVectorNumElements();
3791
3792   bool Changed = false;
3793   SmallVector<int, 8> MaskVec;
3794   SVOp->getMask(MaskVec);
3795
3796   for (unsigned i = 0; i != NumElems; ++i) {
3797     if (MaskVec[i] > (int)NumElems) {
3798       MaskVec[i] = NumElems;
3799       Changed = true;
3800     }
3801   }
3802   if (Changed)
3803     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3804                                 SVOp->getOperand(1), &MaskVec[0]);
3805   return SDValue(SVOp, 0);
3806 }
3807
3808 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3809 /// operation of specified width.
3810 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3811                        SDValue V2) {
3812   unsigned NumElems = VT.getVectorNumElements();
3813   SmallVector<int, 8> Mask;
3814   Mask.push_back(NumElems);
3815   for (unsigned i = 1; i != NumElems; ++i)
3816     Mask.push_back(i);
3817   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3818 }
3819
3820 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3821 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3822                           SDValue V2) {
3823   unsigned NumElems = VT.getVectorNumElements();
3824   SmallVector<int, 8> Mask;
3825   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3826     Mask.push_back(i);
3827     Mask.push_back(i + NumElems);
3828   }
3829   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3830 }
3831
3832 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3833 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3834                           SDValue V2) {
3835   unsigned NumElems = VT.getVectorNumElements();
3836   unsigned Half = NumElems/2;
3837   SmallVector<int, 8> Mask;
3838   for (unsigned i = 0; i != Half; ++i) {
3839     Mask.push_back(i + Half);
3840     Mask.push_back(i + NumElems + Half);
3841   }
3842   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3843 }
3844
3845 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3846 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3847   EVT PVT = MVT::v4f32;
3848   EVT VT = SV->getValueType(0);
3849   DebugLoc dl = SV->getDebugLoc();
3850   SDValue V1 = SV->getOperand(0);
3851   int NumElems = VT.getVectorNumElements();
3852   int EltNo = SV->getSplatIndex();
3853
3854   // unpack elements to the correct location
3855   while (NumElems > 4) {
3856     if (EltNo < NumElems/2) {
3857       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3858     } else {
3859       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3860       EltNo -= NumElems/2;
3861     }
3862     NumElems >>= 1;
3863   }
3864
3865   // Perform the splat.
3866   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3867   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3868   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3869   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3870 }
3871
3872 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3873 /// vector of zero or undef vector.  This produces a shuffle where the low
3874 /// element of V2 is swizzled into the zero/undef vector, landing at element
3875 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3876 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3877                                              bool isZero, bool HasSSE2,
3878                                              SelectionDAG &DAG) {
3879   EVT VT = V2.getValueType();
3880   SDValue V1 = isZero
3881     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3882   unsigned NumElems = VT.getVectorNumElements();
3883   SmallVector<int, 16> MaskVec;
3884   for (unsigned i = 0; i != NumElems; ++i)
3885     // If this is the insertion idx, put the low elt of V2 here.
3886     MaskVec.push_back(i == Idx ? NumElems : i);
3887   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3888 }
3889
3890 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3891 /// element of the result of the vector shuffle.
3892 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3893                                    unsigned Depth) {
3894   if (Depth == 6)
3895     return SDValue();  // Limit search depth.
3896
3897   SDValue V = SDValue(N, 0);
3898   EVT VT = V.getValueType();
3899   unsigned Opcode = V.getOpcode();
3900
3901   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3902   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3903     Index = SV->getMaskElt(Index);
3904
3905     if (Index < 0)
3906       return DAG.getUNDEF(VT.getVectorElementType());
3907
3908     int NumElems = VT.getVectorNumElements();
3909     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3910     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3911   }
3912
3913   // Recurse into target specific vector shuffles to find scalars.
3914   if (isTargetShuffle(Opcode)) {
3915     int NumElems = VT.getVectorNumElements();
3916     SmallVector<unsigned, 16> ShuffleMask;
3917     SDValue ImmN;
3918
3919     switch(Opcode) {
3920     case X86ISD::SHUFPS:
3921     case X86ISD::SHUFPD:
3922       ImmN = N->getOperand(N->getNumOperands()-1);
3923       DecodeSHUFPSMask(NumElems,
3924                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3925                        ShuffleMask);
3926       break;
3927     case X86ISD::PUNPCKHBW:
3928     case X86ISD::PUNPCKHWD:
3929     case X86ISD::PUNPCKHDQ:
3930     case X86ISD::PUNPCKHQDQ:
3931       DecodePUNPCKHMask(NumElems, ShuffleMask);
3932       break;
3933     case X86ISD::UNPCKHPS:
3934     case X86ISD::UNPCKHPD:
3935       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3936       break;
3937     case X86ISD::PUNPCKLBW:
3938     case X86ISD::PUNPCKLWD:
3939     case X86ISD::PUNPCKLDQ:
3940     case X86ISD::PUNPCKLQDQ:
3941       DecodePUNPCKLMask(VT, ShuffleMask);
3942       break;
3943     case X86ISD::UNPCKLPS:
3944     case X86ISD::UNPCKLPD:
3945     case X86ISD::VUNPCKLPS:
3946     case X86ISD::VUNPCKLPD:
3947     case X86ISD::VUNPCKLPSY:
3948     case X86ISD::VUNPCKLPDY:
3949       DecodeUNPCKLPMask(VT, ShuffleMask);
3950       break;
3951     case X86ISD::MOVHLPS:
3952       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3953       break;
3954     case X86ISD::MOVLHPS:
3955       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3956       break;
3957     case X86ISD::PSHUFD:
3958       ImmN = N->getOperand(N->getNumOperands()-1);
3959       DecodePSHUFMask(NumElems,
3960                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3961                       ShuffleMask);
3962       break;
3963     case X86ISD::PSHUFHW:
3964       ImmN = N->getOperand(N->getNumOperands()-1);
3965       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3966                         ShuffleMask);
3967       break;
3968     case X86ISD::PSHUFLW:
3969       ImmN = N->getOperand(N->getNumOperands()-1);
3970       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3971                         ShuffleMask);
3972       break;
3973     case X86ISD::MOVSS:
3974     case X86ISD::MOVSD: {
3975       // The index 0 always comes from the first element of the second source,
3976       // this is why MOVSS and MOVSD are used in the first place. The other
3977       // elements come from the other positions of the first source vector.
3978       unsigned OpNum = (Index == 0) ? 1 : 0;
3979       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3980                                  Depth+1);
3981     }
3982     default:
3983       assert("not implemented for target shuffle node");
3984       return SDValue();
3985     }
3986
3987     Index = ShuffleMask[Index];
3988     if (Index < 0)
3989       return DAG.getUNDEF(VT.getVectorElementType());
3990
3991     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3992     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3993                                Depth+1);
3994   }
3995
3996   // Actual nodes that may contain scalar elements
3997   if (Opcode == ISD::BITCAST) {
3998     V = V.getOperand(0);
3999     EVT SrcVT = V.getValueType();
4000     unsigned NumElems = VT.getVectorNumElements();
4001
4002     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4003       return SDValue();
4004   }
4005
4006   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4007     return (Index == 0) ? V.getOperand(0)
4008                           : DAG.getUNDEF(VT.getVectorElementType());
4009
4010   if (V.getOpcode() == ISD::BUILD_VECTOR)
4011     return V.getOperand(Index);
4012
4013   return SDValue();
4014 }
4015
4016 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4017 /// shuffle operation which come from a consecutively from a zero. The
4018 /// search can start in two different directions, from left or right.
4019 static
4020 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4021                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4022   int i = 0;
4023
4024   while (i < NumElems) {
4025     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4026     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4027     if (!(Elt.getNode() &&
4028          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4029       break;
4030     ++i;
4031   }
4032
4033   return i;
4034 }
4035
4036 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4037 /// MaskE correspond consecutively to elements from one of the vector operands,
4038 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4039 static
4040 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4041                               int OpIdx, int NumElems, unsigned &OpNum) {
4042   bool SeenV1 = false;
4043   bool SeenV2 = false;
4044
4045   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4046     int Idx = SVOp->getMaskElt(i);
4047     // Ignore undef indicies
4048     if (Idx < 0)
4049       continue;
4050
4051     if (Idx < NumElems)
4052       SeenV1 = true;
4053     else
4054       SeenV2 = true;
4055
4056     // Only accept consecutive elements from the same vector
4057     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4058       return false;
4059   }
4060
4061   OpNum = SeenV1 ? 0 : 1;
4062   return true;
4063 }
4064
4065 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4066 /// logical left shift of a vector.
4067 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4068                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4069   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4070   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4071               false /* check zeros from right */, DAG);
4072   unsigned OpSrc;
4073
4074   if (!NumZeros)
4075     return false;
4076
4077   // Considering the elements in the mask that are not consecutive zeros,
4078   // check if they consecutively come from only one of the source vectors.
4079   //
4080   //               V1 = {X, A, B, C}     0
4081   //                         \  \  \    /
4082   //   vector_shuffle V1, V2 <1, 2, 3, X>
4083   //
4084   if (!isShuffleMaskConsecutive(SVOp,
4085             0,                   // Mask Start Index
4086             NumElems-NumZeros-1, // Mask End Index
4087             NumZeros,            // Where to start looking in the src vector
4088             NumElems,            // Number of elements in vector
4089             OpSrc))              // Which source operand ?
4090     return false;
4091
4092   isLeft = false;
4093   ShAmt = NumZeros;
4094   ShVal = SVOp->getOperand(OpSrc);
4095   return true;
4096 }
4097
4098 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4099 /// logical left shift of a vector.
4100 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4101                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4102   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4103   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4104               true /* check zeros from left */, DAG);
4105   unsigned OpSrc;
4106
4107   if (!NumZeros)
4108     return false;
4109
4110   // Considering the elements in the mask that are not consecutive zeros,
4111   // check if they consecutively come from only one of the source vectors.
4112   //
4113   //                           0    { A, B, X, X } = V2
4114   //                          / \    /  /
4115   //   vector_shuffle V1, V2 <X, X, 4, 5>
4116   //
4117   if (!isShuffleMaskConsecutive(SVOp,
4118             NumZeros,     // Mask Start Index
4119             NumElems-1,   // Mask End Index
4120             0,            // Where to start looking in the src vector
4121             NumElems,     // Number of elements in vector
4122             OpSrc))       // Which source operand ?
4123     return false;
4124
4125   isLeft = true;
4126   ShAmt = NumZeros;
4127   ShVal = SVOp->getOperand(OpSrc);
4128   return true;
4129 }
4130
4131 /// isVectorShift - Returns true if the shuffle can be implemented as a
4132 /// logical left or right shift of a vector.
4133 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4134                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4135   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4136       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4137     return true;
4138
4139   return false;
4140 }
4141
4142 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4143 ///
4144 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4145                                        unsigned NumNonZero, unsigned NumZero,
4146                                        SelectionDAG &DAG,
4147                                        const TargetLowering &TLI) {
4148   if (NumNonZero > 8)
4149     return SDValue();
4150
4151   DebugLoc dl = Op.getDebugLoc();
4152   SDValue V(0, 0);
4153   bool First = true;
4154   for (unsigned i = 0; i < 16; ++i) {
4155     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4156     if (ThisIsNonZero && First) {
4157       if (NumZero)
4158         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4159       else
4160         V = DAG.getUNDEF(MVT::v8i16);
4161       First = false;
4162     }
4163
4164     if ((i & 1) != 0) {
4165       SDValue ThisElt(0, 0), LastElt(0, 0);
4166       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4167       if (LastIsNonZero) {
4168         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4169                               MVT::i16, Op.getOperand(i-1));
4170       }
4171       if (ThisIsNonZero) {
4172         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4173         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4174                               ThisElt, DAG.getConstant(8, MVT::i8));
4175         if (LastIsNonZero)
4176           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4177       } else
4178         ThisElt = LastElt;
4179
4180       if (ThisElt.getNode())
4181         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4182                         DAG.getIntPtrConstant(i/2));
4183     }
4184   }
4185
4186   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4187 }
4188
4189 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4190 ///
4191 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4192                                      unsigned NumNonZero, unsigned NumZero,
4193                                      SelectionDAG &DAG,
4194                                      const TargetLowering &TLI) {
4195   if (NumNonZero > 4)
4196     return SDValue();
4197
4198   DebugLoc dl = Op.getDebugLoc();
4199   SDValue V(0, 0);
4200   bool First = true;
4201   for (unsigned i = 0; i < 8; ++i) {
4202     bool isNonZero = (NonZeros & (1 << i)) != 0;
4203     if (isNonZero) {
4204       if (First) {
4205         if (NumZero)
4206           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4207         else
4208           V = DAG.getUNDEF(MVT::v8i16);
4209         First = false;
4210       }
4211       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4212                       MVT::v8i16, V, Op.getOperand(i),
4213                       DAG.getIntPtrConstant(i));
4214     }
4215   }
4216
4217   return V;
4218 }
4219
4220 /// getVShift - Return a vector logical shift node.
4221 ///
4222 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4223                          unsigned NumBits, SelectionDAG &DAG,
4224                          const TargetLowering &TLI, DebugLoc dl) {
4225   EVT ShVT = MVT::v2i64;
4226   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4227   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4228   return DAG.getNode(ISD::BITCAST, dl, VT,
4229                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4230                              DAG.getConstant(NumBits,
4231                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4232 }
4233
4234 SDValue
4235 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4236                                           SelectionDAG &DAG) const {
4237
4238   // Check if the scalar load can be widened into a vector load. And if
4239   // the address is "base + cst" see if the cst can be "absorbed" into
4240   // the shuffle mask.
4241   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4242     SDValue Ptr = LD->getBasePtr();
4243     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4244       return SDValue();
4245     EVT PVT = LD->getValueType(0);
4246     if (PVT != MVT::i32 && PVT != MVT::f32)
4247       return SDValue();
4248
4249     int FI = -1;
4250     int64_t Offset = 0;
4251     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4252       FI = FINode->getIndex();
4253       Offset = 0;
4254     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4255                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4256       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4257       Offset = Ptr.getConstantOperandVal(1);
4258       Ptr = Ptr.getOperand(0);
4259     } else {
4260       return SDValue();
4261     }
4262
4263     SDValue Chain = LD->getChain();
4264     // Make sure the stack object alignment is at least 16.
4265     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4266     if (DAG.InferPtrAlignment(Ptr) < 16) {
4267       if (MFI->isFixedObjectIndex(FI)) {
4268         // Can't change the alignment. FIXME: It's possible to compute
4269         // the exact stack offset and reference FI + adjust offset instead.
4270         // If someone *really* cares about this. That's the way to implement it.
4271         return SDValue();
4272       } else {
4273         MFI->setObjectAlignment(FI, 16);
4274       }
4275     }
4276
4277     // (Offset % 16) must be multiple of 4. Then address is then
4278     // Ptr + (Offset & ~15).
4279     if (Offset < 0)
4280       return SDValue();
4281     if ((Offset % 16) & 3)
4282       return SDValue();
4283     int64_t StartOffset = Offset & ~15;
4284     if (StartOffset)
4285       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4286                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4287
4288     int EltNo = (Offset - StartOffset) >> 2;
4289     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4290     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4291     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4292                              LD->getPointerInfo().getWithOffset(StartOffset),
4293                              false, false, 0);
4294     // Canonicalize it to a v4i32 shuffle.
4295     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4296     return DAG.getNode(ISD::BITCAST, dl, VT,
4297                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4298                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4299   }
4300
4301   return SDValue();
4302 }
4303
4304 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4305 /// vector of type 'VT', see if the elements can be replaced by a single large
4306 /// load which has the same value as a build_vector whose operands are 'elts'.
4307 ///
4308 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4309 ///
4310 /// FIXME: we'd also like to handle the case where the last elements are zero
4311 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4312 /// There's even a handy isZeroNode for that purpose.
4313 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4314                                         DebugLoc &DL, SelectionDAG &DAG) {
4315   EVT EltVT = VT.getVectorElementType();
4316   unsigned NumElems = Elts.size();
4317
4318   LoadSDNode *LDBase = NULL;
4319   unsigned LastLoadedElt = -1U;
4320
4321   // For each element in the initializer, see if we've found a load or an undef.
4322   // If we don't find an initial load element, or later load elements are
4323   // non-consecutive, bail out.
4324   for (unsigned i = 0; i < NumElems; ++i) {
4325     SDValue Elt = Elts[i];
4326
4327     if (!Elt.getNode() ||
4328         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4329       return SDValue();
4330     if (!LDBase) {
4331       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4332         return SDValue();
4333       LDBase = cast<LoadSDNode>(Elt.getNode());
4334       LastLoadedElt = i;
4335       continue;
4336     }
4337     if (Elt.getOpcode() == ISD::UNDEF)
4338       continue;
4339
4340     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4341     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4342       return SDValue();
4343     LastLoadedElt = i;
4344   }
4345
4346   // If we have found an entire vector of loads and undefs, then return a large
4347   // load of the entire vector width starting at the base pointer.  If we found
4348   // consecutive loads for the low half, generate a vzext_load node.
4349   if (LastLoadedElt == NumElems - 1) {
4350     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4351       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4352                          LDBase->getPointerInfo(),
4353                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4354     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4355                        LDBase->getPointerInfo(),
4356                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4357                        LDBase->getAlignment());
4358   } else if (NumElems == 4 && LastLoadedElt == 1) {
4359     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4360     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4361     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4362                                               Ops, 2, MVT::i32,
4363                                               LDBase->getMemOperand());
4364     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4365   }
4366   return SDValue();
4367 }
4368
4369 SDValue
4370 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4371   DebugLoc dl = Op.getDebugLoc();
4372
4373   EVT VT = Op.getValueType();
4374   EVT ExtVT = VT.getVectorElementType();
4375
4376   unsigned NumElems = Op.getNumOperands();
4377
4378   // For AVX-length vectors, build the individual 128-bit pieces and
4379   // use shuffles to put them in place.
4380   if (VT.getSizeInBits() > 256 &&
4381       Subtarget->hasAVX() &&
4382       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4383     SmallVector<SDValue, 8> V;
4384     V.resize(NumElems);
4385     for (unsigned i = 0; i < NumElems; ++i) {
4386       V[i] = Op.getOperand(i);
4387     }
4388
4389     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4390
4391     // Build the lower subvector.
4392     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4393     // Build the upper subvector.
4394     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4395                                 NumElems/2);
4396
4397     return ConcatVectors(Lower, Upper, DAG);
4398   }
4399
4400   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4401   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4402   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4403   // is present, so AllOnes is ignored.
4404   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4405       (Op.getValueType().getSizeInBits() != 256 &&
4406        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4407     // Canonicalize this to <4 x i32> (SSE) to
4408     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4409     // eliminated on x86-32 hosts.
4410     if (Op.getValueType() == MVT::v4i32)
4411       return Op;
4412
4413     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4414       return getOnesVector(Op.getValueType(), DAG, dl);
4415     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4416   }
4417
4418   unsigned EVTBits = ExtVT.getSizeInBits();
4419
4420   unsigned NumZero  = 0;
4421   unsigned NumNonZero = 0;
4422   unsigned NonZeros = 0;
4423   bool IsAllConstants = true;
4424   SmallSet<SDValue, 8> Values;
4425   for (unsigned i = 0; i < NumElems; ++i) {
4426     SDValue Elt = Op.getOperand(i);
4427     if (Elt.getOpcode() == ISD::UNDEF)
4428       continue;
4429     Values.insert(Elt);
4430     if (Elt.getOpcode() != ISD::Constant &&
4431         Elt.getOpcode() != ISD::ConstantFP)
4432       IsAllConstants = false;
4433     if (X86::isZeroNode(Elt))
4434       NumZero++;
4435     else {
4436       NonZeros |= (1 << i);
4437       NumNonZero++;
4438     }
4439   }
4440
4441   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4442   if (NumNonZero == 0)
4443     return DAG.getUNDEF(VT);
4444
4445   // Special case for single non-zero, non-undef, element.
4446   if (NumNonZero == 1) {
4447     unsigned Idx = CountTrailingZeros_32(NonZeros);
4448     SDValue Item = Op.getOperand(Idx);
4449
4450     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4451     // the value are obviously zero, truncate the value to i32 and do the
4452     // insertion that way.  Only do this if the value is non-constant or if the
4453     // value is a constant being inserted into element 0.  It is cheaper to do
4454     // a constant pool load than it is to do a movd + shuffle.
4455     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4456         (!IsAllConstants || Idx == 0)) {
4457       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4458         // Handle SSE only.
4459         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4460         EVT VecVT = MVT::v4i32;
4461         unsigned VecElts = 4;
4462
4463         // Truncate the value (which may itself be a constant) to i32, and
4464         // convert it to a vector with movd (S2V+shuffle to zero extend).
4465         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4466         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4467         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4468                                            Subtarget->hasSSE2(), DAG);
4469
4470         // Now we have our 32-bit value zero extended in the low element of
4471         // a vector.  If Idx != 0, swizzle it into place.
4472         if (Idx != 0) {
4473           SmallVector<int, 4> Mask;
4474           Mask.push_back(Idx);
4475           for (unsigned i = 1; i != VecElts; ++i)
4476             Mask.push_back(i);
4477           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4478                                       DAG.getUNDEF(Item.getValueType()),
4479                                       &Mask[0]);
4480         }
4481         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4482       }
4483     }
4484
4485     // If we have a constant or non-constant insertion into the low element of
4486     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4487     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4488     // depending on what the source datatype is.
4489     if (Idx == 0) {
4490       if (NumZero == 0) {
4491         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4492       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4493           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4494         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4495         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4496         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4497                                            DAG);
4498       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4499         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4500         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4501         EVT MiddleVT = MVT::v4i32;
4502         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4503         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4504                                            Subtarget->hasSSE2(), DAG);
4505         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4506       }
4507     }
4508
4509     // Is it a vector logical left shift?
4510     if (NumElems == 2 && Idx == 1 &&
4511         X86::isZeroNode(Op.getOperand(0)) &&
4512         !X86::isZeroNode(Op.getOperand(1))) {
4513       unsigned NumBits = VT.getSizeInBits();
4514       return getVShift(true, VT,
4515                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4516                                    VT, Op.getOperand(1)),
4517                        NumBits/2, DAG, *this, dl);
4518     }
4519
4520     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4521       return SDValue();
4522
4523     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4524     // is a non-constant being inserted into an element other than the low one,
4525     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4526     // movd/movss) to move this into the low element, then shuffle it into
4527     // place.
4528     if (EVTBits == 32) {
4529       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4530
4531       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4532       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4533                                          Subtarget->hasSSE2(), DAG);
4534       SmallVector<int, 8> MaskVec;
4535       for (unsigned i = 0; i < NumElems; i++)
4536         MaskVec.push_back(i == Idx ? 0 : 1);
4537       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4538     }
4539   }
4540
4541   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4542   if (Values.size() == 1) {
4543     if (EVTBits == 32) {
4544       // Instead of a shuffle like this:
4545       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4546       // Check if it's possible to issue this instead.
4547       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4548       unsigned Idx = CountTrailingZeros_32(NonZeros);
4549       SDValue Item = Op.getOperand(Idx);
4550       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4551         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4552     }
4553     return SDValue();
4554   }
4555
4556   // A vector full of immediates; various special cases are already
4557   // handled, so this is best done with a single constant-pool load.
4558   if (IsAllConstants)
4559     return SDValue();
4560
4561   // Let legalizer expand 2-wide build_vectors.
4562   if (EVTBits == 64) {
4563     if (NumNonZero == 1) {
4564       // One half is zero or undef.
4565       unsigned Idx = CountTrailingZeros_32(NonZeros);
4566       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4567                                  Op.getOperand(Idx));
4568       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4569                                          Subtarget->hasSSE2(), DAG);
4570     }
4571     return SDValue();
4572   }
4573
4574   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4575   if (EVTBits == 8 && NumElems == 16) {
4576     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4577                                         *this);
4578     if (V.getNode()) return V;
4579   }
4580
4581   if (EVTBits == 16 && NumElems == 8) {
4582     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4583                                       *this);
4584     if (V.getNode()) return V;
4585   }
4586
4587   // If element VT is == 32 bits, turn it into a number of shuffles.
4588   SmallVector<SDValue, 8> V;
4589   V.resize(NumElems);
4590   if (NumElems == 4 && NumZero > 0) {
4591     for (unsigned i = 0; i < 4; ++i) {
4592       bool isZero = !(NonZeros & (1 << i));
4593       if (isZero)
4594         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4595       else
4596         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4597     }
4598
4599     for (unsigned i = 0; i < 2; ++i) {
4600       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4601         default: break;
4602         case 0:
4603           V[i] = V[i*2];  // Must be a zero vector.
4604           break;
4605         case 1:
4606           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4607           break;
4608         case 2:
4609           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4610           break;
4611         case 3:
4612           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4613           break;
4614       }
4615     }
4616
4617     SmallVector<int, 8> MaskVec;
4618     bool Reverse = (NonZeros & 0x3) == 2;
4619     for (unsigned i = 0; i < 2; ++i)
4620       MaskVec.push_back(Reverse ? 1-i : i);
4621     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4622     for (unsigned i = 0; i < 2; ++i)
4623       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4624     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4625   }
4626
4627   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4628     // Check for a build vector of consecutive loads.
4629     for (unsigned i = 0; i < NumElems; ++i)
4630       V[i] = Op.getOperand(i);
4631
4632     // Check for elements which are consecutive loads.
4633     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4634     if (LD.getNode())
4635       return LD;
4636
4637     // For SSE 4.1, use insertps to put the high elements into the low element.
4638     if (getSubtarget()->hasSSE41()) {
4639       SDValue Result;
4640       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4641         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4642       else
4643         Result = DAG.getUNDEF(VT);
4644
4645       for (unsigned i = 1; i < NumElems; ++i) {
4646         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4647         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4648                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4649       }
4650       return Result;
4651     }
4652
4653     // Otherwise, expand into a number of unpckl*, start by extending each of
4654     // our (non-undef) elements to the full vector width with the element in the
4655     // bottom slot of the vector (which generates no code for SSE).
4656     for (unsigned i = 0; i < NumElems; ++i) {
4657       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4658         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4659       else
4660         V[i] = DAG.getUNDEF(VT);
4661     }
4662
4663     // Next, we iteratively mix elements, e.g. for v4f32:
4664     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4665     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4666     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4667     unsigned EltStride = NumElems >> 1;
4668     while (EltStride != 0) {
4669       for (unsigned i = 0; i < EltStride; ++i) {
4670         // If V[i+EltStride] is undef and this is the first round of mixing,
4671         // then it is safe to just drop this shuffle: V[i] is already in the
4672         // right place, the one element (since it's the first round) being
4673         // inserted as undef can be dropped.  This isn't safe for successive
4674         // rounds because they will permute elements within both vectors.
4675         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4676             EltStride == NumElems/2)
4677           continue;
4678
4679         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4680       }
4681       EltStride >>= 1;
4682     }
4683     return V[0];
4684   }
4685   return SDValue();
4686 }
4687
4688 SDValue
4689 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4690   // We support concatenate two MMX registers and place them in a MMX
4691   // register.  This is better than doing a stack convert.
4692   DebugLoc dl = Op.getDebugLoc();
4693   EVT ResVT = Op.getValueType();
4694   assert(Op.getNumOperands() == 2);
4695   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4696          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4697   int Mask[2];
4698   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4699   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4700   InVec = Op.getOperand(1);
4701   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4702     unsigned NumElts = ResVT.getVectorNumElements();
4703     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4704     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4705                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4706   } else {
4707     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4708     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4709     Mask[0] = 0; Mask[1] = 2;
4710     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4711   }
4712   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4713 }
4714
4715 // v8i16 shuffles - Prefer shuffles in the following order:
4716 // 1. [all]   pshuflw, pshufhw, optional move
4717 // 2. [ssse3] 1 x pshufb
4718 // 3. [ssse3] 2 x pshufb + 1 x por
4719 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4720 SDValue
4721 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4722                                             SelectionDAG &DAG) const {
4723   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4724   SDValue V1 = SVOp->getOperand(0);
4725   SDValue V2 = SVOp->getOperand(1);
4726   DebugLoc dl = SVOp->getDebugLoc();
4727   SmallVector<int, 8> MaskVals;
4728
4729   // Determine if more than 1 of the words in each of the low and high quadwords
4730   // of the result come from the same quadword of one of the two inputs.  Undef
4731   // mask values count as coming from any quadword, for better codegen.
4732   SmallVector<unsigned, 4> LoQuad(4);
4733   SmallVector<unsigned, 4> HiQuad(4);
4734   BitVector InputQuads(4);
4735   for (unsigned i = 0; i < 8; ++i) {
4736     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4737     int EltIdx = SVOp->getMaskElt(i);
4738     MaskVals.push_back(EltIdx);
4739     if (EltIdx < 0) {
4740       ++Quad[0];
4741       ++Quad[1];
4742       ++Quad[2];
4743       ++Quad[3];
4744       continue;
4745     }
4746     ++Quad[EltIdx / 4];
4747     InputQuads.set(EltIdx / 4);
4748   }
4749
4750   int BestLoQuad = -1;
4751   unsigned MaxQuad = 1;
4752   for (unsigned i = 0; i < 4; ++i) {
4753     if (LoQuad[i] > MaxQuad) {
4754       BestLoQuad = i;
4755       MaxQuad = LoQuad[i];
4756     }
4757   }
4758
4759   int BestHiQuad = -1;
4760   MaxQuad = 1;
4761   for (unsigned i = 0; i < 4; ++i) {
4762     if (HiQuad[i] > MaxQuad) {
4763       BestHiQuad = i;
4764       MaxQuad = HiQuad[i];
4765     }
4766   }
4767
4768   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4769   // of the two input vectors, shuffle them into one input vector so only a
4770   // single pshufb instruction is necessary. If There are more than 2 input
4771   // quads, disable the next transformation since it does not help SSSE3.
4772   bool V1Used = InputQuads[0] || InputQuads[1];
4773   bool V2Used = InputQuads[2] || InputQuads[3];
4774   if (Subtarget->hasSSSE3()) {
4775     if (InputQuads.count() == 2 && V1Used && V2Used) {
4776       BestLoQuad = InputQuads.find_first();
4777       BestHiQuad = InputQuads.find_next(BestLoQuad);
4778     }
4779     if (InputQuads.count() > 2) {
4780       BestLoQuad = -1;
4781       BestHiQuad = -1;
4782     }
4783   }
4784
4785   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4786   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4787   // words from all 4 input quadwords.
4788   SDValue NewV;
4789   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4790     SmallVector<int, 8> MaskV;
4791     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4792     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4793     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4794                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4795                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4796     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4797
4798     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4799     // source words for the shuffle, to aid later transformations.
4800     bool AllWordsInNewV = true;
4801     bool InOrder[2] = { true, true };
4802     for (unsigned i = 0; i != 8; ++i) {
4803       int idx = MaskVals[i];
4804       if (idx != (int)i)
4805         InOrder[i/4] = false;
4806       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4807         continue;
4808       AllWordsInNewV = false;
4809       break;
4810     }
4811
4812     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4813     if (AllWordsInNewV) {
4814       for (int i = 0; i != 8; ++i) {
4815         int idx = MaskVals[i];
4816         if (idx < 0)
4817           continue;
4818         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4819         if ((idx != i) && idx < 4)
4820           pshufhw = false;
4821         if ((idx != i) && idx > 3)
4822           pshuflw = false;
4823       }
4824       V1 = NewV;
4825       V2Used = false;
4826       BestLoQuad = 0;
4827       BestHiQuad = 1;
4828     }
4829
4830     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4831     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4832     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4833       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4834       unsigned TargetMask = 0;
4835       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4836                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4837       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4838                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4839       V1 = NewV.getOperand(0);
4840       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4841     }
4842   }
4843
4844   // If we have SSSE3, and all words of the result are from 1 input vector,
4845   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4846   // is present, fall back to case 4.
4847   if (Subtarget->hasSSSE3()) {
4848     SmallVector<SDValue,16> pshufbMask;
4849
4850     // If we have elements from both input vectors, set the high bit of the
4851     // shuffle mask element to zero out elements that come from V2 in the V1
4852     // mask, and elements that come from V1 in the V2 mask, so that the two
4853     // results can be OR'd together.
4854     bool TwoInputs = V1Used && V2Used;
4855     for (unsigned i = 0; i != 8; ++i) {
4856       int EltIdx = MaskVals[i] * 2;
4857       if (TwoInputs && (EltIdx >= 16)) {
4858         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4859         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4860         continue;
4861       }
4862       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4863       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4864     }
4865     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4866     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4867                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4868                                  MVT::v16i8, &pshufbMask[0], 16));
4869     if (!TwoInputs)
4870       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4871
4872     // Calculate the shuffle mask for the second input, shuffle it, and
4873     // OR it with the first shuffled input.
4874     pshufbMask.clear();
4875     for (unsigned i = 0; i != 8; ++i) {
4876       int EltIdx = MaskVals[i] * 2;
4877       if (EltIdx < 16) {
4878         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4879         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4880         continue;
4881       }
4882       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4883       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4884     }
4885     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4886     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4887                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4888                                  MVT::v16i8, &pshufbMask[0], 16));
4889     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4890     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4891   }
4892
4893   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4894   // and update MaskVals with new element order.
4895   BitVector InOrder(8);
4896   if (BestLoQuad >= 0) {
4897     SmallVector<int, 8> MaskV;
4898     for (int i = 0; i != 4; ++i) {
4899       int idx = MaskVals[i];
4900       if (idx < 0) {
4901         MaskV.push_back(-1);
4902         InOrder.set(i);
4903       } else if ((idx / 4) == BestLoQuad) {
4904         MaskV.push_back(idx & 3);
4905         InOrder.set(i);
4906       } else {
4907         MaskV.push_back(-1);
4908       }
4909     }
4910     for (unsigned i = 4; i != 8; ++i)
4911       MaskV.push_back(i);
4912     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4913                                 &MaskV[0]);
4914
4915     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4916       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4917                                NewV.getOperand(0),
4918                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4919                                DAG);
4920   }
4921
4922   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4923   // and update MaskVals with the new element order.
4924   if (BestHiQuad >= 0) {
4925     SmallVector<int, 8> MaskV;
4926     for (unsigned i = 0; i != 4; ++i)
4927       MaskV.push_back(i);
4928     for (unsigned i = 4; i != 8; ++i) {
4929       int idx = MaskVals[i];
4930       if (idx < 0) {
4931         MaskV.push_back(-1);
4932         InOrder.set(i);
4933       } else if ((idx / 4) == BestHiQuad) {
4934         MaskV.push_back((idx & 3) + 4);
4935         InOrder.set(i);
4936       } else {
4937         MaskV.push_back(-1);
4938       }
4939     }
4940     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4941                                 &MaskV[0]);
4942
4943     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4944       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4945                               NewV.getOperand(0),
4946                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4947                               DAG);
4948   }
4949
4950   // In case BestHi & BestLo were both -1, which means each quadword has a word
4951   // from each of the four input quadwords, calculate the InOrder bitvector now
4952   // before falling through to the insert/extract cleanup.
4953   if (BestLoQuad == -1 && BestHiQuad == -1) {
4954     NewV = V1;
4955     for (int i = 0; i != 8; ++i)
4956       if (MaskVals[i] < 0 || MaskVals[i] == i)
4957         InOrder.set(i);
4958   }
4959
4960   // The other elements are put in the right place using pextrw and pinsrw.
4961   for (unsigned i = 0; i != 8; ++i) {
4962     if (InOrder[i])
4963       continue;
4964     int EltIdx = MaskVals[i];
4965     if (EltIdx < 0)
4966       continue;
4967     SDValue ExtOp = (EltIdx < 8)
4968     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4969                   DAG.getIntPtrConstant(EltIdx))
4970     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4971                   DAG.getIntPtrConstant(EltIdx - 8));
4972     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4973                        DAG.getIntPtrConstant(i));
4974   }
4975   return NewV;
4976 }
4977
4978 // v16i8 shuffles - Prefer shuffles in the following order:
4979 // 1. [ssse3] 1 x pshufb
4980 // 2. [ssse3] 2 x pshufb + 1 x por
4981 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4982 static
4983 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4984                                  SelectionDAG &DAG,
4985                                  const X86TargetLowering &TLI) {
4986   SDValue V1 = SVOp->getOperand(0);
4987   SDValue V2 = SVOp->getOperand(1);
4988   DebugLoc dl = SVOp->getDebugLoc();
4989   SmallVector<int, 16> MaskVals;
4990   SVOp->getMask(MaskVals);
4991
4992   // If we have SSSE3, case 1 is generated when all result bytes come from
4993   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4994   // present, fall back to case 3.
4995   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4996   bool V1Only = true;
4997   bool V2Only = true;
4998   for (unsigned i = 0; i < 16; ++i) {
4999     int EltIdx = MaskVals[i];
5000     if (EltIdx < 0)
5001       continue;
5002     if (EltIdx < 16)
5003       V2Only = false;
5004     else
5005       V1Only = false;
5006   }
5007
5008   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5009   if (TLI.getSubtarget()->hasSSSE3()) {
5010     SmallVector<SDValue,16> pshufbMask;
5011
5012     // If all result elements are from one input vector, then only translate
5013     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5014     //
5015     // Otherwise, we have elements from both input vectors, and must zero out
5016     // elements that come from V2 in the first mask, and V1 in the second mask
5017     // so that we can OR them together.
5018     bool TwoInputs = !(V1Only || V2Only);
5019     for (unsigned i = 0; i != 16; ++i) {
5020       int EltIdx = MaskVals[i];
5021       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5022         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5023         continue;
5024       }
5025       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5026     }
5027     // If all the elements are from V2, assign it to V1 and return after
5028     // building the first pshufb.
5029     if (V2Only)
5030       V1 = V2;
5031     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5032                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5033                                  MVT::v16i8, &pshufbMask[0], 16));
5034     if (!TwoInputs)
5035       return V1;
5036
5037     // Calculate the shuffle mask for the second input, shuffle it, and
5038     // OR it with the first shuffled input.
5039     pshufbMask.clear();
5040     for (unsigned i = 0; i != 16; ++i) {
5041       int EltIdx = MaskVals[i];
5042       if (EltIdx < 16) {
5043         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5044         continue;
5045       }
5046       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5047     }
5048     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5049                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5050                                  MVT::v16i8, &pshufbMask[0], 16));
5051     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5052   }
5053
5054   // No SSSE3 - Calculate in place words and then fix all out of place words
5055   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5056   // the 16 different words that comprise the two doublequadword input vectors.
5057   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5058   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5059   SDValue NewV = V2Only ? V2 : V1;
5060   for (int i = 0; i != 8; ++i) {
5061     int Elt0 = MaskVals[i*2];
5062     int Elt1 = MaskVals[i*2+1];
5063
5064     // This word of the result is all undef, skip it.
5065     if (Elt0 < 0 && Elt1 < 0)
5066       continue;
5067
5068     // This word of the result is already in the correct place, skip it.
5069     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5070       continue;
5071     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5072       continue;
5073
5074     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5075     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5076     SDValue InsElt;
5077
5078     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5079     // using a single extract together, load it and store it.
5080     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5081       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5082                            DAG.getIntPtrConstant(Elt1 / 2));
5083       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5084                         DAG.getIntPtrConstant(i));
5085       continue;
5086     }
5087
5088     // If Elt1 is defined, extract it from the appropriate source.  If the
5089     // source byte is not also odd, shift the extracted word left 8 bits
5090     // otherwise clear the bottom 8 bits if we need to do an or.
5091     if (Elt1 >= 0) {
5092       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5093                            DAG.getIntPtrConstant(Elt1 / 2));
5094       if ((Elt1 & 1) == 0)
5095         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5096                              DAG.getConstant(8,
5097                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5098       else if (Elt0 >= 0)
5099         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5100                              DAG.getConstant(0xFF00, MVT::i16));
5101     }
5102     // If Elt0 is defined, extract it from the appropriate source.  If the
5103     // source byte is not also even, shift the extracted word right 8 bits. If
5104     // Elt1 was also defined, OR the extracted values together before
5105     // inserting them in the result.
5106     if (Elt0 >= 0) {
5107       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5108                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5109       if ((Elt0 & 1) != 0)
5110         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5111                               DAG.getConstant(8,
5112                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5113       else if (Elt1 >= 0)
5114         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5115                              DAG.getConstant(0x00FF, MVT::i16));
5116       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5117                          : InsElt0;
5118     }
5119     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5120                        DAG.getIntPtrConstant(i));
5121   }
5122   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5123 }
5124
5125 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5126 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5127 /// done when every pair / quad of shuffle mask elements point to elements in
5128 /// the right sequence. e.g.
5129 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5130 static
5131 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5132                                  SelectionDAG &DAG, DebugLoc dl) {
5133   EVT VT = SVOp->getValueType(0);
5134   SDValue V1 = SVOp->getOperand(0);
5135   SDValue V2 = SVOp->getOperand(1);
5136   unsigned NumElems = VT.getVectorNumElements();
5137   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5138   EVT NewVT;
5139   switch (VT.getSimpleVT().SimpleTy) {
5140   default: assert(false && "Unexpected!");
5141   case MVT::v4f32: NewVT = MVT::v2f64; break;
5142   case MVT::v4i32: NewVT = MVT::v2i64; break;
5143   case MVT::v8i16: NewVT = MVT::v4i32; break;
5144   case MVT::v16i8: NewVT = MVT::v4i32; break;
5145   }
5146
5147   int Scale = NumElems / NewWidth;
5148   SmallVector<int, 8> MaskVec;
5149   for (unsigned i = 0; i < NumElems; i += Scale) {
5150     int StartIdx = -1;
5151     for (int j = 0; j < Scale; ++j) {
5152       int EltIdx = SVOp->getMaskElt(i+j);
5153       if (EltIdx < 0)
5154         continue;
5155       if (StartIdx == -1)
5156         StartIdx = EltIdx - (EltIdx % Scale);
5157       if (EltIdx != StartIdx + j)
5158         return SDValue();
5159     }
5160     if (StartIdx == -1)
5161       MaskVec.push_back(-1);
5162     else
5163       MaskVec.push_back(StartIdx / Scale);
5164   }
5165
5166   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5167   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5168   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5169 }
5170
5171 /// getVZextMovL - Return a zero-extending vector move low node.
5172 ///
5173 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5174                             SDValue SrcOp, SelectionDAG &DAG,
5175                             const X86Subtarget *Subtarget, DebugLoc dl) {
5176   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5177     LoadSDNode *LD = NULL;
5178     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5179       LD = dyn_cast<LoadSDNode>(SrcOp);
5180     if (!LD) {
5181       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5182       // instead.
5183       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5184       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5185           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5186           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5187           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5188         // PR2108
5189         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5190         return DAG.getNode(ISD::BITCAST, dl, VT,
5191                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5192                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5193                                                    OpVT,
5194                                                    SrcOp.getOperand(0)
5195                                                           .getOperand(0))));
5196       }
5197     }
5198   }
5199
5200   return DAG.getNode(ISD::BITCAST, dl, VT,
5201                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5202                                  DAG.getNode(ISD::BITCAST, dl,
5203                                              OpVT, SrcOp)));
5204 }
5205
5206 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5207 /// shuffles.
5208 static SDValue
5209 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5210   SDValue V1 = SVOp->getOperand(0);
5211   SDValue V2 = SVOp->getOperand(1);
5212   DebugLoc dl = SVOp->getDebugLoc();
5213   EVT VT = SVOp->getValueType(0);
5214
5215   SmallVector<std::pair<int, int>, 8> Locs;
5216   Locs.resize(4);
5217   SmallVector<int, 8> Mask1(4U, -1);
5218   SmallVector<int, 8> PermMask;
5219   SVOp->getMask(PermMask);
5220
5221   unsigned NumHi = 0;
5222   unsigned NumLo = 0;
5223   for (unsigned i = 0; i != 4; ++i) {
5224     int Idx = PermMask[i];
5225     if (Idx < 0) {
5226       Locs[i] = std::make_pair(-1, -1);
5227     } else {
5228       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5229       if (Idx < 4) {
5230         Locs[i] = std::make_pair(0, NumLo);
5231         Mask1[NumLo] = Idx;
5232         NumLo++;
5233       } else {
5234         Locs[i] = std::make_pair(1, NumHi);
5235         if (2+NumHi < 4)
5236           Mask1[2+NumHi] = Idx;
5237         NumHi++;
5238       }
5239     }
5240   }
5241
5242   if (NumLo <= 2 && NumHi <= 2) {
5243     // If no more than two elements come from either vector. This can be
5244     // implemented with two shuffles. First shuffle gather the elements.
5245     // The second shuffle, which takes the first shuffle as both of its
5246     // vector operands, put the elements into the right order.
5247     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5248
5249     SmallVector<int, 8> Mask2(4U, -1);
5250
5251     for (unsigned i = 0; i != 4; ++i) {
5252       if (Locs[i].first == -1)
5253         continue;
5254       else {
5255         unsigned Idx = (i < 2) ? 0 : 4;
5256         Idx += Locs[i].first * 2 + Locs[i].second;
5257         Mask2[i] = Idx;
5258       }
5259     }
5260
5261     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5262   } else if (NumLo == 3 || NumHi == 3) {
5263     // Otherwise, we must have three elements from one vector, call it X, and
5264     // one element from the other, call it Y.  First, use a shufps to build an
5265     // intermediate vector with the one element from Y and the element from X
5266     // that will be in the same half in the final destination (the indexes don't
5267     // matter). Then, use a shufps to build the final vector, taking the half
5268     // containing the element from Y from the intermediate, and the other half
5269     // from X.
5270     if (NumHi == 3) {
5271       // Normalize it so the 3 elements come from V1.
5272       CommuteVectorShuffleMask(PermMask, VT);
5273       std::swap(V1, V2);
5274     }
5275
5276     // Find the element from V2.
5277     unsigned HiIndex;
5278     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5279       int Val = PermMask[HiIndex];
5280       if (Val < 0)
5281         continue;
5282       if (Val >= 4)
5283         break;
5284     }
5285
5286     Mask1[0] = PermMask[HiIndex];
5287     Mask1[1] = -1;
5288     Mask1[2] = PermMask[HiIndex^1];
5289     Mask1[3] = -1;
5290     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5291
5292     if (HiIndex >= 2) {
5293       Mask1[0] = PermMask[0];
5294       Mask1[1] = PermMask[1];
5295       Mask1[2] = HiIndex & 1 ? 6 : 4;
5296       Mask1[3] = HiIndex & 1 ? 4 : 6;
5297       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5298     } else {
5299       Mask1[0] = HiIndex & 1 ? 2 : 0;
5300       Mask1[1] = HiIndex & 1 ? 0 : 2;
5301       Mask1[2] = PermMask[2];
5302       Mask1[3] = PermMask[3];
5303       if (Mask1[2] >= 0)
5304         Mask1[2] += 4;
5305       if (Mask1[3] >= 0)
5306         Mask1[3] += 4;
5307       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5308     }
5309   }
5310
5311   // Break it into (shuffle shuffle_hi, shuffle_lo).
5312   Locs.clear();
5313   Locs.resize(4);
5314   SmallVector<int,8> LoMask(4U, -1);
5315   SmallVector<int,8> HiMask(4U, -1);
5316
5317   SmallVector<int,8> *MaskPtr = &LoMask;
5318   unsigned MaskIdx = 0;
5319   unsigned LoIdx = 0;
5320   unsigned HiIdx = 2;
5321   for (unsigned i = 0; i != 4; ++i) {
5322     if (i == 2) {
5323       MaskPtr = &HiMask;
5324       MaskIdx = 1;
5325       LoIdx = 0;
5326       HiIdx = 2;
5327     }
5328     int Idx = PermMask[i];
5329     if (Idx < 0) {
5330       Locs[i] = std::make_pair(-1, -1);
5331     } else if (Idx < 4) {
5332       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5333       (*MaskPtr)[LoIdx] = Idx;
5334       LoIdx++;
5335     } else {
5336       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5337       (*MaskPtr)[HiIdx] = Idx;
5338       HiIdx++;
5339     }
5340   }
5341
5342   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5343   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5344   SmallVector<int, 8> MaskOps;
5345   for (unsigned i = 0; i != 4; ++i) {
5346     if (Locs[i].first == -1) {
5347       MaskOps.push_back(-1);
5348     } else {
5349       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5350       MaskOps.push_back(Idx);
5351     }
5352   }
5353   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5354 }
5355
5356 static bool MayFoldVectorLoad(SDValue V) {
5357   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5358     V = V.getOperand(0);
5359   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5360     V = V.getOperand(0);
5361   if (MayFoldLoad(V))
5362     return true;
5363   return false;
5364 }
5365
5366 // FIXME: the version above should always be used. Since there's
5367 // a bug where several vector shuffles can't be folded because the
5368 // DAG is not updated during lowering and a node claims to have two
5369 // uses while it only has one, use this version, and let isel match
5370 // another instruction if the load really happens to have more than
5371 // one use. Remove this version after this bug get fixed.
5372 // rdar://8434668, PR8156
5373 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5374   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5375     V = V.getOperand(0);
5376   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5377     V = V.getOperand(0);
5378   if (ISD::isNormalLoad(V.getNode()))
5379     return true;
5380   return false;
5381 }
5382
5383 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5384 /// a vector extract, and if both can be later optimized into a single load.
5385 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5386 /// here because otherwise a target specific shuffle node is going to be
5387 /// emitted for this shuffle, and the optimization not done.
5388 /// FIXME: This is probably not the best approach, but fix the problem
5389 /// until the right path is decided.
5390 static
5391 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5392                                          const TargetLowering &TLI) {
5393   EVT VT = V.getValueType();
5394   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5395
5396   // Be sure that the vector shuffle is present in a pattern like this:
5397   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5398   if (!V.hasOneUse())
5399     return false;
5400
5401   SDNode *N = *V.getNode()->use_begin();
5402   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5403     return false;
5404
5405   SDValue EltNo = N->getOperand(1);
5406   if (!isa<ConstantSDNode>(EltNo))
5407     return false;
5408
5409   // If the bit convert changed the number of elements, it is unsafe
5410   // to examine the mask.
5411   bool HasShuffleIntoBitcast = false;
5412   if (V.getOpcode() == ISD::BITCAST) {
5413     EVT SrcVT = V.getOperand(0).getValueType();
5414     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5415       return false;
5416     V = V.getOperand(0);
5417     HasShuffleIntoBitcast = true;
5418   }
5419
5420   // Select the input vector, guarding against out of range extract vector.
5421   unsigned NumElems = VT.getVectorNumElements();
5422   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5423   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5424   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5425
5426   // Skip one more bit_convert if necessary
5427   if (V.getOpcode() == ISD::BITCAST)
5428     V = V.getOperand(0);
5429
5430   if (ISD::isNormalLoad(V.getNode())) {
5431     // Is the original load suitable?
5432     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5433
5434     // FIXME: avoid the multi-use bug that is preventing lots of
5435     // of foldings to be detected, this is still wrong of course, but
5436     // give the temporary desired behavior, and if it happens that
5437     // the load has real more uses, during isel it will not fold, and
5438     // will generate poor code.
5439     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5440       return false;
5441
5442     if (!HasShuffleIntoBitcast)
5443       return true;
5444
5445     // If there's a bitcast before the shuffle, check if the load type and
5446     // alignment is valid.
5447     unsigned Align = LN0->getAlignment();
5448     unsigned NewAlign =
5449       TLI.getTargetData()->getABITypeAlignment(
5450                                     VT.getTypeForEVT(*DAG.getContext()));
5451
5452     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5453       return false;
5454   }
5455
5456   return true;
5457 }
5458
5459 static
5460 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5461   EVT VT = Op.getValueType();
5462
5463   // Canonizalize to v2f64.
5464   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5465   return DAG.getNode(ISD::BITCAST, dl, VT,
5466                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5467                                           V1, DAG));
5468 }
5469
5470 static
5471 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5472                         bool HasSSE2) {
5473   SDValue V1 = Op.getOperand(0);
5474   SDValue V2 = Op.getOperand(1);
5475   EVT VT = Op.getValueType();
5476
5477   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5478
5479   if (HasSSE2 && VT == MVT::v2f64)
5480     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5481
5482   // v4f32 or v4i32
5483   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5484 }
5485
5486 static
5487 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5488   SDValue V1 = Op.getOperand(0);
5489   SDValue V2 = Op.getOperand(1);
5490   EVT VT = Op.getValueType();
5491
5492   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5493          "unsupported shuffle type");
5494
5495   if (V2.getOpcode() == ISD::UNDEF)
5496     V2 = V1;
5497
5498   // v4i32 or v4f32
5499   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5500 }
5501
5502 static
5503 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5504   SDValue V1 = Op.getOperand(0);
5505   SDValue V2 = Op.getOperand(1);
5506   EVT VT = Op.getValueType();
5507   unsigned NumElems = VT.getVectorNumElements();
5508
5509   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5510   // operand of these instructions is only memory, so check if there's a
5511   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5512   // same masks.
5513   bool CanFoldLoad = false;
5514
5515   // Trivial case, when V2 comes from a load.
5516   if (MayFoldVectorLoad(V2))
5517     CanFoldLoad = true;
5518
5519   // When V1 is a load, it can be folded later into a store in isel, example:
5520   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5521   //    turns into:
5522   //  (MOVLPSmr addr:$src1, VR128:$src2)
5523   // So, recognize this potential and also use MOVLPS or MOVLPD
5524   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5525     CanFoldLoad = true;
5526
5527   // Both of them can't be memory operations though.
5528   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5529     CanFoldLoad = false;
5530
5531   if (CanFoldLoad) {
5532     if (HasSSE2 && NumElems == 2)
5533       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5534
5535     if (NumElems == 4)
5536       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5537   }
5538
5539   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5540   // movl and movlp will both match v2i64, but v2i64 is never matched by
5541   // movl earlier because we make it strict to avoid messing with the movlp load
5542   // folding logic (see the code above getMOVLP call). Match it here then,
5543   // this is horrible, but will stay like this until we move all shuffle
5544   // matching to x86 specific nodes. Note that for the 1st condition all
5545   // types are matched with movsd.
5546   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5547     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5548   else if (HasSSE2)
5549     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5550
5551
5552   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5553
5554   // Invert the operand order and use SHUFPS to match it.
5555   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5556                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5557 }
5558
5559 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5560   switch(VT.getSimpleVT().SimpleTy) {
5561   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5562   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5563   case MVT::v4f32:
5564     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5565   case MVT::v2f64:
5566     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5567   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5568   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5569   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5570   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5571   default:
5572     llvm_unreachable("Unknown type for unpckl");
5573   }
5574   return 0;
5575 }
5576
5577 static inline unsigned getUNPCKHOpcode(EVT VT) {
5578   switch(VT.getSimpleVT().SimpleTy) {
5579   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5580   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5581   case MVT::v4f32: return X86ISD::UNPCKHPS;
5582   case MVT::v2f64: return X86ISD::UNPCKHPD;
5583   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5584   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5585   default:
5586     llvm_unreachable("Unknown type for unpckh");
5587   }
5588   return 0;
5589 }
5590
5591 static
5592 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5593                                const TargetLowering &TLI,
5594                                const X86Subtarget *Subtarget) {
5595   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5596   EVT VT = Op.getValueType();
5597   DebugLoc dl = Op.getDebugLoc();
5598   SDValue V1 = Op.getOperand(0);
5599   SDValue V2 = Op.getOperand(1);
5600
5601   if (isZeroShuffle(SVOp))
5602     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5603
5604   // Handle splat operations
5605   if (SVOp->isSplat()) {
5606     // Special case, this is the only place now where it's
5607     // allowed to return a vector_shuffle operation without
5608     // using a target specific node, because *hopefully* it
5609     // will be optimized away by the dag combiner.
5610     if (VT.getVectorNumElements() <= 4 &&
5611         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5612       return Op;
5613
5614     // Handle splats by matching through known masks
5615     if (VT.getVectorNumElements() <= 4)
5616       return SDValue();
5617
5618     // Canonicalize all of the remaining to v4f32.
5619     return PromoteSplat(SVOp, DAG);
5620   }
5621
5622   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5623   // do it!
5624   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5625     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5626     if (NewOp.getNode())
5627       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5628   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5629     // FIXME: Figure out a cleaner way to do this.
5630     // Try to make use of movq to zero out the top part.
5631     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5632       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5633       if (NewOp.getNode()) {
5634         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5635           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5636                               DAG, Subtarget, dl);
5637       }
5638     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5639       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5640       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5641         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5642                             DAG, Subtarget, dl);
5643     }
5644   }
5645   return SDValue();
5646 }
5647
5648 SDValue
5649 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5650   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5651   SDValue V1 = Op.getOperand(0);
5652   SDValue V2 = Op.getOperand(1);
5653   EVT VT = Op.getValueType();
5654   DebugLoc dl = Op.getDebugLoc();
5655   unsigned NumElems = VT.getVectorNumElements();
5656   bool isMMX = VT.getSizeInBits() == 64;
5657   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5658   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5659   bool V1IsSplat = false;
5660   bool V2IsSplat = false;
5661   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5662   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5663   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5664   MachineFunction &MF = DAG.getMachineFunction();
5665   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5666
5667   // Shuffle operations on MMX not supported.
5668   if (isMMX)
5669     return Op;
5670
5671   // Vector shuffle lowering takes 3 steps:
5672   //
5673   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5674   //    narrowing and commutation of operands should be handled.
5675   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5676   //    shuffle nodes.
5677   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5678   //    so the shuffle can be broken into other shuffles and the legalizer can
5679   //    try the lowering again.
5680   //
5681   // The general ideia is that no vector_shuffle operation should be left to
5682   // be matched during isel, all of them must be converted to a target specific
5683   // node here.
5684
5685   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5686   // narrowing and commutation of operands should be handled. The actual code
5687   // doesn't include all of those, work in progress...
5688   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5689   if (NewOp.getNode())
5690     return NewOp;
5691
5692   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5693   // unpckh_undef). Only use pshufd if speed is more important than size.
5694   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5695     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5696       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5697   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5698     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5699       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5700
5701   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5702       RelaxedMayFoldVectorLoad(V1))
5703     return getMOVDDup(Op, dl, V1, DAG);
5704
5705   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5706     return getMOVHighToLow(Op, dl, DAG);
5707
5708   // Use to match splats
5709   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5710       (VT == MVT::v2f64 || VT == MVT::v2i64))
5711     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5712
5713   if (X86::isPSHUFDMask(SVOp)) {
5714     // The actual implementation will match the mask in the if above and then
5715     // during isel it can match several different instructions, not only pshufd
5716     // as its name says, sad but true, emulate the behavior for now...
5717     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5718         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5719
5720     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5721
5722     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5723       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5724
5725     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5726       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5727                                   TargetMask, DAG);
5728
5729     if (VT == MVT::v4f32)
5730       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5731                                   TargetMask, DAG);
5732   }
5733
5734   // Check if this can be converted into a logical shift.
5735   bool isLeft = false;
5736   unsigned ShAmt = 0;
5737   SDValue ShVal;
5738   bool isShift = getSubtarget()->hasSSE2() &&
5739     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5740   if (isShift && ShVal.hasOneUse()) {
5741     // If the shifted value has multiple uses, it may be cheaper to use
5742     // v_set0 + movlhps or movhlps, etc.
5743     EVT EltVT = VT.getVectorElementType();
5744     ShAmt *= EltVT.getSizeInBits();
5745     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5746   }
5747
5748   if (X86::isMOVLMask(SVOp)) {
5749     if (V1IsUndef)
5750       return V2;
5751     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5752       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5753     if (!X86::isMOVLPMask(SVOp)) {
5754       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5755         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5756
5757       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5758         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5759     }
5760   }
5761
5762   // FIXME: fold these into legal mask.
5763   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5764     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5765
5766   if (X86::isMOVHLPSMask(SVOp))
5767     return getMOVHighToLow(Op, dl, DAG);
5768
5769   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5770     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5771
5772   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5773     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5774
5775   if (X86::isMOVLPMask(SVOp))
5776     return getMOVLP(Op, dl, DAG, HasSSE2);
5777
5778   if (ShouldXformToMOVHLPS(SVOp) ||
5779       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5780     return CommuteVectorShuffle(SVOp, DAG);
5781
5782   if (isShift) {
5783     // No better options. Use a vshl / vsrl.
5784     EVT EltVT = VT.getVectorElementType();
5785     ShAmt *= EltVT.getSizeInBits();
5786     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5787   }
5788
5789   bool Commuted = false;
5790   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5791   // 1,1,1,1 -> v8i16 though.
5792   V1IsSplat = isSplatVector(V1.getNode());
5793   V2IsSplat = isSplatVector(V2.getNode());
5794
5795   // Canonicalize the splat or undef, if present, to be on the RHS.
5796   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5797     Op = CommuteVectorShuffle(SVOp, DAG);
5798     SVOp = cast<ShuffleVectorSDNode>(Op);
5799     V1 = SVOp->getOperand(0);
5800     V2 = SVOp->getOperand(1);
5801     std::swap(V1IsSplat, V2IsSplat);
5802     std::swap(V1IsUndef, V2IsUndef);
5803     Commuted = true;
5804   }
5805
5806   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5807     // Shuffling low element of v1 into undef, just return v1.
5808     if (V2IsUndef)
5809       return V1;
5810     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5811     // the instruction selector will not match, so get a canonical MOVL with
5812     // swapped operands to undo the commute.
5813     return getMOVL(DAG, dl, VT, V2, V1);
5814   }
5815
5816   if (X86::isUNPCKLMask(SVOp))
5817     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5818                                 dl, VT, V1, V2, DAG);
5819
5820   if (X86::isUNPCKHMask(SVOp))
5821     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5822
5823   if (V2IsSplat) {
5824     // Normalize mask so all entries that point to V2 points to its first
5825     // element then try to match unpck{h|l} again. If match, return a
5826     // new vector_shuffle with the corrected mask.
5827     SDValue NewMask = NormalizeMask(SVOp, DAG);
5828     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5829     if (NSVOp != SVOp) {
5830       if (X86::isUNPCKLMask(NSVOp, true)) {
5831         return NewMask;
5832       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5833         return NewMask;
5834       }
5835     }
5836   }
5837
5838   if (Commuted) {
5839     // Commute is back and try unpck* again.
5840     // FIXME: this seems wrong.
5841     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5842     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5843
5844     if (X86::isUNPCKLMask(NewSVOp))
5845       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5846                                   dl, VT, V2, V1, DAG);
5847
5848     if (X86::isUNPCKHMask(NewSVOp))
5849       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5850   }
5851
5852   // Normalize the node to match x86 shuffle ops if needed
5853   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5854     return CommuteVectorShuffle(SVOp, DAG);
5855
5856   // The checks below are all present in isShuffleMaskLegal, but they are
5857   // inlined here right now to enable us to directly emit target specific
5858   // nodes, and remove one by one until they don't return Op anymore.
5859   SmallVector<int, 16> M;
5860   SVOp->getMask(M);
5861
5862   if (isPALIGNRMask(M, VT, HasSSSE3))
5863     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5864                                 X86::getShufflePALIGNRImmediate(SVOp),
5865                                 DAG);
5866
5867   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5868       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5869     if (VT == MVT::v2f64) {
5870       X86ISD::NodeType Opcode =
5871         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5872       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5873     }
5874     if (VT == MVT::v2i64)
5875       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5876   }
5877
5878   if (isPSHUFHWMask(M, VT))
5879     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5880                                 X86::getShufflePSHUFHWImmediate(SVOp),
5881                                 DAG);
5882
5883   if (isPSHUFLWMask(M, VT))
5884     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5885                                 X86::getShufflePSHUFLWImmediate(SVOp),
5886                                 DAG);
5887
5888   if (isSHUFPMask(M, VT)) {
5889     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5890     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5891       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5892                                   TargetMask, DAG);
5893     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5894       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5895                                   TargetMask, DAG);
5896   }
5897
5898   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5899     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5900       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5901                                   dl, VT, V1, V1, DAG);
5902   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5903     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5904       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5905
5906   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5907   if (VT == MVT::v8i16) {
5908     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5909     if (NewOp.getNode())
5910       return NewOp;
5911   }
5912
5913   if (VT == MVT::v16i8) {
5914     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5915     if (NewOp.getNode())
5916       return NewOp;
5917   }
5918
5919   // Handle all 4 wide cases with a number of shuffles.
5920   if (NumElems == 4)
5921     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5922
5923   return SDValue();
5924 }
5925
5926 SDValue
5927 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5928                                                 SelectionDAG &DAG) const {
5929   EVT VT = Op.getValueType();
5930   DebugLoc dl = Op.getDebugLoc();
5931   if (VT.getSizeInBits() == 8) {
5932     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5933                                     Op.getOperand(0), Op.getOperand(1));
5934     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5935                                     DAG.getValueType(VT));
5936     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5937   } else if (VT.getSizeInBits() == 16) {
5938     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5939     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5940     if (Idx == 0)
5941       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5942                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5943                                      DAG.getNode(ISD::BITCAST, dl,
5944                                                  MVT::v4i32,
5945                                                  Op.getOperand(0)),
5946                                      Op.getOperand(1)));
5947     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5948                                     Op.getOperand(0), Op.getOperand(1));
5949     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5950                                     DAG.getValueType(VT));
5951     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5952   } else if (VT == MVT::f32) {
5953     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5954     // the result back to FR32 register. It's only worth matching if the
5955     // result has a single use which is a store or a bitcast to i32.  And in
5956     // the case of a store, it's not worth it if the index is a constant 0,
5957     // because a MOVSSmr can be used instead, which is smaller and faster.
5958     if (!Op.hasOneUse())
5959       return SDValue();
5960     SDNode *User = *Op.getNode()->use_begin();
5961     if ((User->getOpcode() != ISD::STORE ||
5962          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5963           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5964         (User->getOpcode() != ISD::BITCAST ||
5965          User->getValueType(0) != MVT::i32))
5966       return SDValue();
5967     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5968                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5969                                               Op.getOperand(0)),
5970                                               Op.getOperand(1));
5971     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5972   } else if (VT == MVT::i32) {
5973     // ExtractPS works with constant index.
5974     if (isa<ConstantSDNode>(Op.getOperand(1)))
5975       return Op;
5976   }
5977   return SDValue();
5978 }
5979
5980
5981 SDValue
5982 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5983                                            SelectionDAG &DAG) const {
5984   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5985     return SDValue();
5986
5987   SDValue Vec = Op.getOperand(0);
5988   EVT VecVT = Vec.getValueType();
5989
5990   // If this is a 256-bit vector result, first extract the 128-bit
5991   // vector and then extract from the 128-bit vector.
5992   if (VecVT.getSizeInBits() > 128) {
5993     DebugLoc dl = Op.getNode()->getDebugLoc();
5994     unsigned NumElems = VecVT.getVectorNumElements();
5995     SDValue Idx = Op.getOperand(1);
5996
5997     if (!isa<ConstantSDNode>(Idx))
5998       return SDValue();
5999
6000     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6001     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6002
6003     // Get the 128-bit vector.
6004     bool Upper = IdxVal >= ExtractNumElems;
6005     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6006
6007     // Extract from it.
6008     SDValue ScaledIdx = Idx;
6009     if (Upper)
6010       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6011                               DAG.getConstant(ExtractNumElems,
6012                                               Idx.getValueType()));
6013     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6014                        ScaledIdx);
6015   }
6016
6017   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6018
6019   if (Subtarget->hasSSE41()) {
6020     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6021     if (Res.getNode())
6022       return Res;
6023   }
6024
6025   EVT VT = Op.getValueType();
6026   DebugLoc dl = Op.getDebugLoc();
6027   // TODO: handle v16i8.
6028   if (VT.getSizeInBits() == 16) {
6029     SDValue Vec = Op.getOperand(0);
6030     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6031     if (Idx == 0)
6032       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6033                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6034                                      DAG.getNode(ISD::BITCAST, dl,
6035                                                  MVT::v4i32, Vec),
6036                                      Op.getOperand(1)));
6037     // Transform it so it match pextrw which produces a 32-bit result.
6038     EVT EltVT = MVT::i32;
6039     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6040                                     Op.getOperand(0), Op.getOperand(1));
6041     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6042                                     DAG.getValueType(VT));
6043     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6044   } else if (VT.getSizeInBits() == 32) {
6045     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6046     if (Idx == 0)
6047       return Op;
6048
6049     // SHUFPS the element to the lowest double word, then movss.
6050     int Mask[4] = { Idx, -1, -1, -1 };
6051     EVT VVT = Op.getOperand(0).getValueType();
6052     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6053                                        DAG.getUNDEF(VVT), Mask);
6054     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6055                        DAG.getIntPtrConstant(0));
6056   } else if (VT.getSizeInBits() == 64) {
6057     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6058     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6059     //        to match extract_elt for f64.
6060     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6061     if (Idx == 0)
6062       return Op;
6063
6064     // UNPCKHPD the element to the lowest double word, then movsd.
6065     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6066     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6067     int Mask[2] = { 1, -1 };
6068     EVT VVT = Op.getOperand(0).getValueType();
6069     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6070                                        DAG.getUNDEF(VVT), Mask);
6071     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6072                        DAG.getIntPtrConstant(0));
6073   }
6074
6075   return SDValue();
6076 }
6077
6078 SDValue
6079 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6080                                                SelectionDAG &DAG) const {
6081   EVT VT = Op.getValueType();
6082   EVT EltVT = VT.getVectorElementType();
6083   DebugLoc dl = Op.getDebugLoc();
6084
6085   SDValue N0 = Op.getOperand(0);
6086   SDValue N1 = Op.getOperand(1);
6087   SDValue N2 = Op.getOperand(2);
6088
6089   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6090       isa<ConstantSDNode>(N2)) {
6091     unsigned Opc;
6092     if (VT == MVT::v8i16)
6093       Opc = X86ISD::PINSRW;
6094     else if (VT == MVT::v16i8)
6095       Opc = X86ISD::PINSRB;
6096     else
6097       Opc = X86ISD::PINSRB;
6098
6099     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6100     // argument.
6101     if (N1.getValueType() != MVT::i32)
6102       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6103     if (N2.getValueType() != MVT::i32)
6104       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6105     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6106   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6107     // Bits [7:6] of the constant are the source select.  This will always be
6108     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6109     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6110     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6111     // Bits [5:4] of the constant are the destination select.  This is the
6112     //  value of the incoming immediate.
6113     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6114     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6115     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6116     // Create this as a scalar to vector..
6117     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6118     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6119   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6120     // PINSR* works with constant index.
6121     return Op;
6122   }
6123   return SDValue();
6124 }
6125
6126 SDValue
6127 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6128   EVT VT = Op.getValueType();
6129   EVT EltVT = VT.getVectorElementType();
6130
6131   DebugLoc dl = Op.getDebugLoc();
6132   SDValue N0 = Op.getOperand(0);
6133   SDValue N1 = Op.getOperand(1);
6134   SDValue N2 = Op.getOperand(2);
6135
6136   // If this is a 256-bit vector result, first insert into a 128-bit
6137   // vector and then insert into the 256-bit vector.
6138   if (VT.getSizeInBits() > 128) {
6139     if (!isa<ConstantSDNode>(N2))
6140       return SDValue();
6141
6142     // Get the 128-bit vector.
6143     unsigned NumElems = VT.getVectorNumElements();
6144     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6145     bool Upper = IdxVal >= NumElems / 2;
6146
6147     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6148
6149     // Insert into it.
6150     SDValue ScaledN2 = N2;
6151     if (Upper)
6152       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6153                              DAG.getConstant(NumElems /
6154                                              (VT.getSizeInBits() / 128),
6155                                              N2.getValueType()));
6156     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6157                      N1, ScaledN2);
6158
6159     // Insert the 128-bit vector
6160     // FIXME: Why UNDEF?
6161     return Insert128BitVector(N0, Op, N2, DAG, dl);
6162   }
6163
6164   if (Subtarget->hasSSE41())
6165     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6166
6167   if (EltVT == MVT::i8)
6168     return SDValue();
6169
6170   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6171     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6172     // as its second argument.
6173     if (N1.getValueType() != MVT::i32)
6174       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6175     if (N2.getValueType() != MVT::i32)
6176       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6177     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6178   }
6179   return SDValue();
6180 }
6181
6182 SDValue
6183 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6184   LLVMContext *Context = DAG.getContext();
6185   DebugLoc dl = Op.getDebugLoc();
6186   EVT OpVT = Op.getValueType();
6187
6188   // If this is a 256-bit vector result, first insert into a 128-bit
6189   // vector and then insert into the 256-bit vector.
6190   if (OpVT.getSizeInBits() > 128) {
6191     // Insert into a 128-bit vector.
6192     EVT VT128 = EVT::getVectorVT(*Context,
6193                                  OpVT.getVectorElementType(),
6194                                  OpVT.getVectorNumElements() / 2);
6195
6196     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6197
6198     // Insert the 128-bit vector.
6199     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6200                               DAG.getConstant(0, MVT::i32),
6201                               DAG, dl);
6202   }
6203
6204   if (Op.getValueType() == MVT::v1i64 &&
6205       Op.getOperand(0).getValueType() == MVT::i64)
6206     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6207
6208   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6209   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6210          "Expected an SSE type!");
6211   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6212                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6213 }
6214
6215 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6216 // a simple subregister reference or explicit instructions to grab
6217 // upper bits of a vector.
6218 SDValue
6219 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6220   if (Subtarget->hasAVX()) {
6221     DebugLoc dl = Op.getNode()->getDebugLoc();
6222     SDValue Vec = Op.getNode()->getOperand(0);
6223     SDValue Idx = Op.getNode()->getOperand(1);
6224
6225     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6226         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6227         return Extract128BitVector(Vec, Idx, DAG, dl);
6228     }
6229   }
6230   return SDValue();
6231 }
6232
6233 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6234 // simple superregister reference or explicit instructions to insert
6235 // the upper bits of a vector.
6236 SDValue
6237 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6238   if (Subtarget->hasAVX()) {
6239     DebugLoc dl = Op.getNode()->getDebugLoc();
6240     SDValue Vec = Op.getNode()->getOperand(0);
6241     SDValue SubVec = Op.getNode()->getOperand(1);
6242     SDValue Idx = Op.getNode()->getOperand(2);
6243
6244     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6245         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6246       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6247     }
6248   }
6249   return SDValue();
6250 }
6251
6252 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6253 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6254 // one of the above mentioned nodes. It has to be wrapped because otherwise
6255 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6256 // be used to form addressing mode. These wrapped nodes will be selected
6257 // into MOV32ri.
6258 SDValue
6259 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6260   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6261
6262   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6263   // global base reg.
6264   unsigned char OpFlag = 0;
6265   unsigned WrapperKind = X86ISD::Wrapper;
6266   CodeModel::Model M = getTargetMachine().getCodeModel();
6267
6268   if (Subtarget->isPICStyleRIPRel() &&
6269       (M == CodeModel::Small || M == CodeModel::Kernel))
6270     WrapperKind = X86ISD::WrapperRIP;
6271   else if (Subtarget->isPICStyleGOT())
6272     OpFlag = X86II::MO_GOTOFF;
6273   else if (Subtarget->isPICStyleStubPIC())
6274     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6275
6276   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6277                                              CP->getAlignment(),
6278                                              CP->getOffset(), OpFlag);
6279   DebugLoc DL = CP->getDebugLoc();
6280   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6281   // With PIC, the address is actually $g + Offset.
6282   if (OpFlag) {
6283     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6284                          DAG.getNode(X86ISD::GlobalBaseReg,
6285                                      DebugLoc(), getPointerTy()),
6286                          Result);
6287   }
6288
6289   return Result;
6290 }
6291
6292 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6293   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6294
6295   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6296   // global base reg.
6297   unsigned char OpFlag = 0;
6298   unsigned WrapperKind = X86ISD::Wrapper;
6299   CodeModel::Model M = getTargetMachine().getCodeModel();
6300
6301   if (Subtarget->isPICStyleRIPRel() &&
6302       (M == CodeModel::Small || M == CodeModel::Kernel))
6303     WrapperKind = X86ISD::WrapperRIP;
6304   else if (Subtarget->isPICStyleGOT())
6305     OpFlag = X86II::MO_GOTOFF;
6306   else if (Subtarget->isPICStyleStubPIC())
6307     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6308
6309   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6310                                           OpFlag);
6311   DebugLoc DL = JT->getDebugLoc();
6312   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6313
6314   // With PIC, the address is actually $g + Offset.
6315   if (OpFlag)
6316     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6317                          DAG.getNode(X86ISD::GlobalBaseReg,
6318                                      DebugLoc(), getPointerTy()),
6319                          Result);
6320
6321   return Result;
6322 }
6323
6324 SDValue
6325 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6326   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6327
6328   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6329   // global base reg.
6330   unsigned char OpFlag = 0;
6331   unsigned WrapperKind = X86ISD::Wrapper;
6332   CodeModel::Model M = getTargetMachine().getCodeModel();
6333
6334   if (Subtarget->isPICStyleRIPRel() &&
6335       (M == CodeModel::Small || M == CodeModel::Kernel))
6336     WrapperKind = X86ISD::WrapperRIP;
6337   else if (Subtarget->isPICStyleGOT())
6338     OpFlag = X86II::MO_GOTOFF;
6339   else if (Subtarget->isPICStyleStubPIC())
6340     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6341
6342   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6343
6344   DebugLoc DL = Op.getDebugLoc();
6345   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6346
6347
6348   // With PIC, the address is actually $g + Offset.
6349   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6350       !Subtarget->is64Bit()) {
6351     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6352                          DAG.getNode(X86ISD::GlobalBaseReg,
6353                                      DebugLoc(), getPointerTy()),
6354                          Result);
6355   }
6356
6357   return Result;
6358 }
6359
6360 SDValue
6361 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6362   // Create the TargetBlockAddressAddress node.
6363   unsigned char OpFlags =
6364     Subtarget->ClassifyBlockAddressReference();
6365   CodeModel::Model M = getTargetMachine().getCodeModel();
6366   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6367   DebugLoc dl = Op.getDebugLoc();
6368   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6369                                        /*isTarget=*/true, OpFlags);
6370
6371   if (Subtarget->isPICStyleRIPRel() &&
6372       (M == CodeModel::Small || M == CodeModel::Kernel))
6373     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6374   else
6375     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6376
6377   // With PIC, the address is actually $g + Offset.
6378   if (isGlobalRelativeToPICBase(OpFlags)) {
6379     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6380                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6381                          Result);
6382   }
6383
6384   return Result;
6385 }
6386
6387 SDValue
6388 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6389                                       int64_t Offset,
6390                                       SelectionDAG &DAG) const {
6391   // Create the TargetGlobalAddress node, folding in the constant
6392   // offset if it is legal.
6393   unsigned char OpFlags =
6394     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6395   CodeModel::Model M = getTargetMachine().getCodeModel();
6396   SDValue Result;
6397   if (OpFlags == X86II::MO_NO_FLAG &&
6398       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6399     // A direct static reference to a global.
6400     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6401     Offset = 0;
6402   } else {
6403     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6404   }
6405
6406   if (Subtarget->isPICStyleRIPRel() &&
6407       (M == CodeModel::Small || M == CodeModel::Kernel))
6408     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6409   else
6410     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6411
6412   // With PIC, the address is actually $g + Offset.
6413   if (isGlobalRelativeToPICBase(OpFlags)) {
6414     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6415                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6416                          Result);
6417   }
6418
6419   // For globals that require a load from a stub to get the address, emit the
6420   // load.
6421   if (isGlobalStubReference(OpFlags))
6422     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6423                          MachinePointerInfo::getGOT(), false, false, 0);
6424
6425   // If there was a non-zero offset that we didn't fold, create an explicit
6426   // addition for it.
6427   if (Offset != 0)
6428     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6429                          DAG.getConstant(Offset, getPointerTy()));
6430
6431   return Result;
6432 }
6433
6434 SDValue
6435 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6436   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6437   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6438   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6439 }
6440
6441 static SDValue
6442 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6443            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6444            unsigned char OperandFlags) {
6445   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6446   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6447   DebugLoc dl = GA->getDebugLoc();
6448   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6449                                            GA->getValueType(0),
6450                                            GA->getOffset(),
6451                                            OperandFlags);
6452   if (InFlag) {
6453     SDValue Ops[] = { Chain,  TGA, *InFlag };
6454     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6455   } else {
6456     SDValue Ops[]  = { Chain, TGA };
6457     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6458   }
6459
6460   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6461   MFI->setAdjustsStack(true);
6462
6463   SDValue Flag = Chain.getValue(1);
6464   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6465 }
6466
6467 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6468 static SDValue
6469 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6470                                 const EVT PtrVT) {
6471   SDValue InFlag;
6472   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6473   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6474                                      DAG.getNode(X86ISD::GlobalBaseReg,
6475                                                  DebugLoc(), PtrVT), InFlag);
6476   InFlag = Chain.getValue(1);
6477
6478   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6479 }
6480
6481 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6482 static SDValue
6483 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6484                                 const EVT PtrVT) {
6485   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6486                     X86::RAX, X86II::MO_TLSGD);
6487 }
6488
6489 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6490 // "local exec" model.
6491 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6492                                    const EVT PtrVT, TLSModel::Model model,
6493                                    bool is64Bit) {
6494   DebugLoc dl = GA->getDebugLoc();
6495
6496   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6497   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6498                                                          is64Bit ? 257 : 256));
6499
6500   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6501                                       DAG.getIntPtrConstant(0),
6502                                       MachinePointerInfo(Ptr), false, false, 0);
6503
6504   unsigned char OperandFlags = 0;
6505   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6506   // initialexec.
6507   unsigned WrapperKind = X86ISD::Wrapper;
6508   if (model == TLSModel::LocalExec) {
6509     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6510   } else if (is64Bit) {
6511     assert(model == TLSModel::InitialExec);
6512     OperandFlags = X86II::MO_GOTTPOFF;
6513     WrapperKind = X86ISD::WrapperRIP;
6514   } else {
6515     assert(model == TLSModel::InitialExec);
6516     OperandFlags = X86II::MO_INDNTPOFF;
6517   }
6518
6519   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6520   // exec)
6521   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6522                                            GA->getValueType(0),
6523                                            GA->getOffset(), OperandFlags);
6524   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6525
6526   if (model == TLSModel::InitialExec)
6527     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6528                          MachinePointerInfo::getGOT(), false, false, 0);
6529
6530   // The address of the thread local variable is the add of the thread
6531   // pointer with the offset of the variable.
6532   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6533 }
6534
6535 SDValue
6536 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6537
6538   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6539   const GlobalValue *GV = GA->getGlobal();
6540
6541   if (Subtarget->isTargetELF()) {
6542     // TODO: implement the "local dynamic" model
6543     // TODO: implement the "initial exec"model for pic executables
6544
6545     // If GV is an alias then use the aliasee for determining
6546     // thread-localness.
6547     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6548       GV = GA->resolveAliasedGlobal(false);
6549
6550     TLSModel::Model model
6551       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6552
6553     switch (model) {
6554       case TLSModel::GeneralDynamic:
6555       case TLSModel::LocalDynamic: // not implemented
6556         if (Subtarget->is64Bit())
6557           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6558         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6559
6560       case TLSModel::InitialExec:
6561       case TLSModel::LocalExec:
6562         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6563                                    Subtarget->is64Bit());
6564     }
6565   } else if (Subtarget->isTargetDarwin()) {
6566     // Darwin only has one model of TLS.  Lower to that.
6567     unsigned char OpFlag = 0;
6568     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6569                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6570
6571     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6572     // global base reg.
6573     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6574                   !Subtarget->is64Bit();
6575     if (PIC32)
6576       OpFlag = X86II::MO_TLVP_PIC_BASE;
6577     else
6578       OpFlag = X86II::MO_TLVP;
6579     DebugLoc DL = Op.getDebugLoc();
6580     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6581                                                 GA->getValueType(0),
6582                                                 GA->getOffset(), OpFlag);
6583     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6584
6585     // With PIC32, the address is actually $g + Offset.
6586     if (PIC32)
6587       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6588                            DAG.getNode(X86ISD::GlobalBaseReg,
6589                                        DebugLoc(), getPointerTy()),
6590                            Offset);
6591
6592     // Lowering the machine isd will make sure everything is in the right
6593     // location.
6594     SDValue Chain = DAG.getEntryNode();
6595     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6596     SDValue Args[] = { Chain, Offset };
6597     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6598
6599     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6600     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6601     MFI->setAdjustsStack(true);
6602
6603     // And our return value (tls address) is in the standard call return value
6604     // location.
6605     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6606     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6607   }
6608
6609   assert(false &&
6610          "TLS not implemented for this target.");
6611
6612   llvm_unreachable("Unreachable");
6613   return SDValue();
6614 }
6615
6616
6617 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6618 /// take a 2 x i32 value to shift plus a shift amount.
6619 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6620   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6621   EVT VT = Op.getValueType();
6622   unsigned VTBits = VT.getSizeInBits();
6623   DebugLoc dl = Op.getDebugLoc();
6624   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6625   SDValue ShOpLo = Op.getOperand(0);
6626   SDValue ShOpHi = Op.getOperand(1);
6627   SDValue ShAmt  = Op.getOperand(2);
6628   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6629                                      DAG.getConstant(VTBits - 1, MVT::i8))
6630                        : DAG.getConstant(0, VT);
6631
6632   SDValue Tmp2, Tmp3;
6633   if (Op.getOpcode() == ISD::SHL_PARTS) {
6634     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6635     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6636   } else {
6637     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6638     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6639   }
6640
6641   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6642                                 DAG.getConstant(VTBits, MVT::i8));
6643   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6644                              AndNode, DAG.getConstant(0, MVT::i8));
6645
6646   SDValue Hi, Lo;
6647   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6648   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6649   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6650
6651   if (Op.getOpcode() == ISD::SHL_PARTS) {
6652     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6653     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6654   } else {
6655     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6656     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6657   }
6658
6659   SDValue Ops[2] = { Lo, Hi };
6660   return DAG.getMergeValues(Ops, 2, dl);
6661 }
6662
6663 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6664                                            SelectionDAG &DAG) const {
6665   EVT SrcVT = Op.getOperand(0).getValueType();
6666
6667   if (SrcVT.isVector())
6668     return SDValue();
6669
6670   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6671          "Unknown SINT_TO_FP to lower!");
6672
6673   // These are really Legal; return the operand so the caller accepts it as
6674   // Legal.
6675   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6676     return Op;
6677   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6678       Subtarget->is64Bit()) {
6679     return Op;
6680   }
6681
6682   DebugLoc dl = Op.getDebugLoc();
6683   unsigned Size = SrcVT.getSizeInBits()/8;
6684   MachineFunction &MF = DAG.getMachineFunction();
6685   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6686   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6687   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6688                                StackSlot,
6689                                MachinePointerInfo::getFixedStack(SSFI),
6690                                false, false, 0);
6691   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6692 }
6693
6694 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6695                                      SDValue StackSlot,
6696                                      SelectionDAG &DAG) const {
6697   // Build the FILD
6698   DebugLoc DL = Op.getDebugLoc();
6699   SDVTList Tys;
6700   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6701   if (useSSE)
6702     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6703   else
6704     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6705
6706   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6707
6708   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6709   MachineMemOperand *MMO =
6710     DAG.getMachineFunction()
6711     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6712                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6713
6714   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6715   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6716                                            X86ISD::FILD, DL,
6717                                            Tys, Ops, array_lengthof(Ops),
6718                                            SrcVT, MMO);
6719
6720   if (useSSE) {
6721     Chain = Result.getValue(1);
6722     SDValue InFlag = Result.getValue(2);
6723
6724     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6725     // shouldn't be necessary except that RFP cannot be live across
6726     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6727     MachineFunction &MF = DAG.getMachineFunction();
6728     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6729     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6730     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6731     Tys = DAG.getVTList(MVT::Other);
6732     SDValue Ops[] = {
6733       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6734     };
6735     MachineMemOperand *MMO =
6736       DAG.getMachineFunction()
6737       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6738                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6739
6740     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6741                                     Ops, array_lengthof(Ops),
6742                                     Op.getValueType(), MMO);
6743     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6744                          MachinePointerInfo::getFixedStack(SSFI),
6745                          false, false, 0);
6746   }
6747
6748   return Result;
6749 }
6750
6751 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6752 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6753                                                SelectionDAG &DAG) const {
6754   // This algorithm is not obvious. Here it is in C code, more or less:
6755   /*
6756     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6757       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6758       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6759
6760       // Copy ints to xmm registers.
6761       __m128i xh = _mm_cvtsi32_si128( hi );
6762       __m128i xl = _mm_cvtsi32_si128( lo );
6763
6764       // Combine into low half of a single xmm register.
6765       __m128i x = _mm_unpacklo_epi32( xh, xl );
6766       __m128d d;
6767       double sd;
6768
6769       // Merge in appropriate exponents to give the integer bits the right
6770       // magnitude.
6771       x = _mm_unpacklo_epi32( x, exp );
6772
6773       // Subtract away the biases to deal with the IEEE-754 double precision
6774       // implicit 1.
6775       d = _mm_sub_pd( (__m128d) x, bias );
6776
6777       // All conversions up to here are exact. The correctly rounded result is
6778       // calculated using the current rounding mode using the following
6779       // horizontal add.
6780       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6781       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6782                                 // store doesn't really need to be here (except
6783                                 // maybe to zero the other double)
6784       return sd;
6785     }
6786   */
6787
6788   DebugLoc dl = Op.getDebugLoc();
6789   LLVMContext *Context = DAG.getContext();
6790
6791   // Build some magic constants.
6792   std::vector<Constant*> CV0;
6793   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6794   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6795   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6796   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6797   Constant *C0 = ConstantVector::get(CV0);
6798   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6799
6800   std::vector<Constant*> CV1;
6801   CV1.push_back(
6802     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6803   CV1.push_back(
6804     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6805   Constant *C1 = ConstantVector::get(CV1);
6806   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6807
6808   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6809                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6810                                         Op.getOperand(0),
6811                                         DAG.getIntPtrConstant(1)));
6812   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6813                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6814                                         Op.getOperand(0),
6815                                         DAG.getIntPtrConstant(0)));
6816   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6817   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6818                               MachinePointerInfo::getConstantPool(),
6819                               false, false, 16);
6820   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6821   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6822   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6823                               MachinePointerInfo::getConstantPool(),
6824                               false, false, 16);
6825   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6826
6827   // Add the halves; easiest way is to swap them into another reg first.
6828   int ShufMask[2] = { 1, -1 };
6829   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6830                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6831   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6832   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6833                      DAG.getIntPtrConstant(0));
6834 }
6835
6836 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6837 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6838                                                SelectionDAG &DAG) const {
6839   DebugLoc dl = Op.getDebugLoc();
6840   // FP constant to bias correct the final result.
6841   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6842                                    MVT::f64);
6843
6844   // Load the 32-bit value into an XMM register.
6845   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6846                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6847                                          Op.getOperand(0),
6848                                          DAG.getIntPtrConstant(0)));
6849
6850   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6851                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6852                      DAG.getIntPtrConstant(0));
6853
6854   // Or the load with the bias.
6855   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6856                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6857                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6858                                                    MVT::v2f64, Load)),
6859                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6860                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6861                                                    MVT::v2f64, Bias)));
6862   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6863                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6864                    DAG.getIntPtrConstant(0));
6865
6866   // Subtract the bias.
6867   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6868
6869   // Handle final rounding.
6870   EVT DestVT = Op.getValueType();
6871
6872   if (DestVT.bitsLT(MVT::f64)) {
6873     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6874                        DAG.getIntPtrConstant(0));
6875   } else if (DestVT.bitsGT(MVT::f64)) {
6876     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6877   }
6878
6879   // Handle final rounding.
6880   return Sub;
6881 }
6882
6883 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6884                                            SelectionDAG &DAG) const {
6885   SDValue N0 = Op.getOperand(0);
6886   DebugLoc dl = Op.getDebugLoc();
6887
6888   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6889   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6890   // the optimization here.
6891   if (DAG.SignBitIsZero(N0))
6892     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6893
6894   EVT SrcVT = N0.getValueType();
6895   EVT DstVT = Op.getValueType();
6896   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6897     return LowerUINT_TO_FP_i64(Op, DAG);
6898   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6899     return LowerUINT_TO_FP_i32(Op, DAG);
6900
6901   // Make a 64-bit buffer, and use it to build an FILD.
6902   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6903   if (SrcVT == MVT::i32) {
6904     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6905     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6906                                      getPointerTy(), StackSlot, WordOff);
6907     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6908                                   StackSlot, MachinePointerInfo(),
6909                                   false, false, 0);
6910     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6911                                   OffsetSlot, MachinePointerInfo(),
6912                                   false, false, 0);
6913     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6914     return Fild;
6915   }
6916
6917   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6918   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6919                                 StackSlot, MachinePointerInfo(),
6920                                false, false, 0);
6921   // For i64 source, we need to add the appropriate power of 2 if the input
6922   // was negative.  This is the same as the optimization in
6923   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6924   // we must be careful to do the computation in x87 extended precision, not
6925   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6926   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6927   MachineMemOperand *MMO =
6928     DAG.getMachineFunction()
6929     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6930                           MachineMemOperand::MOLoad, 8, 8);
6931
6932   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6933   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6934   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6935                                          MVT::i64, MMO);
6936
6937   APInt FF(32, 0x5F800000ULL);
6938
6939   // Check whether the sign bit is set.
6940   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6941                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6942                                  ISD::SETLT);
6943
6944   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6945   SDValue FudgePtr = DAG.getConstantPool(
6946                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6947                                          getPointerTy());
6948
6949   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6950   SDValue Zero = DAG.getIntPtrConstant(0);
6951   SDValue Four = DAG.getIntPtrConstant(4);
6952   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6953                                Zero, Four);
6954   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6955
6956   // Load the value out, extending it from f32 to f80.
6957   // FIXME: Avoid the extend by constructing the right constant pool?
6958   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6959                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6960                                  MVT::f32, false, false, 4);
6961   // Extend everything to 80 bits to force it to be done on x87.
6962   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6963   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6964 }
6965
6966 std::pair<SDValue,SDValue> X86TargetLowering::
6967 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6968   DebugLoc DL = Op.getDebugLoc();
6969
6970   EVT DstTy = Op.getValueType();
6971
6972   if (!IsSigned) {
6973     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6974     DstTy = MVT::i64;
6975   }
6976
6977   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6978          DstTy.getSimpleVT() >= MVT::i16 &&
6979          "Unknown FP_TO_SINT to lower!");
6980
6981   // These are really Legal.
6982   if (DstTy == MVT::i32 &&
6983       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6984     return std::make_pair(SDValue(), SDValue());
6985   if (Subtarget->is64Bit() &&
6986       DstTy == MVT::i64 &&
6987       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6988     return std::make_pair(SDValue(), SDValue());
6989
6990   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6991   // stack slot.
6992   MachineFunction &MF = DAG.getMachineFunction();
6993   unsigned MemSize = DstTy.getSizeInBits()/8;
6994   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6995   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6996
6997
6998
6999   unsigned Opc;
7000   switch (DstTy.getSimpleVT().SimpleTy) {
7001   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7002   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7003   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7004   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7005   }
7006
7007   SDValue Chain = DAG.getEntryNode();
7008   SDValue Value = Op.getOperand(0);
7009   EVT TheVT = Op.getOperand(0).getValueType();
7010   if (isScalarFPTypeInSSEReg(TheVT)) {
7011     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7012     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7013                          MachinePointerInfo::getFixedStack(SSFI),
7014                          false, false, 0);
7015     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7016     SDValue Ops[] = {
7017       Chain, StackSlot, DAG.getValueType(TheVT)
7018     };
7019
7020     MachineMemOperand *MMO =
7021       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7022                               MachineMemOperand::MOLoad, MemSize, MemSize);
7023     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7024                                     DstTy, MMO);
7025     Chain = Value.getValue(1);
7026     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7027     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7028   }
7029
7030   MachineMemOperand *MMO =
7031     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7032                             MachineMemOperand::MOStore, MemSize, MemSize);
7033
7034   // Build the FP_TO_INT*_IN_MEM
7035   SDValue Ops[] = { Chain, Value, StackSlot };
7036   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7037                                          Ops, 3, DstTy, MMO);
7038
7039   return std::make_pair(FIST, StackSlot);
7040 }
7041
7042 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7043                                            SelectionDAG &DAG) const {
7044   if (Op.getValueType().isVector())
7045     return SDValue();
7046
7047   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7048   SDValue FIST = Vals.first, StackSlot = Vals.second;
7049   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7050   if (FIST.getNode() == 0) return Op;
7051
7052   // Load the result.
7053   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7054                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7055 }
7056
7057 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7058                                            SelectionDAG &DAG) const {
7059   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7060   SDValue FIST = Vals.first, StackSlot = Vals.second;
7061   assert(FIST.getNode() && "Unexpected failure");
7062
7063   // Load the result.
7064   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7065                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7066 }
7067
7068 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7069                                      SelectionDAG &DAG) const {
7070   LLVMContext *Context = DAG.getContext();
7071   DebugLoc dl = Op.getDebugLoc();
7072   EVT VT = Op.getValueType();
7073   EVT EltVT = VT;
7074   if (VT.isVector())
7075     EltVT = VT.getVectorElementType();
7076   std::vector<Constant*> CV;
7077   if (EltVT == MVT::f64) {
7078     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7079     CV.push_back(C);
7080     CV.push_back(C);
7081   } else {
7082     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7083     CV.push_back(C);
7084     CV.push_back(C);
7085     CV.push_back(C);
7086     CV.push_back(C);
7087   }
7088   Constant *C = ConstantVector::get(CV);
7089   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7090   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7091                              MachinePointerInfo::getConstantPool(),
7092                              false, false, 16);
7093   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7094 }
7095
7096 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7097   LLVMContext *Context = DAG.getContext();
7098   DebugLoc dl = Op.getDebugLoc();
7099   EVT VT = Op.getValueType();
7100   EVT EltVT = VT;
7101   if (VT.isVector())
7102     EltVT = VT.getVectorElementType();
7103   std::vector<Constant*> CV;
7104   if (EltVT == MVT::f64) {
7105     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7106     CV.push_back(C);
7107     CV.push_back(C);
7108   } else {
7109     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7110     CV.push_back(C);
7111     CV.push_back(C);
7112     CV.push_back(C);
7113     CV.push_back(C);
7114   }
7115   Constant *C = ConstantVector::get(CV);
7116   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7117   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7118                              MachinePointerInfo::getConstantPool(),
7119                              false, false, 16);
7120   if (VT.isVector()) {
7121     return DAG.getNode(ISD::BITCAST, dl, VT,
7122                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7123                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7124                                 Op.getOperand(0)),
7125                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7126   } else {
7127     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7128   }
7129 }
7130
7131 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7132   LLVMContext *Context = DAG.getContext();
7133   SDValue Op0 = Op.getOperand(0);
7134   SDValue Op1 = Op.getOperand(1);
7135   DebugLoc dl = Op.getDebugLoc();
7136   EVT VT = Op.getValueType();
7137   EVT SrcVT = Op1.getValueType();
7138
7139   // If second operand is smaller, extend it first.
7140   if (SrcVT.bitsLT(VT)) {
7141     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7142     SrcVT = VT;
7143   }
7144   // And if it is bigger, shrink it first.
7145   if (SrcVT.bitsGT(VT)) {
7146     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7147     SrcVT = VT;
7148   }
7149
7150   // At this point the operands and the result should have the same
7151   // type, and that won't be f80 since that is not custom lowered.
7152
7153   // First get the sign bit of second operand.
7154   std::vector<Constant*> CV;
7155   if (SrcVT == MVT::f64) {
7156     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7157     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7158   } else {
7159     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7160     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7161     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7162     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7163   }
7164   Constant *C = ConstantVector::get(CV);
7165   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7166   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7167                               MachinePointerInfo::getConstantPool(),
7168                               false, false, 16);
7169   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7170
7171   // Shift sign bit right or left if the two operands have different types.
7172   if (SrcVT.bitsGT(VT)) {
7173     // Op0 is MVT::f32, Op1 is MVT::f64.
7174     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7175     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7176                           DAG.getConstant(32, MVT::i32));
7177     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7178     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7179                           DAG.getIntPtrConstant(0));
7180   }
7181
7182   // Clear first operand sign bit.
7183   CV.clear();
7184   if (VT == MVT::f64) {
7185     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7186     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7187   } else {
7188     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7189     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7190     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7191     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7192   }
7193   C = ConstantVector::get(CV);
7194   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7195   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7196                               MachinePointerInfo::getConstantPool(),
7197                               false, false, 16);
7198   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7199
7200   // Or the value with the sign bit.
7201   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7202 }
7203
7204 /// Emit nodes that will be selected as "test Op0,Op0", or something
7205 /// equivalent.
7206 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7207                                     SelectionDAG &DAG) const {
7208   DebugLoc dl = Op.getDebugLoc();
7209
7210   // CF and OF aren't always set the way we want. Determine which
7211   // of these we need.
7212   bool NeedCF = false;
7213   bool NeedOF = false;
7214   switch (X86CC) {
7215   default: break;
7216   case X86::COND_A: case X86::COND_AE:
7217   case X86::COND_B: case X86::COND_BE:
7218     NeedCF = true;
7219     break;
7220   case X86::COND_G: case X86::COND_GE:
7221   case X86::COND_L: case X86::COND_LE:
7222   case X86::COND_O: case X86::COND_NO:
7223     NeedOF = true;
7224     break;
7225   }
7226
7227   // See if we can use the EFLAGS value from the operand instead of
7228   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7229   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7230   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7231     // Emit a CMP with 0, which is the TEST pattern.
7232     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7233                        DAG.getConstant(0, Op.getValueType()));
7234
7235   unsigned Opcode = 0;
7236   unsigned NumOperands = 0;
7237   switch (Op.getNode()->getOpcode()) {
7238   case ISD::ADD:
7239     // Due to an isel shortcoming, be conservative if this add is likely to be
7240     // selected as part of a load-modify-store instruction. When the root node
7241     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7242     // uses of other nodes in the match, such as the ADD in this case. This
7243     // leads to the ADD being left around and reselected, with the result being
7244     // two adds in the output.  Alas, even if none our users are stores, that
7245     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7246     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7247     // climbing the DAG back to the root, and it doesn't seem to be worth the
7248     // effort.
7249     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7250            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7251       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7252         goto default_case;
7253
7254     if (ConstantSDNode *C =
7255         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7256       // An add of one will be selected as an INC.
7257       if (C->getAPIntValue() == 1) {
7258         Opcode = X86ISD::INC;
7259         NumOperands = 1;
7260         break;
7261       }
7262
7263       // An add of negative one (subtract of one) will be selected as a DEC.
7264       if (C->getAPIntValue().isAllOnesValue()) {
7265         Opcode = X86ISD::DEC;
7266         NumOperands = 1;
7267         break;
7268       }
7269     }
7270
7271     // Otherwise use a regular EFLAGS-setting add.
7272     Opcode = X86ISD::ADD;
7273     NumOperands = 2;
7274     break;
7275   case ISD::AND: {
7276     // If the primary and result isn't used, don't bother using X86ISD::AND,
7277     // because a TEST instruction will be better.
7278     bool NonFlagUse = false;
7279     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7280            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7281       SDNode *User = *UI;
7282       unsigned UOpNo = UI.getOperandNo();
7283       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7284         // Look pass truncate.
7285         UOpNo = User->use_begin().getOperandNo();
7286         User = *User->use_begin();
7287       }
7288
7289       if (User->getOpcode() != ISD::BRCOND &&
7290           User->getOpcode() != ISD::SETCC &&
7291           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7292         NonFlagUse = true;
7293         break;
7294       }
7295     }
7296
7297     if (!NonFlagUse)
7298       break;
7299   }
7300     // FALL THROUGH
7301   case ISD::SUB:
7302   case ISD::OR:
7303   case ISD::XOR:
7304     // Due to the ISEL shortcoming noted above, be conservative if this op is
7305     // likely to be selected as part of a load-modify-store instruction.
7306     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7307            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7308       if (UI->getOpcode() == ISD::STORE)
7309         goto default_case;
7310
7311     // Otherwise use a regular EFLAGS-setting instruction.
7312     switch (Op.getNode()->getOpcode()) {
7313     default: llvm_unreachable("unexpected operator!");
7314     case ISD::SUB: Opcode = X86ISD::SUB; break;
7315     case ISD::OR:  Opcode = X86ISD::OR;  break;
7316     case ISD::XOR: Opcode = X86ISD::XOR; break;
7317     case ISD::AND: Opcode = X86ISD::AND; break;
7318     }
7319
7320     NumOperands = 2;
7321     break;
7322   case X86ISD::ADD:
7323   case X86ISD::SUB:
7324   case X86ISD::INC:
7325   case X86ISD::DEC:
7326   case X86ISD::OR:
7327   case X86ISD::XOR:
7328   case X86ISD::AND:
7329     return SDValue(Op.getNode(), 1);
7330   default:
7331   default_case:
7332     break;
7333   }
7334
7335   if (Opcode == 0)
7336     // Emit a CMP with 0, which is the TEST pattern.
7337     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7338                        DAG.getConstant(0, Op.getValueType()));
7339
7340   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7341   SmallVector<SDValue, 4> Ops;
7342   for (unsigned i = 0; i != NumOperands; ++i)
7343     Ops.push_back(Op.getOperand(i));
7344
7345   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7346   DAG.ReplaceAllUsesWith(Op, New);
7347   return SDValue(New.getNode(), 1);
7348 }
7349
7350 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7351 /// equivalent.
7352 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7353                                    SelectionDAG &DAG) const {
7354   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7355     if (C->getAPIntValue() == 0)
7356       return EmitTest(Op0, X86CC, DAG);
7357
7358   DebugLoc dl = Op0.getDebugLoc();
7359   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7360 }
7361
7362 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7363 /// if it's possible.
7364 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7365                                      DebugLoc dl, SelectionDAG &DAG) const {
7366   SDValue Op0 = And.getOperand(0);
7367   SDValue Op1 = And.getOperand(1);
7368   if (Op0.getOpcode() == ISD::TRUNCATE)
7369     Op0 = Op0.getOperand(0);
7370   if (Op1.getOpcode() == ISD::TRUNCATE)
7371     Op1 = Op1.getOperand(0);
7372
7373   SDValue LHS, RHS;
7374   if (Op1.getOpcode() == ISD::SHL)
7375     std::swap(Op0, Op1);
7376   if (Op0.getOpcode() == ISD::SHL) {
7377     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7378       if (And00C->getZExtValue() == 1) {
7379         // If we looked past a truncate, check that it's only truncating away
7380         // known zeros.
7381         unsigned BitWidth = Op0.getValueSizeInBits();
7382         unsigned AndBitWidth = And.getValueSizeInBits();
7383         if (BitWidth > AndBitWidth) {
7384           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7385           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7386           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7387             return SDValue();
7388         }
7389         LHS = Op1;
7390         RHS = Op0.getOperand(1);
7391       }
7392   } else if (Op1.getOpcode() == ISD::Constant) {
7393     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7394     SDValue AndLHS = Op0;
7395     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7396       LHS = AndLHS.getOperand(0);
7397       RHS = AndLHS.getOperand(1);
7398     }
7399   }
7400
7401   if (LHS.getNode()) {
7402     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7403     // instruction.  Since the shift amount is in-range-or-undefined, we know
7404     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7405     // the encoding for the i16 version is larger than the i32 version.
7406     // Also promote i16 to i32 for performance / code size reason.
7407     if (LHS.getValueType() == MVT::i8 ||
7408         LHS.getValueType() == MVT::i16)
7409       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7410
7411     // If the operand types disagree, extend the shift amount to match.  Since
7412     // BT ignores high bits (like shifts) we can use anyextend.
7413     if (LHS.getValueType() != RHS.getValueType())
7414       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7415
7416     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7417     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7418     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7419                        DAG.getConstant(Cond, MVT::i8), BT);
7420   }
7421
7422   return SDValue();
7423 }
7424
7425 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7426   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7427   SDValue Op0 = Op.getOperand(0);
7428   SDValue Op1 = Op.getOperand(1);
7429   DebugLoc dl = Op.getDebugLoc();
7430   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7431
7432   // Optimize to BT if possible.
7433   // Lower (X & (1 << N)) == 0 to BT(X, N).
7434   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7435   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7436   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7437       Op1.getOpcode() == ISD::Constant &&
7438       cast<ConstantSDNode>(Op1)->isNullValue() &&
7439       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7440     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7441     if (NewSetCC.getNode())
7442       return NewSetCC;
7443   }
7444
7445   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7446   // these.
7447   if (Op1.getOpcode() == ISD::Constant &&
7448       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7449        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7450       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7451
7452     // If the input is a setcc, then reuse the input setcc or use a new one with
7453     // the inverted condition.
7454     if (Op0.getOpcode() == X86ISD::SETCC) {
7455       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7456       bool Invert = (CC == ISD::SETNE) ^
7457         cast<ConstantSDNode>(Op1)->isNullValue();
7458       if (!Invert) return Op0;
7459
7460       CCode = X86::GetOppositeBranchCondition(CCode);
7461       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7462                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7463     }
7464   }
7465
7466   bool isFP = Op1.getValueType().isFloatingPoint();
7467   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7468   if (X86CC == X86::COND_INVALID)
7469     return SDValue();
7470
7471   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7472   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7473                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7474 }
7475
7476 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7477   SDValue Cond;
7478   SDValue Op0 = Op.getOperand(0);
7479   SDValue Op1 = Op.getOperand(1);
7480   SDValue CC = Op.getOperand(2);
7481   EVT VT = Op.getValueType();
7482   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7483   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7484   DebugLoc dl = Op.getDebugLoc();
7485
7486   if (isFP) {
7487     unsigned SSECC = 8;
7488     EVT VT0 = Op0.getValueType();
7489     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7490     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7491     bool Swap = false;
7492
7493     switch (SetCCOpcode) {
7494     default: break;
7495     case ISD::SETOEQ:
7496     case ISD::SETEQ:  SSECC = 0; break;
7497     case ISD::SETOGT:
7498     case ISD::SETGT: Swap = true; // Fallthrough
7499     case ISD::SETLT:
7500     case ISD::SETOLT: SSECC = 1; break;
7501     case ISD::SETOGE:
7502     case ISD::SETGE: Swap = true; // Fallthrough
7503     case ISD::SETLE:
7504     case ISD::SETOLE: SSECC = 2; break;
7505     case ISD::SETUO:  SSECC = 3; break;
7506     case ISD::SETUNE:
7507     case ISD::SETNE:  SSECC = 4; break;
7508     case ISD::SETULE: Swap = true;
7509     case ISD::SETUGE: SSECC = 5; break;
7510     case ISD::SETULT: Swap = true;
7511     case ISD::SETUGT: SSECC = 6; break;
7512     case ISD::SETO:   SSECC = 7; break;
7513     }
7514     if (Swap)
7515       std::swap(Op0, Op1);
7516
7517     // In the two special cases we can't handle, emit two comparisons.
7518     if (SSECC == 8) {
7519       if (SetCCOpcode == ISD::SETUEQ) {
7520         SDValue UNORD, EQ;
7521         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7522         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7523         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7524       }
7525       else if (SetCCOpcode == ISD::SETONE) {
7526         SDValue ORD, NEQ;
7527         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7528         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7529         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7530       }
7531       llvm_unreachable("Illegal FP comparison");
7532     }
7533     // Handle all other FP comparisons here.
7534     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7535   }
7536
7537   // We are handling one of the integer comparisons here.  Since SSE only has
7538   // GT and EQ comparisons for integer, swapping operands and multiple
7539   // operations may be required for some comparisons.
7540   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7541   bool Swap = false, Invert = false, FlipSigns = false;
7542
7543   switch (VT.getSimpleVT().SimpleTy) {
7544   default: break;
7545   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7546   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7547   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7548   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7549   }
7550
7551   switch (SetCCOpcode) {
7552   default: break;
7553   case ISD::SETNE:  Invert = true;
7554   case ISD::SETEQ:  Opc = EQOpc; break;
7555   case ISD::SETLT:  Swap = true;
7556   case ISD::SETGT:  Opc = GTOpc; break;
7557   case ISD::SETGE:  Swap = true;
7558   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7559   case ISD::SETULT: Swap = true;
7560   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7561   case ISD::SETUGE: Swap = true;
7562   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7563   }
7564   if (Swap)
7565     std::swap(Op0, Op1);
7566
7567   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7568   // bits of the inputs before performing those operations.
7569   if (FlipSigns) {
7570     EVT EltVT = VT.getVectorElementType();
7571     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7572                                       EltVT);
7573     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7574     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7575                                     SignBits.size());
7576     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7577     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7578   }
7579
7580   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7581
7582   // If the logical-not of the result is required, perform that now.
7583   if (Invert)
7584     Result = DAG.getNOT(dl, Result, VT);
7585
7586   return Result;
7587 }
7588
7589 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7590 static bool isX86LogicalCmp(SDValue Op) {
7591   unsigned Opc = Op.getNode()->getOpcode();
7592   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7593     return true;
7594   if (Op.getResNo() == 1 &&
7595       (Opc == X86ISD::ADD ||
7596        Opc == X86ISD::SUB ||
7597        Opc == X86ISD::ADC ||
7598        Opc == X86ISD::SBB ||
7599        Opc == X86ISD::SMUL ||
7600        Opc == X86ISD::UMUL ||
7601        Opc == X86ISD::INC ||
7602        Opc == X86ISD::DEC ||
7603        Opc == X86ISD::OR ||
7604        Opc == X86ISD::XOR ||
7605        Opc == X86ISD::AND))
7606     return true;
7607
7608   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7609     return true;
7610
7611   return false;
7612 }
7613
7614 static bool isZero(SDValue V) {
7615   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7616   return C && C->isNullValue();
7617 }
7618
7619 static bool isAllOnes(SDValue V) {
7620   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7621   return C && C->isAllOnesValue();
7622 }
7623
7624 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7625   bool addTest = true;
7626   SDValue Cond  = Op.getOperand(0);
7627   SDValue Op1 = Op.getOperand(1);
7628   SDValue Op2 = Op.getOperand(2);
7629   DebugLoc DL = Op.getDebugLoc();
7630   SDValue CC;
7631
7632   if (Cond.getOpcode() == ISD::SETCC) {
7633     SDValue NewCond = LowerSETCC(Cond, DAG);
7634     if (NewCond.getNode())
7635       Cond = NewCond;
7636   }
7637
7638   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7639   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7640   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7641   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7642   if (Cond.getOpcode() == X86ISD::SETCC &&
7643       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7644       isZero(Cond.getOperand(1).getOperand(1))) {
7645     SDValue Cmp = Cond.getOperand(1);
7646
7647     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7648
7649     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7650         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7651       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7652
7653       SDValue CmpOp0 = Cmp.getOperand(0);
7654       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7655                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7656
7657       SDValue Res =   // Res = 0 or -1.
7658         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7659                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7660
7661       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7662         Res = DAG.getNOT(DL, Res, Res.getValueType());
7663
7664       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7665       if (N2C == 0 || !N2C->isNullValue())
7666         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7667       return Res;
7668     }
7669   }
7670
7671   // Look past (and (setcc_carry (cmp ...)), 1).
7672   if (Cond.getOpcode() == ISD::AND &&
7673       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7674     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7675     if (C && C->getAPIntValue() == 1)
7676       Cond = Cond.getOperand(0);
7677   }
7678
7679   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7680   // setting operand in place of the X86ISD::SETCC.
7681   if (Cond.getOpcode() == X86ISD::SETCC ||
7682       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7683     CC = Cond.getOperand(0);
7684
7685     SDValue Cmp = Cond.getOperand(1);
7686     unsigned Opc = Cmp.getOpcode();
7687     EVT VT = Op.getValueType();
7688
7689     bool IllegalFPCMov = false;
7690     if (VT.isFloatingPoint() && !VT.isVector() &&
7691         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7692       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7693
7694     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7695         Opc == X86ISD::BT) { // FIXME
7696       Cond = Cmp;
7697       addTest = false;
7698     }
7699   }
7700
7701   if (addTest) {
7702     // Look pass the truncate.
7703     if (Cond.getOpcode() == ISD::TRUNCATE)
7704       Cond = Cond.getOperand(0);
7705
7706     // We know the result of AND is compared against zero. Try to match
7707     // it to BT.
7708     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7709       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7710       if (NewSetCC.getNode()) {
7711         CC = NewSetCC.getOperand(0);
7712         Cond = NewSetCC.getOperand(1);
7713         addTest = false;
7714       }
7715     }
7716   }
7717
7718   if (addTest) {
7719     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7720     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7721   }
7722
7723   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7724   // a <  b ?  0 : -1 -> RES = setcc_carry
7725   // a >= b ? -1 :  0 -> RES = setcc_carry
7726   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7727   if (Cond.getOpcode() == X86ISD::CMP) {
7728     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7729
7730     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7731         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7732       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7733                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7734       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7735         return DAG.getNOT(DL, Res, Res.getValueType());
7736       return Res;
7737     }
7738   }
7739
7740   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7741   // condition is true.
7742   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7743   SDValue Ops[] = { Op2, Op1, CC, Cond };
7744   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7745 }
7746
7747 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7748 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7749 // from the AND / OR.
7750 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7751   Opc = Op.getOpcode();
7752   if (Opc != ISD::OR && Opc != ISD::AND)
7753     return false;
7754   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7755           Op.getOperand(0).hasOneUse() &&
7756           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7757           Op.getOperand(1).hasOneUse());
7758 }
7759
7760 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7761 // 1 and that the SETCC node has a single use.
7762 static bool isXor1OfSetCC(SDValue Op) {
7763   if (Op.getOpcode() != ISD::XOR)
7764     return false;
7765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7766   if (N1C && N1C->getAPIntValue() == 1) {
7767     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7768       Op.getOperand(0).hasOneUse();
7769   }
7770   return false;
7771 }
7772
7773 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7774   bool addTest = true;
7775   SDValue Chain = Op.getOperand(0);
7776   SDValue Cond  = Op.getOperand(1);
7777   SDValue Dest  = Op.getOperand(2);
7778   DebugLoc dl = Op.getDebugLoc();
7779   SDValue CC;
7780
7781   if (Cond.getOpcode() == ISD::SETCC) {
7782     SDValue NewCond = LowerSETCC(Cond, DAG);
7783     if (NewCond.getNode())
7784       Cond = NewCond;
7785   }
7786 #if 0
7787   // FIXME: LowerXALUO doesn't handle these!!
7788   else if (Cond.getOpcode() == X86ISD::ADD  ||
7789            Cond.getOpcode() == X86ISD::SUB  ||
7790            Cond.getOpcode() == X86ISD::SMUL ||
7791            Cond.getOpcode() == X86ISD::UMUL)
7792     Cond = LowerXALUO(Cond, DAG);
7793 #endif
7794
7795   // Look pass (and (setcc_carry (cmp ...)), 1).
7796   if (Cond.getOpcode() == ISD::AND &&
7797       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7798     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7799     if (C && C->getAPIntValue() == 1)
7800       Cond = Cond.getOperand(0);
7801   }
7802
7803   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7804   // setting operand in place of the X86ISD::SETCC.
7805   if (Cond.getOpcode() == X86ISD::SETCC ||
7806       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7807     CC = Cond.getOperand(0);
7808
7809     SDValue Cmp = Cond.getOperand(1);
7810     unsigned Opc = Cmp.getOpcode();
7811     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7812     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7813       Cond = Cmp;
7814       addTest = false;
7815     } else {
7816       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7817       default: break;
7818       case X86::COND_O:
7819       case X86::COND_B:
7820         // These can only come from an arithmetic instruction with overflow,
7821         // e.g. SADDO, UADDO.
7822         Cond = Cond.getNode()->getOperand(1);
7823         addTest = false;
7824         break;
7825       }
7826     }
7827   } else {
7828     unsigned CondOpc;
7829     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7830       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7831       if (CondOpc == ISD::OR) {
7832         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7833         // two branches instead of an explicit OR instruction with a
7834         // separate test.
7835         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7836             isX86LogicalCmp(Cmp)) {
7837           CC = Cond.getOperand(0).getOperand(0);
7838           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7839                               Chain, Dest, CC, Cmp);
7840           CC = Cond.getOperand(1).getOperand(0);
7841           Cond = Cmp;
7842           addTest = false;
7843         }
7844       } else { // ISD::AND
7845         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7846         // two branches instead of an explicit AND instruction with a
7847         // separate test. However, we only do this if this block doesn't
7848         // have a fall-through edge, because this requires an explicit
7849         // jmp when the condition is false.
7850         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7851             isX86LogicalCmp(Cmp) &&
7852             Op.getNode()->hasOneUse()) {
7853           X86::CondCode CCode =
7854             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7855           CCode = X86::GetOppositeBranchCondition(CCode);
7856           CC = DAG.getConstant(CCode, MVT::i8);
7857           SDNode *User = *Op.getNode()->use_begin();
7858           // Look for an unconditional branch following this conditional branch.
7859           // We need this because we need to reverse the successors in order
7860           // to implement FCMP_OEQ.
7861           if (User->getOpcode() == ISD::BR) {
7862             SDValue FalseBB = User->getOperand(1);
7863             SDNode *NewBR =
7864               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7865             assert(NewBR == User);
7866             (void)NewBR;
7867             Dest = FalseBB;
7868
7869             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7870                                 Chain, Dest, CC, Cmp);
7871             X86::CondCode CCode =
7872               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7873             CCode = X86::GetOppositeBranchCondition(CCode);
7874             CC = DAG.getConstant(CCode, MVT::i8);
7875             Cond = Cmp;
7876             addTest = false;
7877           }
7878         }
7879       }
7880     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7881       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7882       // It should be transformed during dag combiner except when the condition
7883       // is set by a arithmetics with overflow node.
7884       X86::CondCode CCode =
7885         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7886       CCode = X86::GetOppositeBranchCondition(CCode);
7887       CC = DAG.getConstant(CCode, MVT::i8);
7888       Cond = Cond.getOperand(0).getOperand(1);
7889       addTest = false;
7890     }
7891   }
7892
7893   if (addTest) {
7894     // Look pass the truncate.
7895     if (Cond.getOpcode() == ISD::TRUNCATE)
7896       Cond = Cond.getOperand(0);
7897
7898     // We know the result of AND is compared against zero. Try to match
7899     // it to BT.
7900     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7901       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7902       if (NewSetCC.getNode()) {
7903         CC = NewSetCC.getOperand(0);
7904         Cond = NewSetCC.getOperand(1);
7905         addTest = false;
7906       }
7907     }
7908   }
7909
7910   if (addTest) {
7911     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7912     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7913   }
7914   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7915                      Chain, Dest, CC, Cond);
7916 }
7917
7918
7919 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7920 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7921 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7922 // that the guard pages used by the OS virtual memory manager are allocated in
7923 // correct sequence.
7924 SDValue
7925 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7926                                            SelectionDAG &DAG) const {
7927   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7928          "This should be used only on Windows targets");
7929   assert(!Subtarget->isTargetEnvMacho());
7930   DebugLoc dl = Op.getDebugLoc();
7931
7932   // Get the inputs.
7933   SDValue Chain = Op.getOperand(0);
7934   SDValue Size  = Op.getOperand(1);
7935   // FIXME: Ensure alignment here
7936
7937   SDValue Flag;
7938
7939   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7940   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7941
7942   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
7943   Flag = Chain.getValue(1);
7944
7945   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7946
7947   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7948   Flag = Chain.getValue(1);
7949
7950   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7951
7952   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7953   return DAG.getMergeValues(Ops1, 2, dl);
7954 }
7955
7956 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7957   MachineFunction &MF = DAG.getMachineFunction();
7958   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7959
7960   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7961   DebugLoc DL = Op.getDebugLoc();
7962
7963   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7964     // vastart just stores the address of the VarArgsFrameIndex slot into the
7965     // memory location argument.
7966     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7967                                    getPointerTy());
7968     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7969                         MachinePointerInfo(SV), false, false, 0);
7970   }
7971
7972   // __va_list_tag:
7973   //   gp_offset         (0 - 6 * 8)
7974   //   fp_offset         (48 - 48 + 8 * 16)
7975   //   overflow_arg_area (point to parameters coming in memory).
7976   //   reg_save_area
7977   SmallVector<SDValue, 8> MemOps;
7978   SDValue FIN = Op.getOperand(1);
7979   // Store gp_offset
7980   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7981                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7982                                                MVT::i32),
7983                                FIN, MachinePointerInfo(SV), false, false, 0);
7984   MemOps.push_back(Store);
7985
7986   // Store fp_offset
7987   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7988                     FIN, DAG.getIntPtrConstant(4));
7989   Store = DAG.getStore(Op.getOperand(0), DL,
7990                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7991                                        MVT::i32),
7992                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7993   MemOps.push_back(Store);
7994
7995   // Store ptr to overflow_arg_area
7996   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7997                     FIN, DAG.getIntPtrConstant(4));
7998   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7999                                     getPointerTy());
8000   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8001                        MachinePointerInfo(SV, 8),
8002                        false, false, 0);
8003   MemOps.push_back(Store);
8004
8005   // Store ptr to reg_save_area.
8006   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8007                     FIN, DAG.getIntPtrConstant(8));
8008   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8009                                     getPointerTy());
8010   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8011                        MachinePointerInfo(SV, 16), false, false, 0);
8012   MemOps.push_back(Store);
8013   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8014                      &MemOps[0], MemOps.size());
8015 }
8016
8017 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8018   assert(Subtarget->is64Bit() &&
8019          "LowerVAARG only handles 64-bit va_arg!");
8020   assert((Subtarget->isTargetLinux() ||
8021           Subtarget->isTargetDarwin()) &&
8022           "Unhandled target in LowerVAARG");
8023   assert(Op.getNode()->getNumOperands() == 4);
8024   SDValue Chain = Op.getOperand(0);
8025   SDValue SrcPtr = Op.getOperand(1);
8026   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8027   unsigned Align = Op.getConstantOperandVal(3);
8028   DebugLoc dl = Op.getDebugLoc();
8029
8030   EVT ArgVT = Op.getNode()->getValueType(0);
8031   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8032   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8033   uint8_t ArgMode;
8034
8035   // Decide which area this value should be read from.
8036   // TODO: Implement the AMD64 ABI in its entirety. This simple
8037   // selection mechanism works only for the basic types.
8038   if (ArgVT == MVT::f80) {
8039     llvm_unreachable("va_arg for f80 not yet implemented");
8040   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8041     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8042   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8043     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8044   } else {
8045     llvm_unreachable("Unhandled argument type in LowerVAARG");
8046   }
8047
8048   if (ArgMode == 2) {
8049     // Sanity Check: Make sure using fp_offset makes sense.
8050     assert(!UseSoftFloat &&
8051            !(DAG.getMachineFunction()
8052                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8053            Subtarget->hasXMM());
8054   }
8055
8056   // Insert VAARG_64 node into the DAG
8057   // VAARG_64 returns two values: Variable Argument Address, Chain
8058   SmallVector<SDValue, 11> InstOps;
8059   InstOps.push_back(Chain);
8060   InstOps.push_back(SrcPtr);
8061   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8062   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8063   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8064   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8065   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8066                                           VTs, &InstOps[0], InstOps.size(),
8067                                           MVT::i64,
8068                                           MachinePointerInfo(SV),
8069                                           /*Align=*/0,
8070                                           /*Volatile=*/false,
8071                                           /*ReadMem=*/true,
8072                                           /*WriteMem=*/true);
8073   Chain = VAARG.getValue(1);
8074
8075   // Load the next argument and return it
8076   return DAG.getLoad(ArgVT, dl,
8077                      Chain,
8078                      VAARG,
8079                      MachinePointerInfo(),
8080                      false, false, 0);
8081 }
8082
8083 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8084   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8085   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8086   SDValue Chain = Op.getOperand(0);
8087   SDValue DstPtr = Op.getOperand(1);
8088   SDValue SrcPtr = Op.getOperand(2);
8089   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8090   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8091   DebugLoc DL = Op.getDebugLoc();
8092
8093   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8094                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8095                        false,
8096                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8097 }
8098
8099 SDValue
8100 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8101   DebugLoc dl = Op.getDebugLoc();
8102   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8103   switch (IntNo) {
8104   default: return SDValue();    // Don't custom lower most intrinsics.
8105   // Comparison intrinsics.
8106   case Intrinsic::x86_sse_comieq_ss:
8107   case Intrinsic::x86_sse_comilt_ss:
8108   case Intrinsic::x86_sse_comile_ss:
8109   case Intrinsic::x86_sse_comigt_ss:
8110   case Intrinsic::x86_sse_comige_ss:
8111   case Intrinsic::x86_sse_comineq_ss:
8112   case Intrinsic::x86_sse_ucomieq_ss:
8113   case Intrinsic::x86_sse_ucomilt_ss:
8114   case Intrinsic::x86_sse_ucomile_ss:
8115   case Intrinsic::x86_sse_ucomigt_ss:
8116   case Intrinsic::x86_sse_ucomige_ss:
8117   case Intrinsic::x86_sse_ucomineq_ss:
8118   case Intrinsic::x86_sse2_comieq_sd:
8119   case Intrinsic::x86_sse2_comilt_sd:
8120   case Intrinsic::x86_sse2_comile_sd:
8121   case Intrinsic::x86_sse2_comigt_sd:
8122   case Intrinsic::x86_sse2_comige_sd:
8123   case Intrinsic::x86_sse2_comineq_sd:
8124   case Intrinsic::x86_sse2_ucomieq_sd:
8125   case Intrinsic::x86_sse2_ucomilt_sd:
8126   case Intrinsic::x86_sse2_ucomile_sd:
8127   case Intrinsic::x86_sse2_ucomigt_sd:
8128   case Intrinsic::x86_sse2_ucomige_sd:
8129   case Intrinsic::x86_sse2_ucomineq_sd: {
8130     unsigned Opc = 0;
8131     ISD::CondCode CC = ISD::SETCC_INVALID;
8132     switch (IntNo) {
8133     default: break;
8134     case Intrinsic::x86_sse_comieq_ss:
8135     case Intrinsic::x86_sse2_comieq_sd:
8136       Opc = X86ISD::COMI;
8137       CC = ISD::SETEQ;
8138       break;
8139     case Intrinsic::x86_sse_comilt_ss:
8140     case Intrinsic::x86_sse2_comilt_sd:
8141       Opc = X86ISD::COMI;
8142       CC = ISD::SETLT;
8143       break;
8144     case Intrinsic::x86_sse_comile_ss:
8145     case Intrinsic::x86_sse2_comile_sd:
8146       Opc = X86ISD::COMI;
8147       CC = ISD::SETLE;
8148       break;
8149     case Intrinsic::x86_sse_comigt_ss:
8150     case Intrinsic::x86_sse2_comigt_sd:
8151       Opc = X86ISD::COMI;
8152       CC = ISD::SETGT;
8153       break;
8154     case Intrinsic::x86_sse_comige_ss:
8155     case Intrinsic::x86_sse2_comige_sd:
8156       Opc = X86ISD::COMI;
8157       CC = ISD::SETGE;
8158       break;
8159     case Intrinsic::x86_sse_comineq_ss:
8160     case Intrinsic::x86_sse2_comineq_sd:
8161       Opc = X86ISD::COMI;
8162       CC = ISD::SETNE;
8163       break;
8164     case Intrinsic::x86_sse_ucomieq_ss:
8165     case Intrinsic::x86_sse2_ucomieq_sd:
8166       Opc = X86ISD::UCOMI;
8167       CC = ISD::SETEQ;
8168       break;
8169     case Intrinsic::x86_sse_ucomilt_ss:
8170     case Intrinsic::x86_sse2_ucomilt_sd:
8171       Opc = X86ISD::UCOMI;
8172       CC = ISD::SETLT;
8173       break;
8174     case Intrinsic::x86_sse_ucomile_ss:
8175     case Intrinsic::x86_sse2_ucomile_sd:
8176       Opc = X86ISD::UCOMI;
8177       CC = ISD::SETLE;
8178       break;
8179     case Intrinsic::x86_sse_ucomigt_ss:
8180     case Intrinsic::x86_sse2_ucomigt_sd:
8181       Opc = X86ISD::UCOMI;
8182       CC = ISD::SETGT;
8183       break;
8184     case Intrinsic::x86_sse_ucomige_ss:
8185     case Intrinsic::x86_sse2_ucomige_sd:
8186       Opc = X86ISD::UCOMI;
8187       CC = ISD::SETGE;
8188       break;
8189     case Intrinsic::x86_sse_ucomineq_ss:
8190     case Intrinsic::x86_sse2_ucomineq_sd:
8191       Opc = X86ISD::UCOMI;
8192       CC = ISD::SETNE;
8193       break;
8194     }
8195
8196     SDValue LHS = Op.getOperand(1);
8197     SDValue RHS = Op.getOperand(2);
8198     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8199     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8200     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8201     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8202                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8203     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8204   }
8205   // ptest and testp intrinsics. The intrinsic these come from are designed to
8206   // return an integer value, not just an instruction so lower it to the ptest
8207   // or testp pattern and a setcc for the result.
8208   case Intrinsic::x86_sse41_ptestz:
8209   case Intrinsic::x86_sse41_ptestc:
8210   case Intrinsic::x86_sse41_ptestnzc:
8211   case Intrinsic::x86_avx_ptestz_256:
8212   case Intrinsic::x86_avx_ptestc_256:
8213   case Intrinsic::x86_avx_ptestnzc_256:
8214   case Intrinsic::x86_avx_vtestz_ps:
8215   case Intrinsic::x86_avx_vtestc_ps:
8216   case Intrinsic::x86_avx_vtestnzc_ps:
8217   case Intrinsic::x86_avx_vtestz_pd:
8218   case Intrinsic::x86_avx_vtestc_pd:
8219   case Intrinsic::x86_avx_vtestnzc_pd:
8220   case Intrinsic::x86_avx_vtestz_ps_256:
8221   case Intrinsic::x86_avx_vtestc_ps_256:
8222   case Intrinsic::x86_avx_vtestnzc_ps_256:
8223   case Intrinsic::x86_avx_vtestz_pd_256:
8224   case Intrinsic::x86_avx_vtestc_pd_256:
8225   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8226     bool IsTestPacked = false;
8227     unsigned X86CC = 0;
8228     switch (IntNo) {
8229     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8230     case Intrinsic::x86_avx_vtestz_ps:
8231     case Intrinsic::x86_avx_vtestz_pd:
8232     case Intrinsic::x86_avx_vtestz_ps_256:
8233     case Intrinsic::x86_avx_vtestz_pd_256:
8234       IsTestPacked = true; // Fallthrough
8235     case Intrinsic::x86_sse41_ptestz:
8236     case Intrinsic::x86_avx_ptestz_256:
8237       // ZF = 1
8238       X86CC = X86::COND_E;
8239       break;
8240     case Intrinsic::x86_avx_vtestc_ps:
8241     case Intrinsic::x86_avx_vtestc_pd:
8242     case Intrinsic::x86_avx_vtestc_ps_256:
8243     case Intrinsic::x86_avx_vtestc_pd_256:
8244       IsTestPacked = true; // Fallthrough
8245     case Intrinsic::x86_sse41_ptestc:
8246     case Intrinsic::x86_avx_ptestc_256:
8247       // CF = 1
8248       X86CC = X86::COND_B;
8249       break;
8250     case Intrinsic::x86_avx_vtestnzc_ps:
8251     case Intrinsic::x86_avx_vtestnzc_pd:
8252     case Intrinsic::x86_avx_vtestnzc_ps_256:
8253     case Intrinsic::x86_avx_vtestnzc_pd_256:
8254       IsTestPacked = true; // Fallthrough
8255     case Intrinsic::x86_sse41_ptestnzc:
8256     case Intrinsic::x86_avx_ptestnzc_256:
8257       // ZF and CF = 0
8258       X86CC = X86::COND_A;
8259       break;
8260     }
8261
8262     SDValue LHS = Op.getOperand(1);
8263     SDValue RHS = Op.getOperand(2);
8264     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8265     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8266     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8267     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8268     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8269   }
8270
8271   // Fix vector shift instructions where the last operand is a non-immediate
8272   // i32 value.
8273   case Intrinsic::x86_sse2_pslli_w:
8274   case Intrinsic::x86_sse2_pslli_d:
8275   case Intrinsic::x86_sse2_pslli_q:
8276   case Intrinsic::x86_sse2_psrli_w:
8277   case Intrinsic::x86_sse2_psrli_d:
8278   case Intrinsic::x86_sse2_psrli_q:
8279   case Intrinsic::x86_sse2_psrai_w:
8280   case Intrinsic::x86_sse2_psrai_d:
8281   case Intrinsic::x86_mmx_pslli_w:
8282   case Intrinsic::x86_mmx_pslli_d:
8283   case Intrinsic::x86_mmx_pslli_q:
8284   case Intrinsic::x86_mmx_psrli_w:
8285   case Intrinsic::x86_mmx_psrli_d:
8286   case Intrinsic::x86_mmx_psrli_q:
8287   case Intrinsic::x86_mmx_psrai_w:
8288   case Intrinsic::x86_mmx_psrai_d: {
8289     SDValue ShAmt = Op.getOperand(2);
8290     if (isa<ConstantSDNode>(ShAmt))
8291       return SDValue();
8292
8293     unsigned NewIntNo = 0;
8294     EVT ShAmtVT = MVT::v4i32;
8295     switch (IntNo) {
8296     case Intrinsic::x86_sse2_pslli_w:
8297       NewIntNo = Intrinsic::x86_sse2_psll_w;
8298       break;
8299     case Intrinsic::x86_sse2_pslli_d:
8300       NewIntNo = Intrinsic::x86_sse2_psll_d;
8301       break;
8302     case Intrinsic::x86_sse2_pslli_q:
8303       NewIntNo = Intrinsic::x86_sse2_psll_q;
8304       break;
8305     case Intrinsic::x86_sse2_psrli_w:
8306       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8307       break;
8308     case Intrinsic::x86_sse2_psrli_d:
8309       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8310       break;
8311     case Intrinsic::x86_sse2_psrli_q:
8312       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8313       break;
8314     case Intrinsic::x86_sse2_psrai_w:
8315       NewIntNo = Intrinsic::x86_sse2_psra_w;
8316       break;
8317     case Intrinsic::x86_sse2_psrai_d:
8318       NewIntNo = Intrinsic::x86_sse2_psra_d;
8319       break;
8320     default: {
8321       ShAmtVT = MVT::v2i32;
8322       switch (IntNo) {
8323       case Intrinsic::x86_mmx_pslli_w:
8324         NewIntNo = Intrinsic::x86_mmx_psll_w;
8325         break;
8326       case Intrinsic::x86_mmx_pslli_d:
8327         NewIntNo = Intrinsic::x86_mmx_psll_d;
8328         break;
8329       case Intrinsic::x86_mmx_pslli_q:
8330         NewIntNo = Intrinsic::x86_mmx_psll_q;
8331         break;
8332       case Intrinsic::x86_mmx_psrli_w:
8333         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8334         break;
8335       case Intrinsic::x86_mmx_psrli_d:
8336         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8337         break;
8338       case Intrinsic::x86_mmx_psrli_q:
8339         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8340         break;
8341       case Intrinsic::x86_mmx_psrai_w:
8342         NewIntNo = Intrinsic::x86_mmx_psra_w;
8343         break;
8344       case Intrinsic::x86_mmx_psrai_d:
8345         NewIntNo = Intrinsic::x86_mmx_psra_d;
8346         break;
8347       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8348       }
8349       break;
8350     }
8351     }
8352
8353     // The vector shift intrinsics with scalars uses 32b shift amounts but
8354     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8355     // to be zero.
8356     SDValue ShOps[4];
8357     ShOps[0] = ShAmt;
8358     ShOps[1] = DAG.getConstant(0, MVT::i32);
8359     if (ShAmtVT == MVT::v4i32) {
8360       ShOps[2] = DAG.getUNDEF(MVT::i32);
8361       ShOps[3] = DAG.getUNDEF(MVT::i32);
8362       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8363     } else {
8364       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8365 // FIXME this must be lowered to get rid of the invalid type.
8366     }
8367
8368     EVT VT = Op.getValueType();
8369     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8370     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8371                        DAG.getConstant(NewIntNo, MVT::i32),
8372                        Op.getOperand(1), ShAmt);
8373   }
8374   }
8375 }
8376
8377 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8378                                            SelectionDAG &DAG) const {
8379   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8380   MFI->setReturnAddressIsTaken(true);
8381
8382   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8383   DebugLoc dl = Op.getDebugLoc();
8384
8385   if (Depth > 0) {
8386     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8387     SDValue Offset =
8388       DAG.getConstant(TD->getPointerSize(),
8389                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8390     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8391                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8392                                    FrameAddr, Offset),
8393                        MachinePointerInfo(), false, false, 0);
8394   }
8395
8396   // Just load the return address.
8397   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8398   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8399                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8400 }
8401
8402 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8403   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8404   MFI->setFrameAddressIsTaken(true);
8405
8406   EVT VT = Op.getValueType();
8407   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8408   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8409   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8410   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8411   while (Depth--)
8412     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8413                             MachinePointerInfo(),
8414                             false, false, 0);
8415   return FrameAddr;
8416 }
8417
8418 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8419                                                      SelectionDAG &DAG) const {
8420   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8421 }
8422
8423 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8424   MachineFunction &MF = DAG.getMachineFunction();
8425   SDValue Chain     = Op.getOperand(0);
8426   SDValue Offset    = Op.getOperand(1);
8427   SDValue Handler   = Op.getOperand(2);
8428   DebugLoc dl       = Op.getDebugLoc();
8429
8430   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8431                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8432                                      getPointerTy());
8433   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8434
8435   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8436                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8437   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8438   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8439                        false, false, 0);
8440   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8441   MF.getRegInfo().addLiveOut(StoreAddrReg);
8442
8443   return DAG.getNode(X86ISD::EH_RETURN, dl,
8444                      MVT::Other,
8445                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8446 }
8447
8448 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8449                                              SelectionDAG &DAG) const {
8450   SDValue Root = Op.getOperand(0);
8451   SDValue Trmp = Op.getOperand(1); // trampoline
8452   SDValue FPtr = Op.getOperand(2); // nested function
8453   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8454   DebugLoc dl  = Op.getDebugLoc();
8455
8456   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8457
8458   if (Subtarget->is64Bit()) {
8459     SDValue OutChains[6];
8460
8461     // Large code-model.
8462     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8463     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8464
8465     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8466     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8467
8468     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8469
8470     // Load the pointer to the nested function into R11.
8471     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8472     SDValue Addr = Trmp;
8473     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8474                                 Addr, MachinePointerInfo(TrmpAddr),
8475                                 false, false, 0);
8476
8477     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8478                        DAG.getConstant(2, MVT::i64));
8479     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8480                                 MachinePointerInfo(TrmpAddr, 2),
8481                                 false, false, 2);
8482
8483     // Load the 'nest' parameter value into R10.
8484     // R10 is specified in X86CallingConv.td
8485     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8486     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8487                        DAG.getConstant(10, MVT::i64));
8488     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8489                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8490                                 false, false, 0);
8491
8492     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8493                        DAG.getConstant(12, MVT::i64));
8494     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8495                                 MachinePointerInfo(TrmpAddr, 12),
8496                                 false, false, 2);
8497
8498     // Jump to the nested function.
8499     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8500     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8501                        DAG.getConstant(20, MVT::i64));
8502     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8503                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8504                                 false, false, 0);
8505
8506     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8507     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8508                        DAG.getConstant(22, MVT::i64));
8509     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8510                                 MachinePointerInfo(TrmpAddr, 22),
8511                                 false, false, 0);
8512
8513     SDValue Ops[] =
8514       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8515     return DAG.getMergeValues(Ops, 2, dl);
8516   } else {
8517     const Function *Func =
8518       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8519     CallingConv::ID CC = Func->getCallingConv();
8520     unsigned NestReg;
8521
8522     switch (CC) {
8523     default:
8524       llvm_unreachable("Unsupported calling convention");
8525     case CallingConv::C:
8526     case CallingConv::X86_StdCall: {
8527       // Pass 'nest' parameter in ECX.
8528       // Must be kept in sync with X86CallingConv.td
8529       NestReg = X86::ECX;
8530
8531       // Check that ECX wasn't needed by an 'inreg' parameter.
8532       const FunctionType *FTy = Func->getFunctionType();
8533       const AttrListPtr &Attrs = Func->getAttributes();
8534
8535       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8536         unsigned InRegCount = 0;
8537         unsigned Idx = 1;
8538
8539         for (FunctionType::param_iterator I = FTy->param_begin(),
8540              E = FTy->param_end(); I != E; ++I, ++Idx)
8541           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8542             // FIXME: should only count parameters that are lowered to integers.
8543             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8544
8545         if (InRegCount > 2) {
8546           report_fatal_error("Nest register in use - reduce number of inreg"
8547                              " parameters!");
8548         }
8549       }
8550       break;
8551     }
8552     case CallingConv::X86_FastCall:
8553     case CallingConv::X86_ThisCall:
8554     case CallingConv::Fast:
8555       // Pass 'nest' parameter in EAX.
8556       // Must be kept in sync with X86CallingConv.td
8557       NestReg = X86::EAX;
8558       break;
8559     }
8560
8561     SDValue OutChains[4];
8562     SDValue Addr, Disp;
8563
8564     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8565                        DAG.getConstant(10, MVT::i32));
8566     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8567
8568     // This is storing the opcode for MOV32ri.
8569     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8570     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8571     OutChains[0] = DAG.getStore(Root, dl,
8572                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8573                                 Trmp, MachinePointerInfo(TrmpAddr),
8574                                 false, false, 0);
8575
8576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8577                        DAG.getConstant(1, MVT::i32));
8578     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8579                                 MachinePointerInfo(TrmpAddr, 1),
8580                                 false, false, 1);
8581
8582     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8583     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8584                        DAG.getConstant(5, MVT::i32));
8585     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8586                                 MachinePointerInfo(TrmpAddr, 5),
8587                                 false, false, 1);
8588
8589     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8590                        DAG.getConstant(6, MVT::i32));
8591     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8592                                 MachinePointerInfo(TrmpAddr, 6),
8593                                 false, false, 1);
8594
8595     SDValue Ops[] =
8596       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8597     return DAG.getMergeValues(Ops, 2, dl);
8598   }
8599 }
8600
8601 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8602                                             SelectionDAG &DAG) const {
8603   /*
8604    The rounding mode is in bits 11:10 of FPSR, and has the following
8605    settings:
8606      00 Round to nearest
8607      01 Round to -inf
8608      10 Round to +inf
8609      11 Round to 0
8610
8611   FLT_ROUNDS, on the other hand, expects the following:
8612     -1 Undefined
8613      0 Round to 0
8614      1 Round to nearest
8615      2 Round to +inf
8616      3 Round to -inf
8617
8618   To perform the conversion, we do:
8619     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8620   */
8621
8622   MachineFunction &MF = DAG.getMachineFunction();
8623   const TargetMachine &TM = MF.getTarget();
8624   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8625   unsigned StackAlignment = TFI.getStackAlignment();
8626   EVT VT = Op.getValueType();
8627   DebugLoc DL = Op.getDebugLoc();
8628
8629   // Save FP Control Word to stack slot
8630   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8631   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8632
8633
8634   MachineMemOperand *MMO =
8635    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8636                            MachineMemOperand::MOStore, 2, 2);
8637
8638   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8639   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8640                                           DAG.getVTList(MVT::Other),
8641                                           Ops, 2, MVT::i16, MMO);
8642
8643   // Load FP Control Word from stack slot
8644   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8645                             MachinePointerInfo(), false, false, 0);
8646
8647   // Transform as necessary
8648   SDValue CWD1 =
8649     DAG.getNode(ISD::SRL, DL, MVT::i16,
8650                 DAG.getNode(ISD::AND, DL, MVT::i16,
8651                             CWD, DAG.getConstant(0x800, MVT::i16)),
8652                 DAG.getConstant(11, MVT::i8));
8653   SDValue CWD2 =
8654     DAG.getNode(ISD::SRL, DL, MVT::i16,
8655                 DAG.getNode(ISD::AND, DL, MVT::i16,
8656                             CWD, DAG.getConstant(0x400, MVT::i16)),
8657                 DAG.getConstant(9, MVT::i8));
8658
8659   SDValue RetVal =
8660     DAG.getNode(ISD::AND, DL, MVT::i16,
8661                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8662                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8663                             DAG.getConstant(1, MVT::i16)),
8664                 DAG.getConstant(3, MVT::i16));
8665
8666
8667   return DAG.getNode((VT.getSizeInBits() < 16 ?
8668                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8669 }
8670
8671 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8672   EVT VT = Op.getValueType();
8673   EVT OpVT = VT;
8674   unsigned NumBits = VT.getSizeInBits();
8675   DebugLoc dl = Op.getDebugLoc();
8676
8677   Op = Op.getOperand(0);
8678   if (VT == MVT::i8) {
8679     // Zero extend to i32 since there is not an i8 bsr.
8680     OpVT = MVT::i32;
8681     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8682   }
8683
8684   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8685   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8686   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8687
8688   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8689   SDValue Ops[] = {
8690     Op,
8691     DAG.getConstant(NumBits+NumBits-1, OpVT),
8692     DAG.getConstant(X86::COND_E, MVT::i8),
8693     Op.getValue(1)
8694   };
8695   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8696
8697   // Finally xor with NumBits-1.
8698   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8699
8700   if (VT == MVT::i8)
8701     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8702   return Op;
8703 }
8704
8705 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8706   EVT VT = Op.getValueType();
8707   EVT OpVT = VT;
8708   unsigned NumBits = VT.getSizeInBits();
8709   DebugLoc dl = Op.getDebugLoc();
8710
8711   Op = Op.getOperand(0);
8712   if (VT == MVT::i8) {
8713     OpVT = MVT::i32;
8714     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8715   }
8716
8717   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8718   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8719   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8720
8721   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8722   SDValue Ops[] = {
8723     Op,
8724     DAG.getConstant(NumBits, OpVT),
8725     DAG.getConstant(X86::COND_E, MVT::i8),
8726     Op.getValue(1)
8727   };
8728   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8729
8730   if (VT == MVT::i8)
8731     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8732   return Op;
8733 }
8734
8735 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8736   EVT VT = Op.getValueType();
8737   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8738   DebugLoc dl = Op.getDebugLoc();
8739
8740   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8741   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8742   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8743   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8744   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8745   //
8746   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8747   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8748   //  return AloBlo + AloBhi + AhiBlo;
8749
8750   SDValue A = Op.getOperand(0);
8751   SDValue B = Op.getOperand(1);
8752
8753   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8754                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8755                        A, DAG.getConstant(32, MVT::i32));
8756   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8757                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8758                        B, DAG.getConstant(32, MVT::i32));
8759   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8760                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8761                        A, B);
8762   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8763                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8764                        A, Bhi);
8765   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8766                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8767                        Ahi, B);
8768   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8769                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8770                        AloBhi, DAG.getConstant(32, MVT::i32));
8771   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8772                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8773                        AhiBlo, DAG.getConstant(32, MVT::i32));
8774   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8775   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8776   return Res;
8777 }
8778
8779 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8780
8781   EVT VT = Op.getValueType();
8782   DebugLoc dl = Op.getDebugLoc();
8783   SDValue R = Op.getOperand(0);
8784   SDValue Amt = Op.getOperand(1);
8785
8786   LLVMContext *Context = DAG.getContext();
8787
8788   // Must have SSE2.
8789   if (!Subtarget->hasSSE2()) return SDValue();
8790
8791   // Optimize shl/srl/sra with constant shift amount.
8792   if (isSplatVector(Amt.getNode())) {
8793     SDValue SclrAmt = Amt->getOperand(0);
8794     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8795       uint64_t ShiftAmt = C->getZExtValue();
8796
8797       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8798        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8799                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8800                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8801
8802       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8803        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8804                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8805                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8806
8807       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8808        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8809                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8810                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8811
8812       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8813        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8814                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8815                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8816
8817       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8818        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8819                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8820                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8821
8822       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8823        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8824                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8825                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8826
8827       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8828        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8829                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8830                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8831
8832       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8833        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8834                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8835                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8836     }
8837   }
8838
8839   // Lower SHL with variable shift amount.
8840   // Cannot lower SHL without SSE4.1 or later.
8841   if (!Subtarget->hasSSE41()) return SDValue();
8842
8843   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8844     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8846                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8847
8848     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8849
8850     std::vector<Constant*> CV(4, CI);
8851     Constant *C = ConstantVector::get(CV);
8852     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8853     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8854                                  MachinePointerInfo::getConstantPool(),
8855                                  false, false, 16);
8856
8857     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8858     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8859     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8860     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8861   }
8862   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8863     // a = a << 5;
8864     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8865                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8866                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8867
8868     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8869     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8870
8871     std::vector<Constant*> CVM1(16, CM1);
8872     std::vector<Constant*> CVM2(16, CM2);
8873     Constant *C = ConstantVector::get(CVM1);
8874     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8875     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8876                             MachinePointerInfo::getConstantPool(),
8877                             false, false, 16);
8878
8879     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8880     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8881     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8882                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8883                     DAG.getConstant(4, MVT::i32));
8884     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8885     // a += a
8886     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8887
8888     C = ConstantVector::get(CVM2);
8889     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8890     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8891                     MachinePointerInfo::getConstantPool(),
8892                     false, false, 16);
8893
8894     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8895     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8896     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8897                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8898                     DAG.getConstant(2, MVT::i32));
8899     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8900     // a += a
8901     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8902
8903     // return pblendv(r, r+r, a);
8904     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8905                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8906     return R;
8907   }
8908   return SDValue();
8909 }
8910
8911 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8912   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8913   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8914   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8915   // has only one use.
8916   SDNode *N = Op.getNode();
8917   SDValue LHS = N->getOperand(0);
8918   SDValue RHS = N->getOperand(1);
8919   unsigned BaseOp = 0;
8920   unsigned Cond = 0;
8921   DebugLoc DL = Op.getDebugLoc();
8922   switch (Op.getOpcode()) {
8923   default: llvm_unreachable("Unknown ovf instruction!");
8924   case ISD::SADDO:
8925     // A subtract of one will be selected as a INC. Note that INC doesn't
8926     // set CF, so we can't do this for UADDO.
8927     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8928       if (C->isOne()) {
8929         BaseOp = X86ISD::INC;
8930         Cond = X86::COND_O;
8931         break;
8932       }
8933     BaseOp = X86ISD::ADD;
8934     Cond = X86::COND_O;
8935     break;
8936   case ISD::UADDO:
8937     BaseOp = X86ISD::ADD;
8938     Cond = X86::COND_B;
8939     break;
8940   case ISD::SSUBO:
8941     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8942     // set CF, so we can't do this for USUBO.
8943     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8944       if (C->isOne()) {
8945         BaseOp = X86ISD::DEC;
8946         Cond = X86::COND_O;
8947         break;
8948       }
8949     BaseOp = X86ISD::SUB;
8950     Cond = X86::COND_O;
8951     break;
8952   case ISD::USUBO:
8953     BaseOp = X86ISD::SUB;
8954     Cond = X86::COND_B;
8955     break;
8956   case ISD::SMULO:
8957     BaseOp = X86ISD::SMUL;
8958     Cond = X86::COND_O;
8959     break;
8960   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8961     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8962                                  MVT::i32);
8963     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8964
8965     SDValue SetCC =
8966       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8967                   DAG.getConstant(X86::COND_O, MVT::i32),
8968                   SDValue(Sum.getNode(), 2));
8969
8970     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8971     return Sum;
8972   }
8973   }
8974
8975   // Also sets EFLAGS.
8976   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8977   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8978
8979   SDValue SetCC =
8980     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8981                 DAG.getConstant(Cond, MVT::i32),
8982                 SDValue(Sum.getNode(), 1));
8983
8984   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8985   return Sum;
8986 }
8987
8988 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8989   DebugLoc dl = Op.getDebugLoc();
8990
8991   if (!Subtarget->hasSSE2()) {
8992     SDValue Chain = Op.getOperand(0);
8993     SDValue Zero = DAG.getConstant(0,
8994                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8995     SDValue Ops[] = {
8996       DAG.getRegister(X86::ESP, MVT::i32), // Base
8997       DAG.getTargetConstant(1, MVT::i8),   // Scale
8998       DAG.getRegister(0, MVT::i32),        // Index
8999       DAG.getTargetConstant(0, MVT::i32),  // Disp
9000       DAG.getRegister(0, MVT::i32),        // Segment.
9001       Zero,
9002       Chain
9003     };
9004     SDNode *Res =
9005       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9006                           array_lengthof(Ops));
9007     return SDValue(Res, 0);
9008   }
9009
9010   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9011   if (!isDev)
9012     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9013
9014   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9015   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9016   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9017   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9018
9019   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9020   if (!Op1 && !Op2 && !Op3 && Op4)
9021     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9022
9023   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9024   if (Op1 && !Op2 && !Op3 && !Op4)
9025     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9026
9027   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9028   //           (MFENCE)>;
9029   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9030 }
9031
9032 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9033   EVT T = Op.getValueType();
9034   DebugLoc DL = Op.getDebugLoc();
9035   unsigned Reg = 0;
9036   unsigned size = 0;
9037   switch(T.getSimpleVT().SimpleTy) {
9038   default:
9039     assert(false && "Invalid value type!");
9040   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9041   case MVT::i16: Reg = X86::AX;  size = 2; break;
9042   case MVT::i32: Reg = X86::EAX; size = 4; break;
9043   case MVT::i64:
9044     assert(Subtarget->is64Bit() && "Node not type legal!");
9045     Reg = X86::RAX; size = 8;
9046     break;
9047   }
9048   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9049                                     Op.getOperand(2), SDValue());
9050   SDValue Ops[] = { cpIn.getValue(0),
9051                     Op.getOperand(1),
9052                     Op.getOperand(3),
9053                     DAG.getTargetConstant(size, MVT::i8),
9054                     cpIn.getValue(1) };
9055   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9056   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9057   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9058                                            Ops, 5, T, MMO);
9059   SDValue cpOut =
9060     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9061   return cpOut;
9062 }
9063
9064 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9065                                                  SelectionDAG &DAG) const {
9066   assert(Subtarget->is64Bit() && "Result not type legalized?");
9067   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9068   SDValue TheChain = Op.getOperand(0);
9069   DebugLoc dl = Op.getDebugLoc();
9070   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9071   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9072   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9073                                    rax.getValue(2));
9074   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9075                             DAG.getConstant(32, MVT::i8));
9076   SDValue Ops[] = {
9077     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9078     rdx.getValue(1)
9079   };
9080   return DAG.getMergeValues(Ops, 2, dl);
9081 }
9082
9083 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9084                                             SelectionDAG &DAG) const {
9085   EVT SrcVT = Op.getOperand(0).getValueType();
9086   EVT DstVT = Op.getValueType();
9087   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9088          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9089   assert((DstVT == MVT::i64 ||
9090           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9091          "Unexpected custom BITCAST");
9092   // i64 <=> MMX conversions are Legal.
9093   if (SrcVT==MVT::i64 && DstVT.isVector())
9094     return Op;
9095   if (DstVT==MVT::i64 && SrcVT.isVector())
9096     return Op;
9097   // MMX <=> MMX conversions are Legal.
9098   if (SrcVT.isVector() && DstVT.isVector())
9099     return Op;
9100   // All other conversions need to be expanded.
9101   return SDValue();
9102 }
9103
9104 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9105   SDNode *Node = Op.getNode();
9106   DebugLoc dl = Node->getDebugLoc();
9107   EVT T = Node->getValueType(0);
9108   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9109                               DAG.getConstant(0, T), Node->getOperand(2));
9110   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9111                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9112                        Node->getOperand(0),
9113                        Node->getOperand(1), negOp,
9114                        cast<AtomicSDNode>(Node)->getSrcValue(),
9115                        cast<AtomicSDNode>(Node)->getAlignment());
9116 }
9117
9118 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9119   EVT VT = Op.getNode()->getValueType(0);
9120
9121   // Let legalize expand this if it isn't a legal type yet.
9122   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9123     return SDValue();
9124
9125   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9126
9127   unsigned Opc;
9128   bool ExtraOp = false;
9129   switch (Op.getOpcode()) {
9130   default: assert(0 && "Invalid code");
9131   case ISD::ADDC: Opc = X86ISD::ADD; break;
9132   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9133   case ISD::SUBC: Opc = X86ISD::SUB; break;
9134   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9135   }
9136
9137   if (!ExtraOp)
9138     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9139                        Op.getOperand(1));
9140   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9141                      Op.getOperand(1), Op.getOperand(2));
9142 }
9143
9144 /// LowerOperation - Provide custom lowering hooks for some operations.
9145 ///
9146 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9147   switch (Op.getOpcode()) {
9148   default: llvm_unreachable("Should not custom lower this!");
9149   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9150   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9151   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9152   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9153   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9154   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9155   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9156   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9157   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9158   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9159   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9160   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9161   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9162   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9163   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9164   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9165   case ISD::SHL_PARTS:
9166   case ISD::SRA_PARTS:
9167   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9168   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9169   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9170   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9171   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9172   case ISD::FABS:               return LowerFABS(Op, DAG);
9173   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9174   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9175   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9176   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9177   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9178   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9179   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9180   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9181   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9182   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9183   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9184   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9185   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9186   case ISD::FRAME_TO_ARGS_OFFSET:
9187                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9188   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9189   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9190   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9191   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9192   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9193   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9194   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9195   case ISD::SRA:
9196   case ISD::SRL:
9197   case ISD::SHL:                return LowerShift(Op, DAG);
9198   case ISD::SADDO:
9199   case ISD::UADDO:
9200   case ISD::SSUBO:
9201   case ISD::USUBO:
9202   case ISD::SMULO:
9203   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9204   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9205   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9206   case ISD::ADDC:
9207   case ISD::ADDE:
9208   case ISD::SUBC:
9209   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9210   }
9211 }
9212
9213 void X86TargetLowering::
9214 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9215                         SelectionDAG &DAG, unsigned NewOp) const {
9216   EVT T = Node->getValueType(0);
9217   DebugLoc dl = Node->getDebugLoc();
9218   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9219
9220   SDValue Chain = Node->getOperand(0);
9221   SDValue In1 = Node->getOperand(1);
9222   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9223                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9224   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9225                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9226   SDValue Ops[] = { Chain, In1, In2L, In2H };
9227   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9228   SDValue Result =
9229     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9230                             cast<MemSDNode>(Node)->getMemOperand());
9231   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9232   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9233   Results.push_back(Result.getValue(2));
9234 }
9235
9236 /// ReplaceNodeResults - Replace a node with an illegal result type
9237 /// with a new node built out of custom code.
9238 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9239                                            SmallVectorImpl<SDValue>&Results,
9240                                            SelectionDAG &DAG) const {
9241   DebugLoc dl = N->getDebugLoc();
9242   switch (N->getOpcode()) {
9243   default:
9244     assert(false && "Do not know how to custom type legalize this operation!");
9245     return;
9246   case ISD::ADDC:
9247   case ISD::ADDE:
9248   case ISD::SUBC:
9249   case ISD::SUBE:
9250     // We don't want to expand or promote these.
9251     return;
9252   case ISD::FP_TO_SINT: {
9253     std::pair<SDValue,SDValue> Vals =
9254         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9255     SDValue FIST = Vals.first, StackSlot = Vals.second;
9256     if (FIST.getNode() != 0) {
9257       EVT VT = N->getValueType(0);
9258       // Return a load from the stack slot.
9259       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9260                                     MachinePointerInfo(), false, false, 0));
9261     }
9262     return;
9263   }
9264   case ISD::READCYCLECOUNTER: {
9265     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9266     SDValue TheChain = N->getOperand(0);
9267     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9268     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9269                                      rd.getValue(1));
9270     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9271                                      eax.getValue(2));
9272     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9273     SDValue Ops[] = { eax, edx };
9274     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9275     Results.push_back(edx.getValue(1));
9276     return;
9277   }
9278   case ISD::ATOMIC_CMP_SWAP: {
9279     EVT T = N->getValueType(0);
9280     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9281     SDValue cpInL, cpInH;
9282     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9283                         DAG.getConstant(0, MVT::i32));
9284     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9285                         DAG.getConstant(1, MVT::i32));
9286     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9287     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9288                              cpInL.getValue(1));
9289     SDValue swapInL, swapInH;
9290     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9291                           DAG.getConstant(0, MVT::i32));
9292     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9293                           DAG.getConstant(1, MVT::i32));
9294     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9295                                cpInH.getValue(1));
9296     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9297                                swapInL.getValue(1));
9298     SDValue Ops[] = { swapInH.getValue(0),
9299                       N->getOperand(1),
9300                       swapInH.getValue(1) };
9301     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9302     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9303     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9304                                              Ops, 3, T, MMO);
9305     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9306                                         MVT::i32, Result.getValue(1));
9307     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9308                                         MVT::i32, cpOutL.getValue(2));
9309     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9310     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9311     Results.push_back(cpOutH.getValue(1));
9312     return;
9313   }
9314   case ISD::ATOMIC_LOAD_ADD:
9315     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9316     return;
9317   case ISD::ATOMIC_LOAD_AND:
9318     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9319     return;
9320   case ISD::ATOMIC_LOAD_NAND:
9321     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9322     return;
9323   case ISD::ATOMIC_LOAD_OR:
9324     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9325     return;
9326   case ISD::ATOMIC_LOAD_SUB:
9327     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9328     return;
9329   case ISD::ATOMIC_LOAD_XOR:
9330     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9331     return;
9332   case ISD::ATOMIC_SWAP:
9333     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9334     return;
9335   }
9336 }
9337
9338 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9339   switch (Opcode) {
9340   default: return NULL;
9341   case X86ISD::BSF:                return "X86ISD::BSF";
9342   case X86ISD::BSR:                return "X86ISD::BSR";
9343   case X86ISD::SHLD:               return "X86ISD::SHLD";
9344   case X86ISD::SHRD:               return "X86ISD::SHRD";
9345   case X86ISD::FAND:               return "X86ISD::FAND";
9346   case X86ISD::FOR:                return "X86ISD::FOR";
9347   case X86ISD::FXOR:               return "X86ISD::FXOR";
9348   case X86ISD::FSRL:               return "X86ISD::FSRL";
9349   case X86ISD::FILD:               return "X86ISD::FILD";
9350   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9351   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9352   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9353   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9354   case X86ISD::FLD:                return "X86ISD::FLD";
9355   case X86ISD::FST:                return "X86ISD::FST";
9356   case X86ISD::CALL:               return "X86ISD::CALL";
9357   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9358   case X86ISD::BT:                 return "X86ISD::BT";
9359   case X86ISD::CMP:                return "X86ISD::CMP";
9360   case X86ISD::COMI:               return "X86ISD::COMI";
9361   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9362   case X86ISD::SETCC:              return "X86ISD::SETCC";
9363   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9364   case X86ISD::CMOV:               return "X86ISD::CMOV";
9365   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9366   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9367   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9368   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9369   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9370   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9371   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9372   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9373   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9374   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9375   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9376   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9377   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9378   case X86ISD::PANDN:              return "X86ISD::PANDN";
9379   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9380   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9381   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9382   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9383   case X86ISD::FMAX:               return "X86ISD::FMAX";
9384   case X86ISD::FMIN:               return "X86ISD::FMIN";
9385   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9386   case X86ISD::FRCP:               return "X86ISD::FRCP";
9387   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9388   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9389   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9390   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9391   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9392   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9393   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9394   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9395   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9396   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9397   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9398   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9399   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9400   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9401   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9402   case X86ISD::VSHL:               return "X86ISD::VSHL";
9403   case X86ISD::VSRL:               return "X86ISD::VSRL";
9404   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9405   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9406   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9407   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9408   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9409   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9410   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9411   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9412   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9413   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9414   case X86ISD::ADD:                return "X86ISD::ADD";
9415   case X86ISD::SUB:                return "X86ISD::SUB";
9416   case X86ISD::ADC:                return "X86ISD::ADC";
9417   case X86ISD::SBB:                return "X86ISD::SBB";
9418   case X86ISD::SMUL:               return "X86ISD::SMUL";
9419   case X86ISD::UMUL:               return "X86ISD::UMUL";
9420   case X86ISD::INC:                return "X86ISD::INC";
9421   case X86ISD::DEC:                return "X86ISD::DEC";
9422   case X86ISD::OR:                 return "X86ISD::OR";
9423   case X86ISD::XOR:                return "X86ISD::XOR";
9424   case X86ISD::AND:                return "X86ISD::AND";
9425   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9426   case X86ISD::PTEST:              return "X86ISD::PTEST";
9427   case X86ISD::TESTP:              return "X86ISD::TESTP";
9428   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9429   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9430   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9431   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9432   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9433   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9434   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9435   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9436   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9437   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9438   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9439   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9440   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9441   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9442   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9443   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9444   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9445   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9446   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9447   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9448   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9449   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9450   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9451   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9452   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9453   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9454   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9455   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9456   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9457   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9458   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9459   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9460   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9461   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9462   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9463   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9464   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9465   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9466   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9467   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9468   }
9469 }
9470
9471 // isLegalAddressingMode - Return true if the addressing mode represented
9472 // by AM is legal for this target, for a load/store of the specified type.
9473 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9474                                               const Type *Ty) const {
9475   // X86 supports extremely general addressing modes.
9476   CodeModel::Model M = getTargetMachine().getCodeModel();
9477   Reloc::Model R = getTargetMachine().getRelocationModel();
9478
9479   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9480   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9481     return false;
9482
9483   if (AM.BaseGV) {
9484     unsigned GVFlags =
9485       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9486
9487     // If a reference to this global requires an extra load, we can't fold it.
9488     if (isGlobalStubReference(GVFlags))
9489       return false;
9490
9491     // If BaseGV requires a register for the PIC base, we cannot also have a
9492     // BaseReg specified.
9493     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9494       return false;
9495
9496     // If lower 4G is not available, then we must use rip-relative addressing.
9497     if ((M != CodeModel::Small || R != Reloc::Static) &&
9498         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9499       return false;
9500   }
9501
9502   switch (AM.Scale) {
9503   case 0:
9504   case 1:
9505   case 2:
9506   case 4:
9507   case 8:
9508     // These scales always work.
9509     break;
9510   case 3:
9511   case 5:
9512   case 9:
9513     // These scales are formed with basereg+scalereg.  Only accept if there is
9514     // no basereg yet.
9515     if (AM.HasBaseReg)
9516       return false;
9517     break;
9518   default:  // Other stuff never works.
9519     return false;
9520   }
9521
9522   return true;
9523 }
9524
9525
9526 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9527   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9528     return false;
9529   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9530   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9531   if (NumBits1 <= NumBits2)
9532     return false;
9533   return true;
9534 }
9535
9536 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9537   if (!VT1.isInteger() || !VT2.isInteger())
9538     return false;
9539   unsigned NumBits1 = VT1.getSizeInBits();
9540   unsigned NumBits2 = VT2.getSizeInBits();
9541   if (NumBits1 <= NumBits2)
9542     return false;
9543   return true;
9544 }
9545
9546 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9547   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9548   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9549 }
9550
9551 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9552   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9553   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9554 }
9555
9556 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9557   // i16 instructions are longer (0x66 prefix) and potentially slower.
9558   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9559 }
9560
9561 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9562 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9563 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9564 /// are assumed to be legal.
9565 bool
9566 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9567                                       EVT VT) const {
9568   // Very little shuffling can be done for 64-bit vectors right now.
9569   if (VT.getSizeInBits() == 64)
9570     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9571
9572   // FIXME: pshufb, blends, shifts.
9573   return (VT.getVectorNumElements() == 2 ||
9574           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9575           isMOVLMask(M, VT) ||
9576           isSHUFPMask(M, VT) ||
9577           isPSHUFDMask(M, VT) ||
9578           isPSHUFHWMask(M, VT) ||
9579           isPSHUFLWMask(M, VT) ||
9580           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9581           isUNPCKLMask(M, VT) ||
9582           isUNPCKHMask(M, VT) ||
9583           isUNPCKL_v_undef_Mask(M, VT) ||
9584           isUNPCKH_v_undef_Mask(M, VT));
9585 }
9586
9587 bool
9588 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9589                                           EVT VT) const {
9590   unsigned NumElts = VT.getVectorNumElements();
9591   // FIXME: This collection of masks seems suspect.
9592   if (NumElts == 2)
9593     return true;
9594   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9595     return (isMOVLMask(Mask, VT)  ||
9596             isCommutedMOVLMask(Mask, VT, true) ||
9597             isSHUFPMask(Mask, VT) ||
9598             isCommutedSHUFPMask(Mask, VT));
9599   }
9600   return false;
9601 }
9602
9603 //===----------------------------------------------------------------------===//
9604 //                           X86 Scheduler Hooks
9605 //===----------------------------------------------------------------------===//
9606
9607 // private utility function
9608 MachineBasicBlock *
9609 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9610                                                        MachineBasicBlock *MBB,
9611                                                        unsigned regOpc,
9612                                                        unsigned immOpc,
9613                                                        unsigned LoadOpc,
9614                                                        unsigned CXchgOpc,
9615                                                        unsigned notOpc,
9616                                                        unsigned EAXreg,
9617                                                        TargetRegisterClass *RC,
9618                                                        bool invSrc) const {
9619   // For the atomic bitwise operator, we generate
9620   //   thisMBB:
9621   //   newMBB:
9622   //     ld  t1 = [bitinstr.addr]
9623   //     op  t2 = t1, [bitinstr.val]
9624   //     mov EAX = t1
9625   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9626   //     bz  newMBB
9627   //     fallthrough -->nextMBB
9628   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9629   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9630   MachineFunction::iterator MBBIter = MBB;
9631   ++MBBIter;
9632
9633   /// First build the CFG
9634   MachineFunction *F = MBB->getParent();
9635   MachineBasicBlock *thisMBB = MBB;
9636   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9637   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9638   F->insert(MBBIter, newMBB);
9639   F->insert(MBBIter, nextMBB);
9640
9641   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9642   nextMBB->splice(nextMBB->begin(), thisMBB,
9643                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9644                   thisMBB->end());
9645   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9646
9647   // Update thisMBB to fall through to newMBB
9648   thisMBB->addSuccessor(newMBB);
9649
9650   // newMBB jumps to itself and fall through to nextMBB
9651   newMBB->addSuccessor(nextMBB);
9652   newMBB->addSuccessor(newMBB);
9653
9654   // Insert instructions into newMBB based on incoming instruction
9655   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9656          "unexpected number of operands");
9657   DebugLoc dl = bInstr->getDebugLoc();
9658   MachineOperand& destOper = bInstr->getOperand(0);
9659   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9660   int numArgs = bInstr->getNumOperands() - 1;
9661   for (int i=0; i < numArgs; ++i)
9662     argOpers[i] = &bInstr->getOperand(i+1);
9663
9664   // x86 address has 4 operands: base, index, scale, and displacement
9665   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9666   int valArgIndx = lastAddrIndx + 1;
9667
9668   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9669   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9670   for (int i=0; i <= lastAddrIndx; ++i)
9671     (*MIB).addOperand(*argOpers[i]);
9672
9673   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9674   if (invSrc) {
9675     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9676   }
9677   else
9678     tt = t1;
9679
9680   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9681   assert((argOpers[valArgIndx]->isReg() ||
9682           argOpers[valArgIndx]->isImm()) &&
9683          "invalid operand");
9684   if (argOpers[valArgIndx]->isReg())
9685     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9686   else
9687     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9688   MIB.addReg(tt);
9689   (*MIB).addOperand(*argOpers[valArgIndx]);
9690
9691   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9692   MIB.addReg(t1);
9693
9694   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9695   for (int i=0; i <= lastAddrIndx; ++i)
9696     (*MIB).addOperand(*argOpers[i]);
9697   MIB.addReg(t2);
9698   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9699   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9700                     bInstr->memoperands_end());
9701
9702   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9703   MIB.addReg(EAXreg);
9704
9705   // insert branch
9706   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9707
9708   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9709   return nextMBB;
9710 }
9711
9712 // private utility function:  64 bit atomics on 32 bit host.
9713 MachineBasicBlock *
9714 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9715                                                        MachineBasicBlock *MBB,
9716                                                        unsigned regOpcL,
9717                                                        unsigned regOpcH,
9718                                                        unsigned immOpcL,
9719                                                        unsigned immOpcH,
9720                                                        bool invSrc) const {
9721   // For the atomic bitwise operator, we generate
9722   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9723   //     ld t1,t2 = [bitinstr.addr]
9724   //   newMBB:
9725   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9726   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9727   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9728   //     mov ECX, EBX <- t5, t6
9729   //     mov EAX, EDX <- t1, t2
9730   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9731   //     mov t3, t4 <- EAX, EDX
9732   //     bz  newMBB
9733   //     result in out1, out2
9734   //     fallthrough -->nextMBB
9735
9736   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9737   const unsigned LoadOpc = X86::MOV32rm;
9738   const unsigned NotOpc = X86::NOT32r;
9739   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9740   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9741   MachineFunction::iterator MBBIter = MBB;
9742   ++MBBIter;
9743
9744   /// First build the CFG
9745   MachineFunction *F = MBB->getParent();
9746   MachineBasicBlock *thisMBB = MBB;
9747   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9748   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9749   F->insert(MBBIter, newMBB);
9750   F->insert(MBBIter, nextMBB);
9751
9752   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9753   nextMBB->splice(nextMBB->begin(), thisMBB,
9754                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9755                   thisMBB->end());
9756   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9757
9758   // Update thisMBB to fall through to newMBB
9759   thisMBB->addSuccessor(newMBB);
9760
9761   // newMBB jumps to itself and fall through to nextMBB
9762   newMBB->addSuccessor(nextMBB);
9763   newMBB->addSuccessor(newMBB);
9764
9765   DebugLoc dl = bInstr->getDebugLoc();
9766   // Insert instructions into newMBB based on incoming instruction
9767   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9768   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9769          "unexpected number of operands");
9770   MachineOperand& dest1Oper = bInstr->getOperand(0);
9771   MachineOperand& dest2Oper = bInstr->getOperand(1);
9772   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9773   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9774     argOpers[i] = &bInstr->getOperand(i+2);
9775
9776     // We use some of the operands multiple times, so conservatively just
9777     // clear any kill flags that might be present.
9778     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9779       argOpers[i]->setIsKill(false);
9780   }
9781
9782   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9783   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9784
9785   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9786   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9787   for (int i=0; i <= lastAddrIndx; ++i)
9788     (*MIB).addOperand(*argOpers[i]);
9789   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9790   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9791   // add 4 to displacement.
9792   for (int i=0; i <= lastAddrIndx-2; ++i)
9793     (*MIB).addOperand(*argOpers[i]);
9794   MachineOperand newOp3 = *(argOpers[3]);
9795   if (newOp3.isImm())
9796     newOp3.setImm(newOp3.getImm()+4);
9797   else
9798     newOp3.setOffset(newOp3.getOffset()+4);
9799   (*MIB).addOperand(newOp3);
9800   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9801
9802   // t3/4 are defined later, at the bottom of the loop
9803   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9804   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9805   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9806     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9807   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9808     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9809
9810   // The subsequent operations should be using the destination registers of
9811   //the PHI instructions.
9812   if (invSrc) {
9813     t1 = F->getRegInfo().createVirtualRegister(RC);
9814     t2 = F->getRegInfo().createVirtualRegister(RC);
9815     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9816     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9817   } else {
9818     t1 = dest1Oper.getReg();
9819     t2 = dest2Oper.getReg();
9820   }
9821
9822   int valArgIndx = lastAddrIndx + 1;
9823   assert((argOpers[valArgIndx]->isReg() ||
9824           argOpers[valArgIndx]->isImm()) &&
9825          "invalid operand");
9826   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9827   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9828   if (argOpers[valArgIndx]->isReg())
9829     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9830   else
9831     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9832   if (regOpcL != X86::MOV32rr)
9833     MIB.addReg(t1);
9834   (*MIB).addOperand(*argOpers[valArgIndx]);
9835   assert(argOpers[valArgIndx + 1]->isReg() ==
9836          argOpers[valArgIndx]->isReg());
9837   assert(argOpers[valArgIndx + 1]->isImm() ==
9838          argOpers[valArgIndx]->isImm());
9839   if (argOpers[valArgIndx + 1]->isReg())
9840     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9841   else
9842     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9843   if (regOpcH != X86::MOV32rr)
9844     MIB.addReg(t2);
9845   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9846
9847   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9848   MIB.addReg(t1);
9849   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9850   MIB.addReg(t2);
9851
9852   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9853   MIB.addReg(t5);
9854   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9855   MIB.addReg(t6);
9856
9857   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9858   for (int i=0; i <= lastAddrIndx; ++i)
9859     (*MIB).addOperand(*argOpers[i]);
9860
9861   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9862   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9863                     bInstr->memoperands_end());
9864
9865   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9866   MIB.addReg(X86::EAX);
9867   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9868   MIB.addReg(X86::EDX);
9869
9870   // insert branch
9871   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9872
9873   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9874   return nextMBB;
9875 }
9876
9877 // private utility function
9878 MachineBasicBlock *
9879 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9880                                                       MachineBasicBlock *MBB,
9881                                                       unsigned cmovOpc) const {
9882   // For the atomic min/max operator, we generate
9883   //   thisMBB:
9884   //   newMBB:
9885   //     ld t1 = [min/max.addr]
9886   //     mov t2 = [min/max.val]
9887   //     cmp  t1, t2
9888   //     cmov[cond] t2 = t1
9889   //     mov EAX = t1
9890   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9891   //     bz   newMBB
9892   //     fallthrough -->nextMBB
9893   //
9894   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9895   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9896   MachineFunction::iterator MBBIter = MBB;
9897   ++MBBIter;
9898
9899   /// First build the CFG
9900   MachineFunction *F = MBB->getParent();
9901   MachineBasicBlock *thisMBB = MBB;
9902   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9904   F->insert(MBBIter, newMBB);
9905   F->insert(MBBIter, nextMBB);
9906
9907   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9908   nextMBB->splice(nextMBB->begin(), thisMBB,
9909                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9910                   thisMBB->end());
9911   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9912
9913   // Update thisMBB to fall through to newMBB
9914   thisMBB->addSuccessor(newMBB);
9915
9916   // newMBB jumps to newMBB and fall through to nextMBB
9917   newMBB->addSuccessor(nextMBB);
9918   newMBB->addSuccessor(newMBB);
9919
9920   DebugLoc dl = mInstr->getDebugLoc();
9921   // Insert instructions into newMBB based on incoming instruction
9922   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9923          "unexpected number of operands");
9924   MachineOperand& destOper = mInstr->getOperand(0);
9925   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9926   int numArgs = mInstr->getNumOperands() - 1;
9927   for (int i=0; i < numArgs; ++i)
9928     argOpers[i] = &mInstr->getOperand(i+1);
9929
9930   // x86 address has 4 operands: base, index, scale, and displacement
9931   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9932   int valArgIndx = lastAddrIndx + 1;
9933
9934   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9935   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9936   for (int i=0; i <= lastAddrIndx; ++i)
9937     (*MIB).addOperand(*argOpers[i]);
9938
9939   // We only support register and immediate values
9940   assert((argOpers[valArgIndx]->isReg() ||
9941           argOpers[valArgIndx]->isImm()) &&
9942          "invalid operand");
9943
9944   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9945   if (argOpers[valArgIndx]->isReg())
9946     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9947   else
9948     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9949   (*MIB).addOperand(*argOpers[valArgIndx]);
9950
9951   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9952   MIB.addReg(t1);
9953
9954   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9955   MIB.addReg(t1);
9956   MIB.addReg(t2);
9957
9958   // Generate movc
9959   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9960   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9961   MIB.addReg(t2);
9962   MIB.addReg(t1);
9963
9964   // Cmp and exchange if none has modified the memory location
9965   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9966   for (int i=0; i <= lastAddrIndx; ++i)
9967     (*MIB).addOperand(*argOpers[i]);
9968   MIB.addReg(t3);
9969   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9970   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9971                     mInstr->memoperands_end());
9972
9973   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9974   MIB.addReg(X86::EAX);
9975
9976   // insert branch
9977   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9978
9979   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9980   return nextMBB;
9981 }
9982
9983 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9984 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9985 // in the .td file.
9986 MachineBasicBlock *
9987 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9988                             unsigned numArgs, bool memArg) const {
9989   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9990          "Target must have SSE4.2 or AVX features enabled");
9991
9992   DebugLoc dl = MI->getDebugLoc();
9993   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9994   unsigned Opc;
9995   if (!Subtarget->hasAVX()) {
9996     if (memArg)
9997       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9998     else
9999       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10000   } else {
10001     if (memArg)
10002       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10003     else
10004       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10005   }
10006
10007   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10008   for (unsigned i = 0; i < numArgs; ++i) {
10009     MachineOperand &Op = MI->getOperand(i+1);
10010     if (!(Op.isReg() && Op.isImplicit()))
10011       MIB.addOperand(Op);
10012   }
10013   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10014     .addReg(X86::XMM0);
10015
10016   MI->eraseFromParent();
10017   return BB;
10018 }
10019
10020 MachineBasicBlock *
10021 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10022   DebugLoc dl = MI->getDebugLoc();
10023   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10024
10025   // Address into RAX/EAX, other two args into ECX, EDX.
10026   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10027   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10028   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10029   for (int i = 0; i < X86::AddrNumOperands; ++i)
10030     MIB.addOperand(MI->getOperand(i));
10031
10032   unsigned ValOps = X86::AddrNumOperands;
10033   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10034     .addReg(MI->getOperand(ValOps).getReg());
10035   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10036     .addReg(MI->getOperand(ValOps+1).getReg());
10037
10038   // The instruction doesn't actually take any operands though.
10039   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10040
10041   MI->eraseFromParent(); // The pseudo is gone now.
10042   return BB;
10043 }
10044
10045 MachineBasicBlock *
10046 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10047   DebugLoc dl = MI->getDebugLoc();
10048   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10049
10050   // First arg in ECX, the second in EAX.
10051   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10052     .addReg(MI->getOperand(0).getReg());
10053   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10054     .addReg(MI->getOperand(1).getReg());
10055
10056   // The instruction doesn't actually take any operands though.
10057   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10058
10059   MI->eraseFromParent(); // The pseudo is gone now.
10060   return BB;
10061 }
10062
10063 MachineBasicBlock *
10064 X86TargetLowering::EmitVAARG64WithCustomInserter(
10065                    MachineInstr *MI,
10066                    MachineBasicBlock *MBB) const {
10067   // Emit va_arg instruction on X86-64.
10068
10069   // Operands to this pseudo-instruction:
10070   // 0  ) Output        : destination address (reg)
10071   // 1-5) Input         : va_list address (addr, i64mem)
10072   // 6  ) ArgSize       : Size (in bytes) of vararg type
10073   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10074   // 8  ) Align         : Alignment of type
10075   // 9  ) EFLAGS (implicit-def)
10076
10077   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10078   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10079
10080   unsigned DestReg = MI->getOperand(0).getReg();
10081   MachineOperand &Base = MI->getOperand(1);
10082   MachineOperand &Scale = MI->getOperand(2);
10083   MachineOperand &Index = MI->getOperand(3);
10084   MachineOperand &Disp = MI->getOperand(4);
10085   MachineOperand &Segment = MI->getOperand(5);
10086   unsigned ArgSize = MI->getOperand(6).getImm();
10087   unsigned ArgMode = MI->getOperand(7).getImm();
10088   unsigned Align = MI->getOperand(8).getImm();
10089
10090   // Memory Reference
10091   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10092   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10093   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10094
10095   // Machine Information
10096   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10097   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10098   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10099   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10100   DebugLoc DL = MI->getDebugLoc();
10101
10102   // struct va_list {
10103   //   i32   gp_offset
10104   //   i32   fp_offset
10105   //   i64   overflow_area (address)
10106   //   i64   reg_save_area (address)
10107   // }
10108   // sizeof(va_list) = 24
10109   // alignment(va_list) = 8
10110
10111   unsigned TotalNumIntRegs = 6;
10112   unsigned TotalNumXMMRegs = 8;
10113   bool UseGPOffset = (ArgMode == 1);
10114   bool UseFPOffset = (ArgMode == 2);
10115   unsigned MaxOffset = TotalNumIntRegs * 8 +
10116                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10117
10118   /* Align ArgSize to a multiple of 8 */
10119   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10120   bool NeedsAlign = (Align > 8);
10121
10122   MachineBasicBlock *thisMBB = MBB;
10123   MachineBasicBlock *overflowMBB;
10124   MachineBasicBlock *offsetMBB;
10125   MachineBasicBlock *endMBB;
10126
10127   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10128   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10129   unsigned OffsetReg = 0;
10130
10131   if (!UseGPOffset && !UseFPOffset) {
10132     // If we only pull from the overflow region, we don't create a branch.
10133     // We don't need to alter control flow.
10134     OffsetDestReg = 0; // unused
10135     OverflowDestReg = DestReg;
10136
10137     offsetMBB = NULL;
10138     overflowMBB = thisMBB;
10139     endMBB = thisMBB;
10140   } else {
10141     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10142     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10143     // If not, pull from overflow_area. (branch to overflowMBB)
10144     //
10145     //       thisMBB
10146     //         |     .
10147     //         |        .
10148     //     offsetMBB   overflowMBB
10149     //         |        .
10150     //         |     .
10151     //        endMBB
10152
10153     // Registers for the PHI in endMBB
10154     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10155     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10156
10157     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10158     MachineFunction *MF = MBB->getParent();
10159     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10160     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10161     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10162
10163     MachineFunction::iterator MBBIter = MBB;
10164     ++MBBIter;
10165
10166     // Insert the new basic blocks
10167     MF->insert(MBBIter, offsetMBB);
10168     MF->insert(MBBIter, overflowMBB);
10169     MF->insert(MBBIter, endMBB);
10170
10171     // Transfer the remainder of MBB and its successor edges to endMBB.
10172     endMBB->splice(endMBB->begin(), thisMBB,
10173                     llvm::next(MachineBasicBlock::iterator(MI)),
10174                     thisMBB->end());
10175     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10176
10177     // Make offsetMBB and overflowMBB successors of thisMBB
10178     thisMBB->addSuccessor(offsetMBB);
10179     thisMBB->addSuccessor(overflowMBB);
10180
10181     // endMBB is a successor of both offsetMBB and overflowMBB
10182     offsetMBB->addSuccessor(endMBB);
10183     overflowMBB->addSuccessor(endMBB);
10184
10185     // Load the offset value into a register
10186     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10187     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10188       .addOperand(Base)
10189       .addOperand(Scale)
10190       .addOperand(Index)
10191       .addDisp(Disp, UseFPOffset ? 4 : 0)
10192       .addOperand(Segment)
10193       .setMemRefs(MMOBegin, MMOEnd);
10194
10195     // Check if there is enough room left to pull this argument.
10196     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10197       .addReg(OffsetReg)
10198       .addImm(MaxOffset + 8 - ArgSizeA8);
10199
10200     // Branch to "overflowMBB" if offset >= max
10201     // Fall through to "offsetMBB" otherwise
10202     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10203       .addMBB(overflowMBB);
10204   }
10205
10206   // In offsetMBB, emit code to use the reg_save_area.
10207   if (offsetMBB) {
10208     assert(OffsetReg != 0);
10209
10210     // Read the reg_save_area address.
10211     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10212     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10213       .addOperand(Base)
10214       .addOperand(Scale)
10215       .addOperand(Index)
10216       .addDisp(Disp, 16)
10217       .addOperand(Segment)
10218       .setMemRefs(MMOBegin, MMOEnd);
10219
10220     // Zero-extend the offset
10221     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10222       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10223         .addImm(0)
10224         .addReg(OffsetReg)
10225         .addImm(X86::sub_32bit);
10226
10227     // Add the offset to the reg_save_area to get the final address.
10228     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10229       .addReg(OffsetReg64)
10230       .addReg(RegSaveReg);
10231
10232     // Compute the offset for the next argument
10233     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10234     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10235       .addReg(OffsetReg)
10236       .addImm(UseFPOffset ? 16 : 8);
10237
10238     // Store it back into the va_list.
10239     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10240       .addOperand(Base)
10241       .addOperand(Scale)
10242       .addOperand(Index)
10243       .addDisp(Disp, UseFPOffset ? 4 : 0)
10244       .addOperand(Segment)
10245       .addReg(NextOffsetReg)
10246       .setMemRefs(MMOBegin, MMOEnd);
10247
10248     // Jump to endMBB
10249     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10250       .addMBB(endMBB);
10251   }
10252
10253   //
10254   // Emit code to use overflow area
10255   //
10256
10257   // Load the overflow_area address into a register.
10258   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10259   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10260     .addOperand(Base)
10261     .addOperand(Scale)
10262     .addOperand(Index)
10263     .addDisp(Disp, 8)
10264     .addOperand(Segment)
10265     .setMemRefs(MMOBegin, MMOEnd);
10266
10267   // If we need to align it, do so. Otherwise, just copy the address
10268   // to OverflowDestReg.
10269   if (NeedsAlign) {
10270     // Align the overflow address
10271     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10272     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10273
10274     // aligned_addr = (addr + (align-1)) & ~(align-1)
10275     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10276       .addReg(OverflowAddrReg)
10277       .addImm(Align-1);
10278
10279     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10280       .addReg(TmpReg)
10281       .addImm(~(uint64_t)(Align-1));
10282   } else {
10283     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10284       .addReg(OverflowAddrReg);
10285   }
10286
10287   // Compute the next overflow address after this argument.
10288   // (the overflow address should be kept 8-byte aligned)
10289   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10290   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10291     .addReg(OverflowDestReg)
10292     .addImm(ArgSizeA8);
10293
10294   // Store the new overflow address.
10295   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10296     .addOperand(Base)
10297     .addOperand(Scale)
10298     .addOperand(Index)
10299     .addDisp(Disp, 8)
10300     .addOperand(Segment)
10301     .addReg(NextAddrReg)
10302     .setMemRefs(MMOBegin, MMOEnd);
10303
10304   // If we branched, emit the PHI to the front of endMBB.
10305   if (offsetMBB) {
10306     BuildMI(*endMBB, endMBB->begin(), DL,
10307             TII->get(X86::PHI), DestReg)
10308       .addReg(OffsetDestReg).addMBB(offsetMBB)
10309       .addReg(OverflowDestReg).addMBB(overflowMBB);
10310   }
10311
10312   // Erase the pseudo instruction
10313   MI->eraseFromParent();
10314
10315   return endMBB;
10316 }
10317
10318 MachineBasicBlock *
10319 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10320                                                  MachineInstr *MI,
10321                                                  MachineBasicBlock *MBB) const {
10322   // Emit code to save XMM registers to the stack. The ABI says that the
10323   // number of registers to save is given in %al, so it's theoretically
10324   // possible to do an indirect jump trick to avoid saving all of them,
10325   // however this code takes a simpler approach and just executes all
10326   // of the stores if %al is non-zero. It's less code, and it's probably
10327   // easier on the hardware branch predictor, and stores aren't all that
10328   // expensive anyway.
10329
10330   // Create the new basic blocks. One block contains all the XMM stores,
10331   // and one block is the final destination regardless of whether any
10332   // stores were performed.
10333   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10334   MachineFunction *F = MBB->getParent();
10335   MachineFunction::iterator MBBIter = MBB;
10336   ++MBBIter;
10337   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10338   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10339   F->insert(MBBIter, XMMSaveMBB);
10340   F->insert(MBBIter, EndMBB);
10341
10342   // Transfer the remainder of MBB and its successor edges to EndMBB.
10343   EndMBB->splice(EndMBB->begin(), MBB,
10344                  llvm::next(MachineBasicBlock::iterator(MI)),
10345                  MBB->end());
10346   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10347
10348   // The original block will now fall through to the XMM save block.
10349   MBB->addSuccessor(XMMSaveMBB);
10350   // The XMMSaveMBB will fall through to the end block.
10351   XMMSaveMBB->addSuccessor(EndMBB);
10352
10353   // Now add the instructions.
10354   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10355   DebugLoc DL = MI->getDebugLoc();
10356
10357   unsigned CountReg = MI->getOperand(0).getReg();
10358   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10359   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10360
10361   if (!Subtarget->isTargetWin64()) {
10362     // If %al is 0, branch around the XMM save block.
10363     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10364     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10365     MBB->addSuccessor(EndMBB);
10366   }
10367
10368   // In the XMM save block, save all the XMM argument registers.
10369   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10370     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10371     MachineMemOperand *MMO =
10372       F->getMachineMemOperand(
10373           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10374         MachineMemOperand::MOStore,
10375         /*Size=*/16, /*Align=*/16);
10376     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10377       .addFrameIndex(RegSaveFrameIndex)
10378       .addImm(/*Scale=*/1)
10379       .addReg(/*IndexReg=*/0)
10380       .addImm(/*Disp=*/Offset)
10381       .addReg(/*Segment=*/0)
10382       .addReg(MI->getOperand(i).getReg())
10383       .addMemOperand(MMO);
10384   }
10385
10386   MI->eraseFromParent();   // The pseudo instruction is gone now.
10387
10388   return EndMBB;
10389 }
10390
10391 MachineBasicBlock *
10392 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10393                                      MachineBasicBlock *BB) const {
10394   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10395   DebugLoc DL = MI->getDebugLoc();
10396
10397   // To "insert" a SELECT_CC instruction, we actually have to insert the
10398   // diamond control-flow pattern.  The incoming instruction knows the
10399   // destination vreg to set, the condition code register to branch on, the
10400   // true/false values to select between, and a branch opcode to use.
10401   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10402   MachineFunction::iterator It = BB;
10403   ++It;
10404
10405   //  thisMBB:
10406   //  ...
10407   //   TrueVal = ...
10408   //   cmpTY ccX, r1, r2
10409   //   bCC copy1MBB
10410   //   fallthrough --> copy0MBB
10411   MachineBasicBlock *thisMBB = BB;
10412   MachineFunction *F = BB->getParent();
10413   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10414   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10415   F->insert(It, copy0MBB);
10416   F->insert(It, sinkMBB);
10417
10418   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10419   // live into the sink and copy blocks.
10420   const MachineFunction *MF = BB->getParent();
10421   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10422   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10423
10424   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10425     const MachineOperand &MO = MI->getOperand(I);
10426     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10427     unsigned Reg = MO.getReg();
10428     if (Reg != X86::EFLAGS) continue;
10429     copy0MBB->addLiveIn(Reg);
10430     sinkMBB->addLiveIn(Reg);
10431   }
10432
10433   // Transfer the remainder of BB and its successor edges to sinkMBB.
10434   sinkMBB->splice(sinkMBB->begin(), BB,
10435                   llvm::next(MachineBasicBlock::iterator(MI)),
10436                   BB->end());
10437   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10438
10439   // Add the true and fallthrough blocks as its successors.
10440   BB->addSuccessor(copy0MBB);
10441   BB->addSuccessor(sinkMBB);
10442
10443   // Create the conditional branch instruction.
10444   unsigned Opc =
10445     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10446   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10447
10448   //  copy0MBB:
10449   //   %FalseValue = ...
10450   //   # fallthrough to sinkMBB
10451   copy0MBB->addSuccessor(sinkMBB);
10452
10453   //  sinkMBB:
10454   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10455   //  ...
10456   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10457           TII->get(X86::PHI), MI->getOperand(0).getReg())
10458     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10459     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10460
10461   MI->eraseFromParent();   // The pseudo instruction is gone now.
10462   return sinkMBB;
10463 }
10464
10465 MachineBasicBlock *
10466 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10467                                           MachineBasicBlock *BB) const {
10468   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10469   DebugLoc DL = MI->getDebugLoc();
10470
10471   assert(!Subtarget->isTargetEnvMacho());
10472
10473   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10474   // non-trivial part is impdef of ESP.
10475
10476   if (Subtarget->isTargetWin64()) {
10477     if (Subtarget->isTargetCygMing()) {
10478       // ___chkstk(Mingw64):
10479       // Clobbers R10, R11, RAX and EFLAGS.
10480       // Updates RSP.
10481       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10482         .addExternalSymbol("___chkstk")
10483         .addReg(X86::RAX, RegState::Implicit)
10484         .addReg(X86::RSP, RegState::Implicit)
10485         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10486         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10487         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10488     } else {
10489       // __chkstk(MSVCRT): does not update stack pointer.
10490       // Clobbers R10, R11 and EFLAGS.
10491       // FIXME: RAX(allocated size) might be reused and not killed.
10492       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10493         .addExternalSymbol("__chkstk")
10494         .addReg(X86::RAX, RegState::Implicit)
10495         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10496       // RAX has the offset to subtracted from RSP.
10497       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10498         .addReg(X86::RSP)
10499         .addReg(X86::RAX);
10500     }
10501   } else {
10502     const char *StackProbeSymbol =
10503       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10504
10505     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10506       .addExternalSymbol(StackProbeSymbol)
10507       .addReg(X86::EAX, RegState::Implicit)
10508       .addReg(X86::ESP, RegState::Implicit)
10509       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10510       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10511       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10512   }
10513
10514   MI->eraseFromParent();   // The pseudo instruction is gone now.
10515   return BB;
10516 }
10517
10518 MachineBasicBlock *
10519 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10520                                       MachineBasicBlock *BB) const {
10521   // This is pretty easy.  We're taking the value that we received from
10522   // our load from the relocation, sticking it in either RDI (x86-64)
10523   // or EAX and doing an indirect call.  The return value will then
10524   // be in the normal return register.
10525   const X86InstrInfo *TII
10526     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10527   DebugLoc DL = MI->getDebugLoc();
10528   MachineFunction *F = BB->getParent();
10529
10530   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10531   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10532
10533   if (Subtarget->is64Bit()) {
10534     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10535                                       TII->get(X86::MOV64rm), X86::RDI)
10536     .addReg(X86::RIP)
10537     .addImm(0).addReg(0)
10538     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10539                       MI->getOperand(3).getTargetFlags())
10540     .addReg(0);
10541     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10542     addDirectMem(MIB, X86::RDI);
10543   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10544     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10545                                       TII->get(X86::MOV32rm), X86::EAX)
10546     .addReg(0)
10547     .addImm(0).addReg(0)
10548     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10549                       MI->getOperand(3).getTargetFlags())
10550     .addReg(0);
10551     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10552     addDirectMem(MIB, X86::EAX);
10553   } else {
10554     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10555                                       TII->get(X86::MOV32rm), X86::EAX)
10556     .addReg(TII->getGlobalBaseReg(F))
10557     .addImm(0).addReg(0)
10558     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10559                       MI->getOperand(3).getTargetFlags())
10560     .addReg(0);
10561     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10562     addDirectMem(MIB, X86::EAX);
10563   }
10564
10565   MI->eraseFromParent(); // The pseudo instruction is gone now.
10566   return BB;
10567 }
10568
10569 MachineBasicBlock *
10570 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10571                                                MachineBasicBlock *BB) const {
10572   switch (MI->getOpcode()) {
10573   default: assert(false && "Unexpected instr type to insert");
10574   case X86::TAILJMPd64:
10575   case X86::TAILJMPr64:
10576   case X86::TAILJMPm64:
10577     assert(!"TAILJMP64 would not be touched here.");
10578   case X86::TCRETURNdi64:
10579   case X86::TCRETURNri64:
10580   case X86::TCRETURNmi64:
10581     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10582     // On AMD64, additional defs should be added before register allocation.
10583     if (!Subtarget->isTargetWin64()) {
10584       MI->addRegisterDefined(X86::RSI);
10585       MI->addRegisterDefined(X86::RDI);
10586       MI->addRegisterDefined(X86::XMM6);
10587       MI->addRegisterDefined(X86::XMM7);
10588       MI->addRegisterDefined(X86::XMM8);
10589       MI->addRegisterDefined(X86::XMM9);
10590       MI->addRegisterDefined(X86::XMM10);
10591       MI->addRegisterDefined(X86::XMM11);
10592       MI->addRegisterDefined(X86::XMM12);
10593       MI->addRegisterDefined(X86::XMM13);
10594       MI->addRegisterDefined(X86::XMM14);
10595       MI->addRegisterDefined(X86::XMM15);
10596     }
10597     return BB;
10598   case X86::WIN_ALLOCA:
10599     return EmitLoweredWinAlloca(MI, BB);
10600   case X86::TLSCall_32:
10601   case X86::TLSCall_64:
10602     return EmitLoweredTLSCall(MI, BB);
10603   case X86::CMOV_GR8:
10604   case X86::CMOV_FR32:
10605   case X86::CMOV_FR64:
10606   case X86::CMOV_V4F32:
10607   case X86::CMOV_V2F64:
10608   case X86::CMOV_V2I64:
10609   case X86::CMOV_GR16:
10610   case X86::CMOV_GR32:
10611   case X86::CMOV_RFP32:
10612   case X86::CMOV_RFP64:
10613   case X86::CMOV_RFP80:
10614     return EmitLoweredSelect(MI, BB);
10615
10616   case X86::FP32_TO_INT16_IN_MEM:
10617   case X86::FP32_TO_INT32_IN_MEM:
10618   case X86::FP32_TO_INT64_IN_MEM:
10619   case X86::FP64_TO_INT16_IN_MEM:
10620   case X86::FP64_TO_INT32_IN_MEM:
10621   case X86::FP64_TO_INT64_IN_MEM:
10622   case X86::FP80_TO_INT16_IN_MEM:
10623   case X86::FP80_TO_INT32_IN_MEM:
10624   case X86::FP80_TO_INT64_IN_MEM: {
10625     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10626     DebugLoc DL = MI->getDebugLoc();
10627
10628     // Change the floating point control register to use "round towards zero"
10629     // mode when truncating to an integer value.
10630     MachineFunction *F = BB->getParent();
10631     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10632     addFrameReference(BuildMI(*BB, MI, DL,
10633                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10634
10635     // Load the old value of the high byte of the control word...
10636     unsigned OldCW =
10637       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10638     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10639                       CWFrameIdx);
10640
10641     // Set the high part to be round to zero...
10642     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10643       .addImm(0xC7F);
10644
10645     // Reload the modified control word now...
10646     addFrameReference(BuildMI(*BB, MI, DL,
10647                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10648
10649     // Restore the memory image of control word to original value
10650     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10651       .addReg(OldCW);
10652
10653     // Get the X86 opcode to use.
10654     unsigned Opc;
10655     switch (MI->getOpcode()) {
10656     default: llvm_unreachable("illegal opcode!");
10657     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10658     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10659     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10660     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10661     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10662     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10663     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10664     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10665     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10666     }
10667
10668     X86AddressMode AM;
10669     MachineOperand &Op = MI->getOperand(0);
10670     if (Op.isReg()) {
10671       AM.BaseType = X86AddressMode::RegBase;
10672       AM.Base.Reg = Op.getReg();
10673     } else {
10674       AM.BaseType = X86AddressMode::FrameIndexBase;
10675       AM.Base.FrameIndex = Op.getIndex();
10676     }
10677     Op = MI->getOperand(1);
10678     if (Op.isImm())
10679       AM.Scale = Op.getImm();
10680     Op = MI->getOperand(2);
10681     if (Op.isImm())
10682       AM.IndexReg = Op.getImm();
10683     Op = MI->getOperand(3);
10684     if (Op.isGlobal()) {
10685       AM.GV = Op.getGlobal();
10686     } else {
10687       AM.Disp = Op.getImm();
10688     }
10689     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10690                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10691
10692     // Reload the original control word now.
10693     addFrameReference(BuildMI(*BB, MI, DL,
10694                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10695
10696     MI->eraseFromParent();   // The pseudo instruction is gone now.
10697     return BB;
10698   }
10699     // String/text processing lowering.
10700   case X86::PCMPISTRM128REG:
10701   case X86::VPCMPISTRM128REG:
10702     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10703   case X86::PCMPISTRM128MEM:
10704   case X86::VPCMPISTRM128MEM:
10705     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10706   case X86::PCMPESTRM128REG:
10707   case X86::VPCMPESTRM128REG:
10708     return EmitPCMP(MI, BB, 5, false /* in mem */);
10709   case X86::PCMPESTRM128MEM:
10710   case X86::VPCMPESTRM128MEM:
10711     return EmitPCMP(MI, BB, 5, true /* in mem */);
10712
10713     // Thread synchronization.
10714   case X86::MONITOR:
10715     return EmitMonitor(MI, BB);
10716   case X86::MWAIT:
10717     return EmitMwait(MI, BB);
10718
10719     // Atomic Lowering.
10720   case X86::ATOMAND32:
10721     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10722                                                X86::AND32ri, X86::MOV32rm,
10723                                                X86::LCMPXCHG32,
10724                                                X86::NOT32r, X86::EAX,
10725                                                X86::GR32RegisterClass);
10726   case X86::ATOMOR32:
10727     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10728                                                X86::OR32ri, X86::MOV32rm,
10729                                                X86::LCMPXCHG32,
10730                                                X86::NOT32r, X86::EAX,
10731                                                X86::GR32RegisterClass);
10732   case X86::ATOMXOR32:
10733     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10734                                                X86::XOR32ri, X86::MOV32rm,
10735                                                X86::LCMPXCHG32,
10736                                                X86::NOT32r, X86::EAX,
10737                                                X86::GR32RegisterClass);
10738   case X86::ATOMNAND32:
10739     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10740                                                X86::AND32ri, X86::MOV32rm,
10741                                                X86::LCMPXCHG32,
10742                                                X86::NOT32r, X86::EAX,
10743                                                X86::GR32RegisterClass, true);
10744   case X86::ATOMMIN32:
10745     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10746   case X86::ATOMMAX32:
10747     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10748   case X86::ATOMUMIN32:
10749     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10750   case X86::ATOMUMAX32:
10751     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10752
10753   case X86::ATOMAND16:
10754     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10755                                                X86::AND16ri, X86::MOV16rm,
10756                                                X86::LCMPXCHG16,
10757                                                X86::NOT16r, X86::AX,
10758                                                X86::GR16RegisterClass);
10759   case X86::ATOMOR16:
10760     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10761                                                X86::OR16ri, X86::MOV16rm,
10762                                                X86::LCMPXCHG16,
10763                                                X86::NOT16r, X86::AX,
10764                                                X86::GR16RegisterClass);
10765   case X86::ATOMXOR16:
10766     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10767                                                X86::XOR16ri, X86::MOV16rm,
10768                                                X86::LCMPXCHG16,
10769                                                X86::NOT16r, X86::AX,
10770                                                X86::GR16RegisterClass);
10771   case X86::ATOMNAND16:
10772     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10773                                                X86::AND16ri, X86::MOV16rm,
10774                                                X86::LCMPXCHG16,
10775                                                X86::NOT16r, X86::AX,
10776                                                X86::GR16RegisterClass, true);
10777   case X86::ATOMMIN16:
10778     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10779   case X86::ATOMMAX16:
10780     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10781   case X86::ATOMUMIN16:
10782     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10783   case X86::ATOMUMAX16:
10784     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10785
10786   case X86::ATOMAND8:
10787     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10788                                                X86::AND8ri, X86::MOV8rm,
10789                                                X86::LCMPXCHG8,
10790                                                X86::NOT8r, X86::AL,
10791                                                X86::GR8RegisterClass);
10792   case X86::ATOMOR8:
10793     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10794                                                X86::OR8ri, X86::MOV8rm,
10795                                                X86::LCMPXCHG8,
10796                                                X86::NOT8r, X86::AL,
10797                                                X86::GR8RegisterClass);
10798   case X86::ATOMXOR8:
10799     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10800                                                X86::XOR8ri, X86::MOV8rm,
10801                                                X86::LCMPXCHG8,
10802                                                X86::NOT8r, X86::AL,
10803                                                X86::GR8RegisterClass);
10804   case X86::ATOMNAND8:
10805     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10806                                                X86::AND8ri, X86::MOV8rm,
10807                                                X86::LCMPXCHG8,
10808                                                X86::NOT8r, X86::AL,
10809                                                X86::GR8RegisterClass, true);
10810   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10811   // This group is for 64-bit host.
10812   case X86::ATOMAND64:
10813     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10814                                                X86::AND64ri32, X86::MOV64rm,
10815                                                X86::LCMPXCHG64,
10816                                                X86::NOT64r, X86::RAX,
10817                                                X86::GR64RegisterClass);
10818   case X86::ATOMOR64:
10819     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10820                                                X86::OR64ri32, X86::MOV64rm,
10821                                                X86::LCMPXCHG64,
10822                                                X86::NOT64r, X86::RAX,
10823                                                X86::GR64RegisterClass);
10824   case X86::ATOMXOR64:
10825     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10826                                                X86::XOR64ri32, X86::MOV64rm,
10827                                                X86::LCMPXCHG64,
10828                                                X86::NOT64r, X86::RAX,
10829                                                X86::GR64RegisterClass);
10830   case X86::ATOMNAND64:
10831     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10832                                                X86::AND64ri32, X86::MOV64rm,
10833                                                X86::LCMPXCHG64,
10834                                                X86::NOT64r, X86::RAX,
10835                                                X86::GR64RegisterClass, true);
10836   case X86::ATOMMIN64:
10837     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10838   case X86::ATOMMAX64:
10839     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10840   case X86::ATOMUMIN64:
10841     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10842   case X86::ATOMUMAX64:
10843     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10844
10845   // This group does 64-bit operations on a 32-bit host.
10846   case X86::ATOMAND6432:
10847     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10848                                                X86::AND32rr, X86::AND32rr,
10849                                                X86::AND32ri, X86::AND32ri,
10850                                                false);
10851   case X86::ATOMOR6432:
10852     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10853                                                X86::OR32rr, X86::OR32rr,
10854                                                X86::OR32ri, X86::OR32ri,
10855                                                false);
10856   case X86::ATOMXOR6432:
10857     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10858                                                X86::XOR32rr, X86::XOR32rr,
10859                                                X86::XOR32ri, X86::XOR32ri,
10860                                                false);
10861   case X86::ATOMNAND6432:
10862     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10863                                                X86::AND32rr, X86::AND32rr,
10864                                                X86::AND32ri, X86::AND32ri,
10865                                                true);
10866   case X86::ATOMADD6432:
10867     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10868                                                X86::ADD32rr, X86::ADC32rr,
10869                                                X86::ADD32ri, X86::ADC32ri,
10870                                                false);
10871   case X86::ATOMSUB6432:
10872     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10873                                                X86::SUB32rr, X86::SBB32rr,
10874                                                X86::SUB32ri, X86::SBB32ri,
10875                                                false);
10876   case X86::ATOMSWAP6432:
10877     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10878                                                X86::MOV32rr, X86::MOV32rr,
10879                                                X86::MOV32ri, X86::MOV32ri,
10880                                                false);
10881   case X86::VASTART_SAVE_XMM_REGS:
10882     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10883
10884   case X86::VAARG_64:
10885     return EmitVAARG64WithCustomInserter(MI, BB);
10886   }
10887 }
10888
10889 //===----------------------------------------------------------------------===//
10890 //                           X86 Optimization Hooks
10891 //===----------------------------------------------------------------------===//
10892
10893 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10894                                                        const APInt &Mask,
10895                                                        APInt &KnownZero,
10896                                                        APInt &KnownOne,
10897                                                        const SelectionDAG &DAG,
10898                                                        unsigned Depth) const {
10899   unsigned Opc = Op.getOpcode();
10900   assert((Opc >= ISD::BUILTIN_OP_END ||
10901           Opc == ISD::INTRINSIC_WO_CHAIN ||
10902           Opc == ISD::INTRINSIC_W_CHAIN ||
10903           Opc == ISD::INTRINSIC_VOID) &&
10904          "Should use MaskedValueIsZero if you don't know whether Op"
10905          " is a target node!");
10906
10907   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10908   switch (Opc) {
10909   default: break;
10910   case X86ISD::ADD:
10911   case X86ISD::SUB:
10912   case X86ISD::ADC:
10913   case X86ISD::SBB:
10914   case X86ISD::SMUL:
10915   case X86ISD::UMUL:
10916   case X86ISD::INC:
10917   case X86ISD::DEC:
10918   case X86ISD::OR:
10919   case X86ISD::XOR:
10920   case X86ISD::AND:
10921     // These nodes' second result is a boolean.
10922     if (Op.getResNo() == 0)
10923       break;
10924     // Fallthrough
10925   case X86ISD::SETCC:
10926     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10927                                        Mask.getBitWidth() - 1);
10928     break;
10929   }
10930 }
10931
10932 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10933                                                          unsigned Depth) const {
10934   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10935   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10936     return Op.getValueType().getScalarType().getSizeInBits();
10937
10938   // Fallback case.
10939   return 1;
10940 }
10941
10942 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10943 /// node is a GlobalAddress + offset.
10944 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10945                                        const GlobalValue* &GA,
10946                                        int64_t &Offset) const {
10947   if (N->getOpcode() == X86ISD::Wrapper) {
10948     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10949       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10950       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10951       return true;
10952     }
10953   }
10954   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10955 }
10956
10957 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10958 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10959 /// if the load addresses are consecutive, non-overlapping, and in the right
10960 /// order.
10961 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10962                                      TargetLowering::DAGCombinerInfo &DCI) {
10963   DebugLoc dl = N->getDebugLoc();
10964   EVT VT = N->getValueType(0);
10965
10966   if (VT.getSizeInBits() != 128)
10967     return SDValue();
10968
10969   // Don't create instructions with illegal types after legalize types has run.
10970   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10971   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10972     return SDValue();
10973
10974   SmallVector<SDValue, 16> Elts;
10975   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10976     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10977
10978   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10979 }
10980
10981 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10982 /// generation and convert it from being a bunch of shuffles and extracts
10983 /// to a simple store and scalar loads to extract the elements.
10984 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10985                                                 const TargetLowering &TLI) {
10986   SDValue InputVector = N->getOperand(0);
10987
10988   // Only operate on vectors of 4 elements, where the alternative shuffling
10989   // gets to be more expensive.
10990   if (InputVector.getValueType() != MVT::v4i32)
10991     return SDValue();
10992
10993   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10994   // single use which is a sign-extend or zero-extend, and all elements are
10995   // used.
10996   SmallVector<SDNode *, 4> Uses;
10997   unsigned ExtractedElements = 0;
10998   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10999        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11000     if (UI.getUse().getResNo() != InputVector.getResNo())
11001       return SDValue();
11002
11003     SDNode *Extract = *UI;
11004     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11005       return SDValue();
11006
11007     if (Extract->getValueType(0) != MVT::i32)
11008       return SDValue();
11009     if (!Extract->hasOneUse())
11010       return SDValue();
11011     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11012         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11013       return SDValue();
11014     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11015       return SDValue();
11016
11017     // Record which element was extracted.
11018     ExtractedElements |=
11019       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11020
11021     Uses.push_back(Extract);
11022   }
11023
11024   // If not all the elements were used, this may not be worthwhile.
11025   if (ExtractedElements != 15)
11026     return SDValue();
11027
11028   // Ok, we've now decided to do the transformation.
11029   DebugLoc dl = InputVector.getDebugLoc();
11030
11031   // Store the value to a temporary stack slot.
11032   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11033   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11034                             MachinePointerInfo(), false, false, 0);
11035
11036   // Replace each use (extract) with a load of the appropriate element.
11037   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11038        UE = Uses.end(); UI != UE; ++UI) {
11039     SDNode *Extract = *UI;
11040
11041     // cOMpute the element's address.
11042     SDValue Idx = Extract->getOperand(1);
11043     unsigned EltSize =
11044         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11045     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11046     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11047
11048     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11049                                      StackPtr, OffsetVal);
11050
11051     // Load the scalar.
11052     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11053                                      ScalarAddr, MachinePointerInfo(),
11054                                      false, false, 0);
11055
11056     // Replace the exact with the load.
11057     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11058   }
11059
11060   // The replacement was made in place; don't return anything.
11061   return SDValue();
11062 }
11063
11064 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11065 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11066                                     const X86Subtarget *Subtarget) {
11067   DebugLoc DL = N->getDebugLoc();
11068   SDValue Cond = N->getOperand(0);
11069   // Get the LHS/RHS of the select.
11070   SDValue LHS = N->getOperand(1);
11071   SDValue RHS = N->getOperand(2);
11072
11073   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11074   // instructions match the semantics of the common C idiom x<y?x:y but not
11075   // x<=y?x:y, because of how they handle negative zero (which can be
11076   // ignored in unsafe-math mode).
11077   if (Subtarget->hasSSE2() &&
11078       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11079       Cond.getOpcode() == ISD::SETCC) {
11080     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11081
11082     unsigned Opcode = 0;
11083     // Check for x CC y ? x : y.
11084     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11085         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11086       switch (CC) {
11087       default: break;
11088       case ISD::SETULT:
11089         // Converting this to a min would handle NaNs incorrectly, and swapping
11090         // the operands would cause it to handle comparisons between positive
11091         // and negative zero incorrectly.
11092         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11093           if (!UnsafeFPMath &&
11094               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11095             break;
11096           std::swap(LHS, RHS);
11097         }
11098         Opcode = X86ISD::FMIN;
11099         break;
11100       case ISD::SETOLE:
11101         // Converting this to a min would handle comparisons between positive
11102         // and negative zero incorrectly.
11103         if (!UnsafeFPMath &&
11104             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11105           break;
11106         Opcode = X86ISD::FMIN;
11107         break;
11108       case ISD::SETULE:
11109         // Converting this to a min would handle both negative zeros and NaNs
11110         // incorrectly, but we can swap the operands to fix both.
11111         std::swap(LHS, RHS);
11112       case ISD::SETOLT:
11113       case ISD::SETLT:
11114       case ISD::SETLE:
11115         Opcode = X86ISD::FMIN;
11116         break;
11117
11118       case ISD::SETOGE:
11119         // Converting this to a max would handle comparisons between positive
11120         // and negative zero incorrectly.
11121         if (!UnsafeFPMath &&
11122             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11123           break;
11124         Opcode = X86ISD::FMAX;
11125         break;
11126       case ISD::SETUGT:
11127         // Converting this to a max would handle NaNs incorrectly, and swapping
11128         // the operands would cause it to handle comparisons between positive
11129         // and negative zero incorrectly.
11130         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11131           if (!UnsafeFPMath &&
11132               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11133             break;
11134           std::swap(LHS, RHS);
11135         }
11136         Opcode = X86ISD::FMAX;
11137         break;
11138       case ISD::SETUGE:
11139         // Converting this to a max would handle both negative zeros and NaNs
11140         // incorrectly, but we can swap the operands to fix both.
11141         std::swap(LHS, RHS);
11142       case ISD::SETOGT:
11143       case ISD::SETGT:
11144       case ISD::SETGE:
11145         Opcode = X86ISD::FMAX;
11146         break;
11147       }
11148     // Check for x CC y ? y : x -- a min/max with reversed arms.
11149     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11150                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11151       switch (CC) {
11152       default: break;
11153       case ISD::SETOGE:
11154         // Converting this to a min would handle comparisons between positive
11155         // and negative zero incorrectly, and swapping the operands would
11156         // cause it to handle NaNs incorrectly.
11157         if (!UnsafeFPMath &&
11158             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11159           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11160             break;
11161           std::swap(LHS, RHS);
11162         }
11163         Opcode = X86ISD::FMIN;
11164         break;
11165       case ISD::SETUGT:
11166         // Converting this to a min would handle NaNs incorrectly.
11167         if (!UnsafeFPMath &&
11168             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11169           break;
11170         Opcode = X86ISD::FMIN;
11171         break;
11172       case ISD::SETUGE:
11173         // Converting this to a min would handle both negative zeros and NaNs
11174         // incorrectly, but we can swap the operands to fix both.
11175         std::swap(LHS, RHS);
11176       case ISD::SETOGT:
11177       case ISD::SETGT:
11178       case ISD::SETGE:
11179         Opcode = X86ISD::FMIN;
11180         break;
11181
11182       case ISD::SETULT:
11183         // Converting this to a max would handle NaNs incorrectly.
11184         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11185           break;
11186         Opcode = X86ISD::FMAX;
11187         break;
11188       case ISD::SETOLE:
11189         // Converting this to a max would handle comparisons between positive
11190         // and negative zero incorrectly, and swapping the operands would
11191         // cause it to handle NaNs incorrectly.
11192         if (!UnsafeFPMath &&
11193             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11194           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11195             break;
11196           std::swap(LHS, RHS);
11197         }
11198         Opcode = X86ISD::FMAX;
11199         break;
11200       case ISD::SETULE:
11201         // Converting this to a max would handle both negative zeros and NaNs
11202         // incorrectly, but we can swap the operands to fix both.
11203         std::swap(LHS, RHS);
11204       case ISD::SETOLT:
11205       case ISD::SETLT:
11206       case ISD::SETLE:
11207         Opcode = X86ISD::FMAX;
11208         break;
11209       }
11210     }
11211
11212     if (Opcode)
11213       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11214   }
11215
11216   // If this is a select between two integer constants, try to do some
11217   // optimizations.
11218   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11219     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11220       // Don't do this for crazy integer types.
11221       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11222         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11223         // so that TrueC (the true value) is larger than FalseC.
11224         bool NeedsCondInvert = false;
11225
11226         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11227             // Efficiently invertible.
11228             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11229              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11230               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11231           NeedsCondInvert = true;
11232           std::swap(TrueC, FalseC);
11233         }
11234
11235         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11236         if (FalseC->getAPIntValue() == 0 &&
11237             TrueC->getAPIntValue().isPowerOf2()) {
11238           if (NeedsCondInvert) // Invert the condition if needed.
11239             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11240                                DAG.getConstant(1, Cond.getValueType()));
11241
11242           // Zero extend the condition if needed.
11243           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11244
11245           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11246           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11247                              DAG.getConstant(ShAmt, MVT::i8));
11248         }
11249
11250         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11251         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11252           if (NeedsCondInvert) // Invert the condition if needed.
11253             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11254                                DAG.getConstant(1, Cond.getValueType()));
11255
11256           // Zero extend the condition if needed.
11257           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11258                              FalseC->getValueType(0), Cond);
11259           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11260                              SDValue(FalseC, 0));
11261         }
11262
11263         // Optimize cases that will turn into an LEA instruction.  This requires
11264         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11265         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11266           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11267           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11268
11269           bool isFastMultiplier = false;
11270           if (Diff < 10) {
11271             switch ((unsigned char)Diff) {
11272               default: break;
11273               case 1:  // result = add base, cond
11274               case 2:  // result = lea base(    , cond*2)
11275               case 3:  // result = lea base(cond, cond*2)
11276               case 4:  // result = lea base(    , cond*4)
11277               case 5:  // result = lea base(cond, cond*4)
11278               case 8:  // result = lea base(    , cond*8)
11279               case 9:  // result = lea base(cond, cond*8)
11280                 isFastMultiplier = true;
11281                 break;
11282             }
11283           }
11284
11285           if (isFastMultiplier) {
11286             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11287             if (NeedsCondInvert) // Invert the condition if needed.
11288               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11289                                  DAG.getConstant(1, Cond.getValueType()));
11290
11291             // Zero extend the condition if needed.
11292             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11293                                Cond);
11294             // Scale the condition by the difference.
11295             if (Diff != 1)
11296               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11297                                  DAG.getConstant(Diff, Cond.getValueType()));
11298
11299             // Add the base if non-zero.
11300             if (FalseC->getAPIntValue() != 0)
11301               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11302                                  SDValue(FalseC, 0));
11303             return Cond;
11304           }
11305         }
11306       }
11307   }
11308
11309   return SDValue();
11310 }
11311
11312 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11313 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11314                                   TargetLowering::DAGCombinerInfo &DCI) {
11315   DebugLoc DL = N->getDebugLoc();
11316
11317   // If the flag operand isn't dead, don't touch this CMOV.
11318   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11319     return SDValue();
11320
11321   // If this is a select between two integer constants, try to do some
11322   // optimizations.  Note that the operands are ordered the opposite of SELECT
11323   // operands.
11324   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11325     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11326       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11327       // larger than FalseC (the false value).
11328       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11329
11330       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11331         CC = X86::GetOppositeBranchCondition(CC);
11332         std::swap(TrueC, FalseC);
11333       }
11334
11335       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11336       // This is efficient for any integer data type (including i8/i16) and
11337       // shift amount.
11338       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11339         SDValue Cond = N->getOperand(3);
11340         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11341                            DAG.getConstant(CC, MVT::i8), Cond);
11342
11343         // Zero extend the condition if needed.
11344         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11345
11346         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11347         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11348                            DAG.getConstant(ShAmt, MVT::i8));
11349         if (N->getNumValues() == 2)  // Dead flag value?
11350           return DCI.CombineTo(N, Cond, SDValue());
11351         return Cond;
11352       }
11353
11354       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11355       // for any integer data type, including i8/i16.
11356       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11357         SDValue Cond = N->getOperand(3);
11358         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11359                            DAG.getConstant(CC, MVT::i8), Cond);
11360
11361         // Zero extend the condition if needed.
11362         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11363                            FalseC->getValueType(0), Cond);
11364         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11365                            SDValue(FalseC, 0));
11366
11367         if (N->getNumValues() == 2)  // Dead flag value?
11368           return DCI.CombineTo(N, Cond, SDValue());
11369         return Cond;
11370       }
11371
11372       // Optimize cases that will turn into an LEA instruction.  This requires
11373       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11374       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11375         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11376         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11377
11378         bool isFastMultiplier = false;
11379         if (Diff < 10) {
11380           switch ((unsigned char)Diff) {
11381           default: break;
11382           case 1:  // result = add base, cond
11383           case 2:  // result = lea base(    , cond*2)
11384           case 3:  // result = lea base(cond, cond*2)
11385           case 4:  // result = lea base(    , cond*4)
11386           case 5:  // result = lea base(cond, cond*4)
11387           case 8:  // result = lea base(    , cond*8)
11388           case 9:  // result = lea base(cond, cond*8)
11389             isFastMultiplier = true;
11390             break;
11391           }
11392         }
11393
11394         if (isFastMultiplier) {
11395           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11396           SDValue Cond = N->getOperand(3);
11397           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11398                              DAG.getConstant(CC, MVT::i8), Cond);
11399           // Zero extend the condition if needed.
11400           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11401                              Cond);
11402           // Scale the condition by the difference.
11403           if (Diff != 1)
11404             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11405                                DAG.getConstant(Diff, Cond.getValueType()));
11406
11407           // Add the base if non-zero.
11408           if (FalseC->getAPIntValue() != 0)
11409             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11410                                SDValue(FalseC, 0));
11411           if (N->getNumValues() == 2)  // Dead flag value?
11412             return DCI.CombineTo(N, Cond, SDValue());
11413           return Cond;
11414         }
11415       }
11416     }
11417   }
11418   return SDValue();
11419 }
11420
11421
11422 /// PerformMulCombine - Optimize a single multiply with constant into two
11423 /// in order to implement it with two cheaper instructions, e.g.
11424 /// LEA + SHL, LEA + LEA.
11425 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11426                                  TargetLowering::DAGCombinerInfo &DCI) {
11427   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11428     return SDValue();
11429
11430   EVT VT = N->getValueType(0);
11431   if (VT != MVT::i64)
11432     return SDValue();
11433
11434   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11435   if (!C)
11436     return SDValue();
11437   uint64_t MulAmt = C->getZExtValue();
11438   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11439     return SDValue();
11440
11441   uint64_t MulAmt1 = 0;
11442   uint64_t MulAmt2 = 0;
11443   if ((MulAmt % 9) == 0) {
11444     MulAmt1 = 9;
11445     MulAmt2 = MulAmt / 9;
11446   } else if ((MulAmt % 5) == 0) {
11447     MulAmt1 = 5;
11448     MulAmt2 = MulAmt / 5;
11449   } else if ((MulAmt % 3) == 0) {
11450     MulAmt1 = 3;
11451     MulAmt2 = MulAmt / 3;
11452   }
11453   if (MulAmt2 &&
11454       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11455     DebugLoc DL = N->getDebugLoc();
11456
11457     if (isPowerOf2_64(MulAmt2) &&
11458         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11459       // If second multiplifer is pow2, issue it first. We want the multiply by
11460       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11461       // is an add.
11462       std::swap(MulAmt1, MulAmt2);
11463
11464     SDValue NewMul;
11465     if (isPowerOf2_64(MulAmt1))
11466       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11467                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11468     else
11469       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11470                            DAG.getConstant(MulAmt1, VT));
11471
11472     if (isPowerOf2_64(MulAmt2))
11473       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11474                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11475     else
11476       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11477                            DAG.getConstant(MulAmt2, VT));
11478
11479     // Do not add new nodes to DAG combiner worklist.
11480     DCI.CombineTo(N, NewMul, false);
11481   }
11482   return SDValue();
11483 }
11484
11485 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11486   SDValue N0 = N->getOperand(0);
11487   SDValue N1 = N->getOperand(1);
11488   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11489   EVT VT = N0.getValueType();
11490
11491   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11492   // since the result of setcc_c is all zero's or all ones.
11493   if (N1C && N0.getOpcode() == ISD::AND &&
11494       N0.getOperand(1).getOpcode() == ISD::Constant) {
11495     SDValue N00 = N0.getOperand(0);
11496     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11497         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11498           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11499          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11500       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11501       APInt ShAmt = N1C->getAPIntValue();
11502       Mask = Mask.shl(ShAmt);
11503       if (Mask != 0)
11504         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11505                            N00, DAG.getConstant(Mask, VT));
11506     }
11507   }
11508
11509   return SDValue();
11510 }
11511
11512 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11513 ///                       when possible.
11514 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11515                                    const X86Subtarget *Subtarget) {
11516   EVT VT = N->getValueType(0);
11517   if (!VT.isVector() && VT.isInteger() &&
11518       N->getOpcode() == ISD::SHL)
11519     return PerformSHLCombine(N, DAG);
11520
11521   // On X86 with SSE2 support, we can transform this to a vector shift if
11522   // all elements are shifted by the same amount.  We can't do this in legalize
11523   // because the a constant vector is typically transformed to a constant pool
11524   // so we have no knowledge of the shift amount.
11525   if (!Subtarget->hasSSE2())
11526     return SDValue();
11527
11528   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11529     return SDValue();
11530
11531   SDValue ShAmtOp = N->getOperand(1);
11532   EVT EltVT = VT.getVectorElementType();
11533   DebugLoc DL = N->getDebugLoc();
11534   SDValue BaseShAmt = SDValue();
11535   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11536     unsigned NumElts = VT.getVectorNumElements();
11537     unsigned i = 0;
11538     for (; i != NumElts; ++i) {
11539       SDValue Arg = ShAmtOp.getOperand(i);
11540       if (Arg.getOpcode() == ISD::UNDEF) continue;
11541       BaseShAmt = Arg;
11542       break;
11543     }
11544     for (; i != NumElts; ++i) {
11545       SDValue Arg = ShAmtOp.getOperand(i);
11546       if (Arg.getOpcode() == ISD::UNDEF) continue;
11547       if (Arg != BaseShAmt) {
11548         return SDValue();
11549       }
11550     }
11551   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11552              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11553     SDValue InVec = ShAmtOp.getOperand(0);
11554     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11555       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11556       unsigned i = 0;
11557       for (; i != NumElts; ++i) {
11558         SDValue Arg = InVec.getOperand(i);
11559         if (Arg.getOpcode() == ISD::UNDEF) continue;
11560         BaseShAmt = Arg;
11561         break;
11562       }
11563     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11564        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11565          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11566          if (C->getZExtValue() == SplatIdx)
11567            BaseShAmt = InVec.getOperand(1);
11568        }
11569     }
11570     if (BaseShAmt.getNode() == 0)
11571       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11572                               DAG.getIntPtrConstant(0));
11573   } else
11574     return SDValue();
11575
11576   // The shift amount is an i32.
11577   if (EltVT.bitsGT(MVT::i32))
11578     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11579   else if (EltVT.bitsLT(MVT::i32))
11580     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11581
11582   // The shift amount is identical so we can do a vector shift.
11583   SDValue  ValOp = N->getOperand(0);
11584   switch (N->getOpcode()) {
11585   default:
11586     llvm_unreachable("Unknown shift opcode!");
11587     break;
11588   case ISD::SHL:
11589     if (VT == MVT::v2i64)
11590       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11591                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11592                          ValOp, BaseShAmt);
11593     if (VT == MVT::v4i32)
11594       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11595                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11596                          ValOp, BaseShAmt);
11597     if (VT == MVT::v8i16)
11598       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11599                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11600                          ValOp, BaseShAmt);
11601     break;
11602   case ISD::SRA:
11603     if (VT == MVT::v4i32)
11604       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11605                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11606                          ValOp, BaseShAmt);
11607     if (VT == MVT::v8i16)
11608       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11609                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11610                          ValOp, BaseShAmt);
11611     break;
11612   case ISD::SRL:
11613     if (VT == MVT::v2i64)
11614       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11615                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11616                          ValOp, BaseShAmt);
11617     if (VT == MVT::v4i32)
11618       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11619                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11620                          ValOp, BaseShAmt);
11621     if (VT ==  MVT::v8i16)
11622       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11623                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11624                          ValOp, BaseShAmt);
11625     break;
11626   }
11627   return SDValue();
11628 }
11629
11630
11631 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11632                                  TargetLowering::DAGCombinerInfo &DCI,
11633                                  const X86Subtarget *Subtarget) {
11634   if (DCI.isBeforeLegalizeOps())
11635     return SDValue();
11636
11637   // Want to form PANDN nodes, in the hopes of then easily combining them with
11638   // OR and AND nodes to form PBLEND/PSIGN.
11639   EVT VT = N->getValueType(0);
11640   if (VT != MVT::v2i64)
11641     return SDValue();
11642
11643   SDValue N0 = N->getOperand(0);
11644   SDValue N1 = N->getOperand(1);
11645   DebugLoc DL = N->getDebugLoc();
11646
11647   // Check LHS for vnot
11648   if (N0.getOpcode() == ISD::XOR &&
11649       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11650     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11651
11652   // Check RHS for vnot
11653   if (N1.getOpcode() == ISD::XOR &&
11654       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11655     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11656
11657   return SDValue();
11658 }
11659
11660 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11661                                 TargetLowering::DAGCombinerInfo &DCI,
11662                                 const X86Subtarget *Subtarget) {
11663   if (DCI.isBeforeLegalizeOps())
11664     return SDValue();
11665
11666   EVT VT = N->getValueType(0);
11667   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11668     return SDValue();
11669
11670   SDValue N0 = N->getOperand(0);
11671   SDValue N1 = N->getOperand(1);
11672
11673   // look for psign/blend
11674   if (Subtarget->hasSSSE3()) {
11675     if (VT == MVT::v2i64) {
11676       // Canonicalize pandn to RHS
11677       if (N0.getOpcode() == X86ISD::PANDN)
11678         std::swap(N0, N1);
11679       // or (and (m, x), (pandn m, y))
11680       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11681         SDValue Mask = N1.getOperand(0);
11682         SDValue X    = N1.getOperand(1);
11683         SDValue Y;
11684         if (N0.getOperand(0) == Mask)
11685           Y = N0.getOperand(1);
11686         if (N0.getOperand(1) == Mask)
11687           Y = N0.getOperand(0);
11688
11689         // Check to see if the mask appeared in both the AND and PANDN and
11690         if (!Y.getNode())
11691           return SDValue();
11692
11693         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11694         if (Mask.getOpcode() != ISD::BITCAST ||
11695             X.getOpcode() != ISD::BITCAST ||
11696             Y.getOpcode() != ISD::BITCAST)
11697           return SDValue();
11698
11699         // Look through mask bitcast.
11700         Mask = Mask.getOperand(0);
11701         EVT MaskVT = Mask.getValueType();
11702
11703         // Validate that the Mask operand is a vector sra node.  The sra node
11704         // will be an intrinsic.
11705         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11706           return SDValue();
11707
11708         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11709         // there is no psrai.b
11710         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11711         case Intrinsic::x86_sse2_psrai_w:
11712         case Intrinsic::x86_sse2_psrai_d:
11713           break;
11714         default: return SDValue();
11715         }
11716
11717         // Check that the SRA is all signbits.
11718         SDValue SraC = Mask.getOperand(2);
11719         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11720         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11721         if ((SraAmt + 1) != EltBits)
11722           return SDValue();
11723
11724         DebugLoc DL = N->getDebugLoc();
11725
11726         // Now we know we at least have a plendvb with the mask val.  See if
11727         // we can form a psignb/w/d.
11728         // psign = x.type == y.type == mask.type && y = sub(0, x);
11729         X = X.getOperand(0);
11730         Y = Y.getOperand(0);
11731         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11732             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11733             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11734           unsigned Opc = 0;
11735           switch (EltBits) {
11736           case 8: Opc = X86ISD::PSIGNB; break;
11737           case 16: Opc = X86ISD::PSIGNW; break;
11738           case 32: Opc = X86ISD::PSIGND; break;
11739           default: break;
11740           }
11741           if (Opc) {
11742             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11743             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11744           }
11745         }
11746         // PBLENDVB only available on SSE 4.1
11747         if (!Subtarget->hasSSE41())
11748           return SDValue();
11749
11750         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11751         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11752         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11753         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11754         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11755       }
11756     }
11757   }
11758
11759   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11760   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11761     std::swap(N0, N1);
11762   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11763     return SDValue();
11764   if (!N0.hasOneUse() || !N1.hasOneUse())
11765     return SDValue();
11766
11767   SDValue ShAmt0 = N0.getOperand(1);
11768   if (ShAmt0.getValueType() != MVT::i8)
11769     return SDValue();
11770   SDValue ShAmt1 = N1.getOperand(1);
11771   if (ShAmt1.getValueType() != MVT::i8)
11772     return SDValue();
11773   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11774     ShAmt0 = ShAmt0.getOperand(0);
11775   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11776     ShAmt1 = ShAmt1.getOperand(0);
11777
11778   DebugLoc DL = N->getDebugLoc();
11779   unsigned Opc = X86ISD::SHLD;
11780   SDValue Op0 = N0.getOperand(0);
11781   SDValue Op1 = N1.getOperand(0);
11782   if (ShAmt0.getOpcode() == ISD::SUB) {
11783     Opc = X86ISD::SHRD;
11784     std::swap(Op0, Op1);
11785     std::swap(ShAmt0, ShAmt1);
11786   }
11787
11788   unsigned Bits = VT.getSizeInBits();
11789   if (ShAmt1.getOpcode() == ISD::SUB) {
11790     SDValue Sum = ShAmt1.getOperand(0);
11791     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11792       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11793       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11794         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11795       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11796         return DAG.getNode(Opc, DL, VT,
11797                            Op0, Op1,
11798                            DAG.getNode(ISD::TRUNCATE, DL,
11799                                        MVT::i8, ShAmt0));
11800     }
11801   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11802     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11803     if (ShAmt0C &&
11804         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11805       return DAG.getNode(Opc, DL, VT,
11806                          N0.getOperand(0), N1.getOperand(0),
11807                          DAG.getNode(ISD::TRUNCATE, DL,
11808                                        MVT::i8, ShAmt0));
11809   }
11810
11811   return SDValue();
11812 }
11813
11814 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11815 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11816                                    const X86Subtarget *Subtarget) {
11817   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11818   // the FP state in cases where an emms may be missing.
11819   // A preferable solution to the general problem is to figure out the right
11820   // places to insert EMMS.  This qualifies as a quick hack.
11821
11822   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11823   StoreSDNode *St = cast<StoreSDNode>(N);
11824   EVT VT = St->getValue().getValueType();
11825   if (VT.getSizeInBits() != 64)
11826     return SDValue();
11827
11828   const Function *F = DAG.getMachineFunction().getFunction();
11829   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11830   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11831     && Subtarget->hasSSE2();
11832   if ((VT.isVector() ||
11833        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11834       isa<LoadSDNode>(St->getValue()) &&
11835       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11836       St->getChain().hasOneUse() && !St->isVolatile()) {
11837     SDNode* LdVal = St->getValue().getNode();
11838     LoadSDNode *Ld = 0;
11839     int TokenFactorIndex = -1;
11840     SmallVector<SDValue, 8> Ops;
11841     SDNode* ChainVal = St->getChain().getNode();
11842     // Must be a store of a load.  We currently handle two cases:  the load
11843     // is a direct child, and it's under an intervening TokenFactor.  It is
11844     // possible to dig deeper under nested TokenFactors.
11845     if (ChainVal == LdVal)
11846       Ld = cast<LoadSDNode>(St->getChain());
11847     else if (St->getValue().hasOneUse() &&
11848              ChainVal->getOpcode() == ISD::TokenFactor) {
11849       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11850         if (ChainVal->getOperand(i).getNode() == LdVal) {
11851           TokenFactorIndex = i;
11852           Ld = cast<LoadSDNode>(St->getValue());
11853         } else
11854           Ops.push_back(ChainVal->getOperand(i));
11855       }
11856     }
11857
11858     if (!Ld || !ISD::isNormalLoad(Ld))
11859       return SDValue();
11860
11861     // If this is not the MMX case, i.e. we are just turning i64 load/store
11862     // into f64 load/store, avoid the transformation if there are multiple
11863     // uses of the loaded value.
11864     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11865       return SDValue();
11866
11867     DebugLoc LdDL = Ld->getDebugLoc();
11868     DebugLoc StDL = N->getDebugLoc();
11869     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11870     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11871     // pair instead.
11872     if (Subtarget->is64Bit() || F64IsLegal) {
11873       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11874       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11875                                   Ld->getPointerInfo(), Ld->isVolatile(),
11876                                   Ld->isNonTemporal(), Ld->getAlignment());
11877       SDValue NewChain = NewLd.getValue(1);
11878       if (TokenFactorIndex != -1) {
11879         Ops.push_back(NewChain);
11880         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11881                                Ops.size());
11882       }
11883       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11884                           St->getPointerInfo(),
11885                           St->isVolatile(), St->isNonTemporal(),
11886                           St->getAlignment());
11887     }
11888
11889     // Otherwise, lower to two pairs of 32-bit loads / stores.
11890     SDValue LoAddr = Ld->getBasePtr();
11891     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11892                                  DAG.getConstant(4, MVT::i32));
11893
11894     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11895                                Ld->getPointerInfo(),
11896                                Ld->isVolatile(), Ld->isNonTemporal(),
11897                                Ld->getAlignment());
11898     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11899                                Ld->getPointerInfo().getWithOffset(4),
11900                                Ld->isVolatile(), Ld->isNonTemporal(),
11901                                MinAlign(Ld->getAlignment(), 4));
11902
11903     SDValue NewChain = LoLd.getValue(1);
11904     if (TokenFactorIndex != -1) {
11905       Ops.push_back(LoLd);
11906       Ops.push_back(HiLd);
11907       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11908                              Ops.size());
11909     }
11910
11911     LoAddr = St->getBasePtr();
11912     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11913                          DAG.getConstant(4, MVT::i32));
11914
11915     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11916                                 St->getPointerInfo(),
11917                                 St->isVolatile(), St->isNonTemporal(),
11918                                 St->getAlignment());
11919     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11920                                 St->getPointerInfo().getWithOffset(4),
11921                                 St->isVolatile(),
11922                                 St->isNonTemporal(),
11923                                 MinAlign(St->getAlignment(), 4));
11924     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11925   }
11926   return SDValue();
11927 }
11928
11929 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11930 /// X86ISD::FXOR nodes.
11931 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11932   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11933   // F[X]OR(0.0, x) -> x
11934   // F[X]OR(x, 0.0) -> x
11935   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11936     if (C->getValueAPF().isPosZero())
11937       return N->getOperand(1);
11938   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11939     if (C->getValueAPF().isPosZero())
11940       return N->getOperand(0);
11941   return SDValue();
11942 }
11943
11944 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11945 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11946   // FAND(0.0, x) -> 0.0
11947   // FAND(x, 0.0) -> 0.0
11948   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11949     if (C->getValueAPF().isPosZero())
11950       return N->getOperand(0);
11951   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11952     if (C->getValueAPF().isPosZero())
11953       return N->getOperand(1);
11954   return SDValue();
11955 }
11956
11957 static SDValue PerformBTCombine(SDNode *N,
11958                                 SelectionDAG &DAG,
11959                                 TargetLowering::DAGCombinerInfo &DCI) {
11960   // BT ignores high bits in the bit index operand.
11961   SDValue Op1 = N->getOperand(1);
11962   if (Op1.hasOneUse()) {
11963     unsigned BitWidth = Op1.getValueSizeInBits();
11964     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11965     APInt KnownZero, KnownOne;
11966     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11967                                           !DCI.isBeforeLegalizeOps());
11968     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11969     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11970         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11971       DCI.CommitTargetLoweringOpt(TLO);
11972   }
11973   return SDValue();
11974 }
11975
11976 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11977   SDValue Op = N->getOperand(0);
11978   if (Op.getOpcode() == ISD::BITCAST)
11979     Op = Op.getOperand(0);
11980   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11981   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11982       VT.getVectorElementType().getSizeInBits() ==
11983       OpVT.getVectorElementType().getSizeInBits()) {
11984     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11985   }
11986   return SDValue();
11987 }
11988
11989 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11990   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11991   //           (and (i32 x86isd::setcc_carry), 1)
11992   // This eliminates the zext. This transformation is necessary because
11993   // ISD::SETCC is always legalized to i8.
11994   DebugLoc dl = N->getDebugLoc();
11995   SDValue N0 = N->getOperand(0);
11996   EVT VT = N->getValueType(0);
11997   if (N0.getOpcode() == ISD::AND &&
11998       N0.hasOneUse() &&
11999       N0.getOperand(0).hasOneUse()) {
12000     SDValue N00 = N0.getOperand(0);
12001     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12002       return SDValue();
12003     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12004     if (!C || C->getZExtValue() != 1)
12005       return SDValue();
12006     return DAG.getNode(ISD::AND, dl, VT,
12007                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12008                                    N00.getOperand(0), N00.getOperand(1)),
12009                        DAG.getConstant(1, VT));
12010   }
12011
12012   return SDValue();
12013 }
12014
12015 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12016 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12017   unsigned X86CC = N->getConstantOperandVal(0);
12018   SDValue EFLAG = N->getOperand(1);
12019   DebugLoc DL = N->getDebugLoc();
12020
12021   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12022   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12023   // cases.
12024   if (X86CC == X86::COND_B)
12025     return DAG.getNode(ISD::AND, DL, MVT::i8,
12026                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12027                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12028                        DAG.getConstant(1, MVT::i8));
12029
12030   return SDValue();
12031 }
12032
12033 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12034 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12035                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12036   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12037   // the result is either zero or one (depending on the input carry bit).
12038   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12039   if (X86::isZeroNode(N->getOperand(0)) &&
12040       X86::isZeroNode(N->getOperand(1)) &&
12041       // We don't have a good way to replace an EFLAGS use, so only do this when
12042       // dead right now.
12043       SDValue(N, 1).use_empty()) {
12044     DebugLoc DL = N->getDebugLoc();
12045     EVT VT = N->getValueType(0);
12046     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12047     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12048                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12049                                            DAG.getConstant(X86::COND_B,MVT::i8),
12050                                            N->getOperand(2)),
12051                                DAG.getConstant(1, VT));
12052     return DCI.CombineTo(N, Res1, CarryOut);
12053   }
12054
12055   return SDValue();
12056 }
12057
12058 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12059 //      (add Y, (setne X, 0)) -> sbb -1, Y
12060 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12061 //      (sub (setne X, 0), Y) -> adc -1, Y
12062 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12063   DebugLoc DL = N->getDebugLoc();
12064
12065   // Look through ZExts.
12066   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12067   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12068     return SDValue();
12069
12070   SDValue SetCC = Ext.getOperand(0);
12071   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12072     return SDValue();
12073
12074   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12075   if (CC != X86::COND_E && CC != X86::COND_NE)
12076     return SDValue();
12077
12078   SDValue Cmp = SetCC.getOperand(1);
12079   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12080       !X86::isZeroNode(Cmp.getOperand(1)) ||
12081       !Cmp.getOperand(0).getValueType().isInteger())
12082     return SDValue();
12083
12084   SDValue CmpOp0 = Cmp.getOperand(0);
12085   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12086                                DAG.getConstant(1, CmpOp0.getValueType()));
12087
12088   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12089   if (CC == X86::COND_NE)
12090     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12091                        DL, OtherVal.getValueType(), OtherVal,
12092                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12093   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12094                      DL, OtherVal.getValueType(), OtherVal,
12095                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12096 }
12097
12098 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12099                                              DAGCombinerInfo &DCI) const {
12100   SelectionDAG &DAG = DCI.DAG;
12101   switch (N->getOpcode()) {
12102   default: break;
12103   case ISD::EXTRACT_VECTOR_ELT:
12104     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12105   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12106   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12107   case ISD::ADD:
12108   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12109   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12110   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12111   case ISD::SHL:
12112   case ISD::SRA:
12113   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12114   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12115   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12116   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12117   case X86ISD::FXOR:
12118   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12119   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12120   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12121   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12122   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12123   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12124   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12125   case X86ISD::SHUFPD:
12126   case X86ISD::PALIGN:
12127   case X86ISD::PUNPCKHBW:
12128   case X86ISD::PUNPCKHWD:
12129   case X86ISD::PUNPCKHDQ:
12130   case X86ISD::PUNPCKHQDQ:
12131   case X86ISD::UNPCKHPS:
12132   case X86ISD::UNPCKHPD:
12133   case X86ISD::PUNPCKLBW:
12134   case X86ISD::PUNPCKLWD:
12135   case X86ISD::PUNPCKLDQ:
12136   case X86ISD::PUNPCKLQDQ:
12137   case X86ISD::UNPCKLPS:
12138   case X86ISD::UNPCKLPD:
12139   case X86ISD::VUNPCKLPS:
12140   case X86ISD::VUNPCKLPD:
12141   case X86ISD::VUNPCKLPSY:
12142   case X86ISD::VUNPCKLPDY:
12143   case X86ISD::MOVHLPS:
12144   case X86ISD::MOVLHPS:
12145   case X86ISD::PSHUFD:
12146   case X86ISD::PSHUFHW:
12147   case X86ISD::PSHUFLW:
12148   case X86ISD::MOVSS:
12149   case X86ISD::MOVSD:
12150   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12151   }
12152
12153   return SDValue();
12154 }
12155
12156 /// isTypeDesirableForOp - Return true if the target has native support for
12157 /// the specified value type and it is 'desirable' to use the type for the
12158 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12159 /// instruction encodings are longer and some i16 instructions are slow.
12160 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12161   if (!isTypeLegal(VT))
12162     return false;
12163   if (VT != MVT::i16)
12164     return true;
12165
12166   switch (Opc) {
12167   default:
12168     return true;
12169   case ISD::LOAD:
12170   case ISD::SIGN_EXTEND:
12171   case ISD::ZERO_EXTEND:
12172   case ISD::ANY_EXTEND:
12173   case ISD::SHL:
12174   case ISD::SRL:
12175   case ISD::SUB:
12176   case ISD::ADD:
12177   case ISD::MUL:
12178   case ISD::AND:
12179   case ISD::OR:
12180   case ISD::XOR:
12181     return false;
12182   }
12183 }
12184
12185 /// IsDesirableToPromoteOp - This method query the target whether it is
12186 /// beneficial for dag combiner to promote the specified node. If true, it
12187 /// should return the desired promotion type by reference.
12188 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12189   EVT VT = Op.getValueType();
12190   if (VT != MVT::i16)
12191     return false;
12192
12193   bool Promote = false;
12194   bool Commute = false;
12195   switch (Op.getOpcode()) {
12196   default: break;
12197   case ISD::LOAD: {
12198     LoadSDNode *LD = cast<LoadSDNode>(Op);
12199     // If the non-extending load has a single use and it's not live out, then it
12200     // might be folded.
12201     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12202                                                      Op.hasOneUse()*/) {
12203       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12204              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12205         // The only case where we'd want to promote LOAD (rather then it being
12206         // promoted as an operand is when it's only use is liveout.
12207         if (UI->getOpcode() != ISD::CopyToReg)
12208           return false;
12209       }
12210     }
12211     Promote = true;
12212     break;
12213   }
12214   case ISD::SIGN_EXTEND:
12215   case ISD::ZERO_EXTEND:
12216   case ISD::ANY_EXTEND:
12217     Promote = true;
12218     break;
12219   case ISD::SHL:
12220   case ISD::SRL: {
12221     SDValue N0 = Op.getOperand(0);
12222     // Look out for (store (shl (load), x)).
12223     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12224       return false;
12225     Promote = true;
12226     break;
12227   }
12228   case ISD::ADD:
12229   case ISD::MUL:
12230   case ISD::AND:
12231   case ISD::OR:
12232   case ISD::XOR:
12233     Commute = true;
12234     // fallthrough
12235   case ISD::SUB: {
12236     SDValue N0 = Op.getOperand(0);
12237     SDValue N1 = Op.getOperand(1);
12238     if (!Commute && MayFoldLoad(N1))
12239       return false;
12240     // Avoid disabling potential load folding opportunities.
12241     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12242       return false;
12243     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12244       return false;
12245     Promote = true;
12246   }
12247   }
12248
12249   PVT = MVT::i32;
12250   return Promote;
12251 }
12252
12253 //===----------------------------------------------------------------------===//
12254 //                           X86 Inline Assembly Support
12255 //===----------------------------------------------------------------------===//
12256
12257 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12258   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12259
12260   std::string AsmStr = IA->getAsmString();
12261
12262   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12263   SmallVector<StringRef, 4> AsmPieces;
12264   SplitString(AsmStr, AsmPieces, ";\n");
12265
12266   switch (AsmPieces.size()) {
12267   default: return false;
12268   case 1:
12269     AsmStr = AsmPieces[0];
12270     AsmPieces.clear();
12271     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12272
12273     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12274     // we will turn this bswap into something that will be lowered to logical ops
12275     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12276     // so don't worry about this.
12277     // bswap $0
12278     if (AsmPieces.size() == 2 &&
12279         (AsmPieces[0] == "bswap" ||
12280          AsmPieces[0] == "bswapq" ||
12281          AsmPieces[0] == "bswapl") &&
12282         (AsmPieces[1] == "$0" ||
12283          AsmPieces[1] == "${0:q}")) {
12284       // No need to check constraints, nothing other than the equivalent of
12285       // "=r,0" would be valid here.
12286       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12287       if (!Ty || Ty->getBitWidth() % 16 != 0)
12288         return false;
12289       return IntrinsicLowering::LowerToByteSwap(CI);
12290     }
12291     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12292     if (CI->getType()->isIntegerTy(16) &&
12293         AsmPieces.size() == 3 &&
12294         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12295         AsmPieces[1] == "$$8," &&
12296         AsmPieces[2] == "${0:w}" &&
12297         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12298       AsmPieces.clear();
12299       const std::string &ConstraintsStr = IA->getConstraintString();
12300       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12301       std::sort(AsmPieces.begin(), AsmPieces.end());
12302       if (AsmPieces.size() == 4 &&
12303           AsmPieces[0] == "~{cc}" &&
12304           AsmPieces[1] == "~{dirflag}" &&
12305           AsmPieces[2] == "~{flags}" &&
12306           AsmPieces[3] == "~{fpsr}") {
12307         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12308         if (!Ty || Ty->getBitWidth() % 16 != 0)
12309           return false;
12310         return IntrinsicLowering::LowerToByteSwap(CI);
12311       }
12312     }
12313     break;
12314   case 3:
12315     if (CI->getType()->isIntegerTy(32) &&
12316         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12317       SmallVector<StringRef, 4> Words;
12318       SplitString(AsmPieces[0], Words, " \t,");
12319       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12320           Words[2] == "${0:w}") {
12321         Words.clear();
12322         SplitString(AsmPieces[1], Words, " \t,");
12323         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12324             Words[2] == "$0") {
12325           Words.clear();
12326           SplitString(AsmPieces[2], Words, " \t,");
12327           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12328               Words[2] == "${0:w}") {
12329             AsmPieces.clear();
12330             const std::string &ConstraintsStr = IA->getConstraintString();
12331             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12332             std::sort(AsmPieces.begin(), AsmPieces.end());
12333             if (AsmPieces.size() == 4 &&
12334                 AsmPieces[0] == "~{cc}" &&
12335                 AsmPieces[1] == "~{dirflag}" &&
12336                 AsmPieces[2] == "~{flags}" &&
12337                 AsmPieces[3] == "~{fpsr}") {
12338               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12339               if (!Ty || Ty->getBitWidth() % 16 != 0)
12340                 return false;
12341               return IntrinsicLowering::LowerToByteSwap(CI);
12342             }
12343           }
12344         }
12345       }
12346     }
12347
12348     if (CI->getType()->isIntegerTy(64)) {
12349       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12350       if (Constraints.size() >= 2 &&
12351           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12352           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12353         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12354         SmallVector<StringRef, 4> Words;
12355         SplitString(AsmPieces[0], Words, " \t");
12356         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12357           Words.clear();
12358           SplitString(AsmPieces[1], Words, " \t");
12359           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12360             Words.clear();
12361             SplitString(AsmPieces[2], Words, " \t,");
12362             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12363                 Words[2] == "%edx") {
12364               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12365               if (!Ty || Ty->getBitWidth() % 16 != 0)
12366                 return false;
12367               return IntrinsicLowering::LowerToByteSwap(CI);
12368             }
12369           }
12370         }
12371       }
12372     }
12373     break;
12374   }
12375   return false;
12376 }
12377
12378
12379
12380 /// getConstraintType - Given a constraint letter, return the type of
12381 /// constraint it is for this target.
12382 X86TargetLowering::ConstraintType
12383 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12384   if (Constraint.size() == 1) {
12385     switch (Constraint[0]) {
12386     case 'R':
12387     case 'q':
12388     case 'Q':
12389     case 'f':
12390     case 't':
12391     case 'u':
12392     case 'y':
12393     case 'x':
12394     case 'Y':
12395       return C_RegisterClass;
12396     case 'a':
12397     case 'b':
12398     case 'c':
12399     case 'd':
12400     case 'S':
12401     case 'D':
12402     case 'A':
12403       return C_Register;
12404     case 'I':
12405     case 'J':
12406     case 'K':
12407     case 'L':
12408     case 'M':
12409     case 'N':
12410     case 'G':
12411     case 'C':
12412     case 'e':
12413     case 'Z':
12414       return C_Other;
12415     default:
12416       break;
12417     }
12418   }
12419   return TargetLowering::getConstraintType(Constraint);
12420 }
12421
12422 /// Examine constraint type and operand type and determine a weight value.
12423 /// This object must already have been set up with the operand type
12424 /// and the current alternative constraint selected.
12425 TargetLowering::ConstraintWeight
12426   X86TargetLowering::getSingleConstraintMatchWeight(
12427     AsmOperandInfo &info, const char *constraint) const {
12428   ConstraintWeight weight = CW_Invalid;
12429   Value *CallOperandVal = info.CallOperandVal;
12430     // If we don't have a value, we can't do a match,
12431     // but allow it at the lowest weight.
12432   if (CallOperandVal == NULL)
12433     return CW_Default;
12434   const Type *type = CallOperandVal->getType();
12435   // Look at the constraint type.
12436   switch (*constraint) {
12437   default:
12438     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12439   case 'R':
12440   case 'q':
12441   case 'Q':
12442   case 'a':
12443   case 'b':
12444   case 'c':
12445   case 'd':
12446   case 'S':
12447   case 'D':
12448   case 'A':
12449     if (CallOperandVal->getType()->isIntegerTy())
12450       weight = CW_SpecificReg;
12451     break;
12452   case 'f':
12453   case 't':
12454   case 'u':
12455       if (type->isFloatingPointTy())
12456         weight = CW_SpecificReg;
12457       break;
12458   case 'y':
12459       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12460         weight = CW_SpecificReg;
12461       break;
12462   case 'x':
12463   case 'Y':
12464     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12465       weight = CW_Register;
12466     break;
12467   case 'I':
12468     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12469       if (C->getZExtValue() <= 31)
12470         weight = CW_Constant;
12471     }
12472     break;
12473   case 'J':
12474     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12475       if (C->getZExtValue() <= 63)
12476         weight = CW_Constant;
12477     }
12478     break;
12479   case 'K':
12480     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12481       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12482         weight = CW_Constant;
12483     }
12484     break;
12485   case 'L':
12486     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12487       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12488         weight = CW_Constant;
12489     }
12490     break;
12491   case 'M':
12492     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12493       if (C->getZExtValue() <= 3)
12494         weight = CW_Constant;
12495     }
12496     break;
12497   case 'N':
12498     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12499       if (C->getZExtValue() <= 0xff)
12500         weight = CW_Constant;
12501     }
12502     break;
12503   case 'G':
12504   case 'C':
12505     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12506       weight = CW_Constant;
12507     }
12508     break;
12509   case 'e':
12510     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12511       if ((C->getSExtValue() >= -0x80000000LL) &&
12512           (C->getSExtValue() <= 0x7fffffffLL))
12513         weight = CW_Constant;
12514     }
12515     break;
12516   case 'Z':
12517     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12518       if (C->getZExtValue() <= 0xffffffff)
12519         weight = CW_Constant;
12520     }
12521     break;
12522   }
12523   return weight;
12524 }
12525
12526 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12527 /// with another that has more specific requirements based on the type of the
12528 /// corresponding operand.
12529 const char *X86TargetLowering::
12530 LowerXConstraint(EVT ConstraintVT) const {
12531   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12532   // 'f' like normal targets.
12533   if (ConstraintVT.isFloatingPoint()) {
12534     if (Subtarget->hasXMMInt())
12535       return "Y";
12536     if (Subtarget->hasXMM())
12537       return "x";
12538   }
12539
12540   return TargetLowering::LowerXConstraint(ConstraintVT);
12541 }
12542
12543 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12544 /// vector.  If it is invalid, don't add anything to Ops.
12545 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12546                                                      char Constraint,
12547                                                      std::vector<SDValue>&Ops,
12548                                                      SelectionDAG &DAG) const {
12549   SDValue Result(0, 0);
12550
12551   switch (Constraint) {
12552   default: break;
12553   case 'I':
12554     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12555       if (C->getZExtValue() <= 31) {
12556         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12557         break;
12558       }
12559     }
12560     return;
12561   case 'J':
12562     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12563       if (C->getZExtValue() <= 63) {
12564         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12565         break;
12566       }
12567     }
12568     return;
12569   case 'K':
12570     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12571       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12572         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12573         break;
12574       }
12575     }
12576     return;
12577   case 'N':
12578     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12579       if (C->getZExtValue() <= 255) {
12580         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12581         break;
12582       }
12583     }
12584     return;
12585   case 'e': {
12586     // 32-bit signed value
12587     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12588       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12589                                            C->getSExtValue())) {
12590         // Widen to 64 bits here to get it sign extended.
12591         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12592         break;
12593       }
12594     // FIXME gcc accepts some relocatable values here too, but only in certain
12595     // memory models; it's complicated.
12596     }
12597     return;
12598   }
12599   case 'Z': {
12600     // 32-bit unsigned value
12601     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12602       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12603                                            C->getZExtValue())) {
12604         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12605         break;
12606       }
12607     }
12608     // FIXME gcc accepts some relocatable values here too, but only in certain
12609     // memory models; it's complicated.
12610     return;
12611   }
12612   case 'i': {
12613     // Literal immediates are always ok.
12614     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12615       // Widen to 64 bits here to get it sign extended.
12616       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12617       break;
12618     }
12619
12620     // In any sort of PIC mode addresses need to be computed at runtime by
12621     // adding in a register or some sort of table lookup.  These can't
12622     // be used as immediates.
12623     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12624       return;
12625
12626     // If we are in non-pic codegen mode, we allow the address of a global (with
12627     // an optional displacement) to be used with 'i'.
12628     GlobalAddressSDNode *GA = 0;
12629     int64_t Offset = 0;
12630
12631     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12632     while (1) {
12633       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12634         Offset += GA->getOffset();
12635         break;
12636       } else if (Op.getOpcode() == ISD::ADD) {
12637         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12638           Offset += C->getZExtValue();
12639           Op = Op.getOperand(0);
12640           continue;
12641         }
12642       } else if (Op.getOpcode() == ISD::SUB) {
12643         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12644           Offset += -C->getZExtValue();
12645           Op = Op.getOperand(0);
12646           continue;
12647         }
12648       }
12649
12650       // Otherwise, this isn't something we can handle, reject it.
12651       return;
12652     }
12653
12654     const GlobalValue *GV = GA->getGlobal();
12655     // If we require an extra load to get this address, as in PIC mode, we
12656     // can't accept it.
12657     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12658                                                         getTargetMachine())))
12659       return;
12660
12661     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12662                                         GA->getValueType(0), Offset);
12663     break;
12664   }
12665   }
12666
12667   if (Result.getNode()) {
12668     Ops.push_back(Result);
12669     return;
12670   }
12671   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12672 }
12673
12674 std::vector<unsigned> X86TargetLowering::
12675 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12676                                   EVT VT) const {
12677   if (Constraint.size() == 1) {
12678     // FIXME: not handling fp-stack yet!
12679     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12680     default: break;  // Unknown constraint letter
12681     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12682       if (Subtarget->is64Bit()) {
12683         if (VT == MVT::i32)
12684           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12685                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12686                                        X86::R10D,X86::R11D,X86::R12D,
12687                                        X86::R13D,X86::R14D,X86::R15D,
12688                                        X86::EBP, X86::ESP, 0);
12689         else if (VT == MVT::i16)
12690           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12691                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12692                                        X86::R10W,X86::R11W,X86::R12W,
12693                                        X86::R13W,X86::R14W,X86::R15W,
12694                                        X86::BP,  X86::SP, 0);
12695         else if (VT == MVT::i8)
12696           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12697                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12698                                        X86::R10B,X86::R11B,X86::R12B,
12699                                        X86::R13B,X86::R14B,X86::R15B,
12700                                        X86::BPL, X86::SPL, 0);
12701
12702         else if (VT == MVT::i64)
12703           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12704                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12705                                        X86::R10, X86::R11, X86::R12,
12706                                        X86::R13, X86::R14, X86::R15,
12707                                        X86::RBP, X86::RSP, 0);
12708
12709         break;
12710       }
12711       // 32-bit fallthrough
12712     case 'Q':   // Q_REGS
12713       if (VT == MVT::i32)
12714         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12715       else if (VT == MVT::i16)
12716         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12717       else if (VT == MVT::i8)
12718         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12719       else if (VT == MVT::i64)
12720         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12721       break;
12722     }
12723   }
12724
12725   return std::vector<unsigned>();
12726 }
12727
12728 std::pair<unsigned, const TargetRegisterClass*>
12729 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12730                                                 EVT VT) const {
12731   // First, see if this is a constraint that directly corresponds to an LLVM
12732   // register class.
12733   if (Constraint.size() == 1) {
12734     // GCC Constraint Letters
12735     switch (Constraint[0]) {
12736     default: break;
12737     case 'r':   // GENERAL_REGS
12738     case 'l':   // INDEX_REGS
12739       if (VT == MVT::i8)
12740         return std::make_pair(0U, X86::GR8RegisterClass);
12741       if (VT == MVT::i16)
12742         return std::make_pair(0U, X86::GR16RegisterClass);
12743       if (VT == MVT::i32 || !Subtarget->is64Bit())
12744         return std::make_pair(0U, X86::GR32RegisterClass);
12745       return std::make_pair(0U, X86::GR64RegisterClass);
12746     case 'R':   // LEGACY_REGS
12747       if (VT == MVT::i8)
12748         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12749       if (VT == MVT::i16)
12750         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12751       if (VT == MVT::i32 || !Subtarget->is64Bit())
12752         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12753       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12754     case 'f':  // FP Stack registers.
12755       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12756       // value to the correct fpstack register class.
12757       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12758         return std::make_pair(0U, X86::RFP32RegisterClass);
12759       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12760         return std::make_pair(0U, X86::RFP64RegisterClass);
12761       return std::make_pair(0U, X86::RFP80RegisterClass);
12762     case 'y':   // MMX_REGS if MMX allowed.
12763       if (!Subtarget->hasMMX()) break;
12764       return std::make_pair(0U, X86::VR64RegisterClass);
12765     case 'Y':   // SSE_REGS if SSE2 allowed
12766       if (!Subtarget->hasXMMInt()) break;
12767       // FALL THROUGH.
12768     case 'x':   // SSE_REGS if SSE1 allowed
12769       if (!Subtarget->hasXMM()) break;
12770
12771       switch (VT.getSimpleVT().SimpleTy) {
12772       default: break;
12773       // Scalar SSE types.
12774       case MVT::f32:
12775       case MVT::i32:
12776         return std::make_pair(0U, X86::FR32RegisterClass);
12777       case MVT::f64:
12778       case MVT::i64:
12779         return std::make_pair(0U, X86::FR64RegisterClass);
12780       // Vector types.
12781       case MVT::v16i8:
12782       case MVT::v8i16:
12783       case MVT::v4i32:
12784       case MVT::v2i64:
12785       case MVT::v4f32:
12786       case MVT::v2f64:
12787         return std::make_pair(0U, X86::VR128RegisterClass);
12788       }
12789       break;
12790     }
12791   }
12792
12793   // Use the default implementation in TargetLowering to convert the register
12794   // constraint into a member of a register class.
12795   std::pair<unsigned, const TargetRegisterClass*> Res;
12796   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12797
12798   // Not found as a standard register?
12799   if (Res.second == 0) {
12800     // Map st(0) -> st(7) -> ST0
12801     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12802         tolower(Constraint[1]) == 's' &&
12803         tolower(Constraint[2]) == 't' &&
12804         Constraint[3] == '(' &&
12805         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12806         Constraint[5] == ')' &&
12807         Constraint[6] == '}') {
12808
12809       Res.first = X86::ST0+Constraint[4]-'0';
12810       Res.second = X86::RFP80RegisterClass;
12811       return Res;
12812     }
12813
12814     // GCC allows "st(0)" to be called just plain "st".
12815     if (StringRef("{st}").equals_lower(Constraint)) {
12816       Res.first = X86::ST0;
12817       Res.second = X86::RFP80RegisterClass;
12818       return Res;
12819     }
12820
12821     // flags -> EFLAGS
12822     if (StringRef("{flags}").equals_lower(Constraint)) {
12823       Res.first = X86::EFLAGS;
12824       Res.second = X86::CCRRegisterClass;
12825       return Res;
12826     }
12827
12828     // 'A' means EAX + EDX.
12829     if (Constraint == "A") {
12830       Res.first = X86::EAX;
12831       Res.second = X86::GR32_ADRegisterClass;
12832       return Res;
12833     }
12834     return Res;
12835   }
12836
12837   // Otherwise, check to see if this is a register class of the wrong value
12838   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12839   // turn into {ax},{dx}.
12840   if (Res.second->hasType(VT))
12841     return Res;   // Correct type already, nothing to do.
12842
12843   // All of the single-register GCC register classes map their values onto
12844   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12845   // really want an 8-bit or 32-bit register, map to the appropriate register
12846   // class and return the appropriate register.
12847   if (Res.second == X86::GR16RegisterClass) {
12848     if (VT == MVT::i8) {
12849       unsigned DestReg = 0;
12850       switch (Res.first) {
12851       default: break;
12852       case X86::AX: DestReg = X86::AL; break;
12853       case X86::DX: DestReg = X86::DL; break;
12854       case X86::CX: DestReg = X86::CL; break;
12855       case X86::BX: DestReg = X86::BL; break;
12856       }
12857       if (DestReg) {
12858         Res.first = DestReg;
12859         Res.second = X86::GR8RegisterClass;
12860       }
12861     } else if (VT == MVT::i32) {
12862       unsigned DestReg = 0;
12863       switch (Res.first) {
12864       default: break;
12865       case X86::AX: DestReg = X86::EAX; break;
12866       case X86::DX: DestReg = X86::EDX; break;
12867       case X86::CX: DestReg = X86::ECX; break;
12868       case X86::BX: DestReg = X86::EBX; break;
12869       case X86::SI: DestReg = X86::ESI; break;
12870       case X86::DI: DestReg = X86::EDI; break;
12871       case X86::BP: DestReg = X86::EBP; break;
12872       case X86::SP: DestReg = X86::ESP; break;
12873       }
12874       if (DestReg) {
12875         Res.first = DestReg;
12876         Res.second = X86::GR32RegisterClass;
12877       }
12878     } else if (VT == MVT::i64) {
12879       unsigned DestReg = 0;
12880       switch (Res.first) {
12881       default: break;
12882       case X86::AX: DestReg = X86::RAX; break;
12883       case X86::DX: DestReg = X86::RDX; break;
12884       case X86::CX: DestReg = X86::RCX; break;
12885       case X86::BX: DestReg = X86::RBX; break;
12886       case X86::SI: DestReg = X86::RSI; break;
12887       case X86::DI: DestReg = X86::RDI; break;
12888       case X86::BP: DestReg = X86::RBP; break;
12889       case X86::SP: DestReg = X86::RSP; break;
12890       }
12891       if (DestReg) {
12892         Res.first = DestReg;
12893         Res.second = X86::GR64RegisterClass;
12894       }
12895     }
12896   } else if (Res.second == X86::FR32RegisterClass ||
12897              Res.second == X86::FR64RegisterClass ||
12898              Res.second == X86::VR128RegisterClass) {
12899     // Handle references to XMM physical registers that got mapped into the
12900     // wrong class.  This can happen with constraints like {xmm0} where the
12901     // target independent register mapper will just pick the first match it can
12902     // find, ignoring the required type.
12903     if (VT == MVT::f32)
12904       Res.second = X86::FR32RegisterClass;
12905     else if (VT == MVT::f64)
12906       Res.second = X86::FR64RegisterClass;
12907     else if (X86::VR128RegisterClass->hasType(VT))
12908       Res.second = X86::VR128RegisterClass;
12909   }
12910
12911   return Res;
12912 }