Omit unnecessary stack copy when x87 input is a load.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference.  Idx is an index in the 128 bits we
80 /// want.  It need not be aligned to a 128-bit bounday.  That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
83                                    SDValue Idx,
84                                    SelectionDAG &DAG,
85                                    DebugLoc dl) {
86   EVT VT = Vec.getValueType();
87   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88
89   EVT ElVT = VT.getVectorElementType();
90
91   int Factor = VT.getSizeInBits() / 128;
92
93   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94                                   ElVT,
95                                   VT.getVectorNumElements() / Factor);
96
97   // Extract from UNDEF is UNDEF.
98   if (Vec.getOpcode() == ISD::UNDEF)
99     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100
101   if (isa<ConstantSDNode>(Idx)) {
102     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103
104     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
105     // we can match to VEXTRACTF128.
106     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107
108     // This is the index of the first element of the 128-bit chunk
109     // we want.
110     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
111                                  * ElemsPerChunk);
112
113     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114
115     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116                                  VecIdx);
117
118     return Result;
119   }
120
121   return SDValue();
122 }
123
124 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference.  Idx is an index in the 128 bits
127 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
130                                   SDValue Vec,
131                                   SDValue Idx,
132                                   SelectionDAG &DAG,
133                                   DebugLoc dl) {
134   if (isa<ConstantSDNode>(Idx)) {
135     EVT VT = Vec.getValueType();
136     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138     EVT ElVT = VT.getVectorElementType();
139
140     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142     EVT ResultVT = Result.getValueType();
143
144     // Insert the relevant 128 bits.
145     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147     // This is the index of the first element of the 128-bit chunk
148     // we want.
149     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                  * ElemsPerChunk);
151
152     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                          VecIdx);
156     return Result;
157   }
158
159   return SDValue();
160 }
161
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164   DebugLoc dl = Lower.getDebugLoc();
165
166   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168   EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                             Lower.getValueType().getVectorElementType(),
170                             Lower.getValueType().getVectorNumElements() * 2);
171
172   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175   // Insert the upper subvector.
176   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                    DAG.getConstant(
178                                      // This is half the length of the result
179                                      // vector.  Start inserting the upper 128
180                                      // bits here.
181                                      Lower.getValueType().getVectorNumElements(),
182                                      MVT::i32),
183                                    DAG, dl);
184
185   // Insert the lower subvector.
186   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187   return Vec;
188 }
189
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192   bool is64Bit = Subtarget->is64Bit();
193
194   if (Subtarget->isTargetEnvMacho()) {
195     if (is64Bit)
196       return new X8664_MachoTargetObjectFile();
197     return new TargetLoweringObjectFileMachO();
198   }
199
200   if (Subtarget->isTargetELF()) {
201     if (is64Bit)
202       return new X8664_ELFTargetObjectFile(TM);
203     return new X8632_ELFTargetObjectFile(TM);
204   }
205   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206     return new TargetLoweringObjectFileCOFF();
207   llvm_unreachable("unknown subtarget type");
208 }
209
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211   : TargetLowering(TM, createTLOF(TM)) {
212   Subtarget = &TM.getSubtarget<X86Subtarget>();
213   X86ScalarSSEf64 = Subtarget->hasXMMInt();
214   X86ScalarSSEf32 = Subtarget->hasXMM();
215   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217   RegInfo = TM.getRegisterInfo();
218   TD = getTargetData();
219
220   // Set up the TargetLowering object.
221   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223   // X86 is weird, it always uses i8 for shift amounts and setcc results.
224   setBooleanContents(ZeroOrOneBooleanContent);
225     
226   // For 64-bit since we have so many registers use the ILP scheduler, for
227   // 32-bit code use the register pressure specific scheduling.
228   if (Subtarget->is64Bit())
229     setSchedulingPreference(Sched::ILP);
230   else
231     setSchedulingPreference(Sched::RegPressure);
232   setStackPointerRegisterToSaveRestore(X86StackPtr);
233
234   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235     // Setup Windows compiler runtime calls.
236     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
244   }
245
246   if (Subtarget->isTargetDarwin()) {
247     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248     setUseUnderscoreSetJmp(false);
249     setUseUnderscoreLongJmp(false);
250   } else if (Subtarget->isTargetMingw()) {
251     // MS runtime is weird: it exports _setjmp, but longjmp!
252     setUseUnderscoreSetJmp(true);
253     setUseUnderscoreLongJmp(false);
254   } else {
255     setUseUnderscoreSetJmp(true);
256     setUseUnderscoreLongJmp(true);
257   }
258
259   // Set up the register classes.
260   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263   if (Subtarget->is64Bit())
264     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265
266   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267
268   // We don't accept any truncstore of integer registers.
269   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
275
276   // SETOEQ and SETUNE require checking two conditions.
277   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283
284   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285   // operation.
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
288   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
289
290   if (Subtarget->is64Bit()) {
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
292     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
293   } else if (!UseSoftFloat) {
294     // We have an algorithm for SSE2->double, and we turn this into a
295     // 64-bit FILD followed by conditional FADD for other targets.
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
297     // We have an algorithm for SSE2, and we turn this into a 64-bit
298     // FILD for other targets.
299     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
300   }
301
302   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303   // this operation.
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
305   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
306
307   if (!UseSoftFloat) {
308     // SSE has no i16 to fp conversion, only i32
309     if (X86ScalarSSEf32) {
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
311       // f32 and f64 cases are Legal, f80 case is not
312       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
313     } else {
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
316     }
317   } else {
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
319     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
320   }
321
322   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
323   // are Legal, f80 is custom lowered.
324   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
325   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
326
327   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328   // this operation.
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
330   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
331
332   if (X86ScalarSSEf32) {
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
334     // f32 and f64 cases are Legal, f80 case is not
335     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
336   } else {
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
339   }
340
341   // Handle FP_TO_UINT by promoting the destination to a larger signed
342   // conversion.
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
345   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
346
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
349     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
350   } else if (!UseSoftFloat) {
351     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352       // Expand FP_TO_UINT into a select.
353       // FIXME: We would like to use a Custom expander here eventually to do
354       // the optimal thing for SSE vs. the default expansion in the legalizer.
355       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
356     else
357       // With SSE3 we can use fisttpll to convert to a signed i64; without
358       // SSE, we're stuck with a fistpll.
359       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
360   }
361
362   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363   if (!X86ScalarSSEf64) {
364     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
365     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
366     if (Subtarget->is64Bit()) {
367       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
368       // Without SSE, i64->f64 goes through memory.
369       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
370     }
371   }
372
373   // Scalar integer divide and remainder are lowered to use operations that
374   // produce two results, to match the available instructions. This exposes
375   // the two-result form to trivial CSE, which is able to combine x/y and x%y
376   // into a single instruction.
377   //
378   // Scalar integer multiply-high is also lowered to use two-result
379   // operations, to match the available instructions. However, plain multiply
380   // (low) operations are left as Legal, as there are single-result
381   // instructions for this in x86. Using the two-result multiply instructions
382   // when both high and low results are needed must be arranged by dagcombine.
383   for (unsigned i = 0, e = 4; i != e; ++i) {
384     MVT VT = IntVTs[i];
385     setOperationAction(ISD::MULHS, VT, Expand);
386     setOperationAction(ISD::MULHU, VT, Expand);
387     setOperationAction(ISD::SDIV, VT, Expand);
388     setOperationAction(ISD::UDIV, VT, Expand);
389     setOperationAction(ISD::SREM, VT, Expand);
390     setOperationAction(ISD::UREM, VT, Expand);
391
392     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393     setOperationAction(ISD::ADDC, VT, Custom);
394     setOperationAction(ISD::ADDE, VT, Custom);
395     setOperationAction(ISD::SUBC, VT, Custom);
396     setOperationAction(ISD::SUBE, VT, Custom);
397   }
398
399   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
400   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
401   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
408   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
412   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
413
414   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
416   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
418   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
419   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
420   if (Subtarget->is64Bit()) {
421     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
422     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
423   }
424
425   if (Subtarget->hasPOPCNT()) {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
427   } else {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
433   }
434
435   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
436   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
437
438   // These should be promoted to a larger select which is supported.
439   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
440   // X86 wants to expand cmov itself.
441   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
455     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
456   }
457   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
458
459   // Darwin ABI issue.
460   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
461   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
463   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
464   if (Subtarget->is64Bit())
465     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
467   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
470     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
471     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
472     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
473     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
474   }
475   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
478   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
479   if (Subtarget->is64Bit()) {
480     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
482     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
483   }
484
485   if (Subtarget->hasXMM())
486     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
487
488   // We may not have a libcall for MEMBARRIER so we should lower this.
489   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
490
491   // On X86 and X86-64, atomic operations are lowered to locked instructions.
492   // Locked instructions, in turn, have implicit fence semantics (all memory
493   // operations are flushed before issuing the locked instruction, and they
494   // are not buffered), so we can fold away the common pattern of
495   // fence-atomic-fence.
496   setShouldFoldAtomicFences(true);
497
498   // Expand certain atomics
499   for (unsigned i = 0, e = 4; i != e; ++i) {
500     MVT VT = IntVTs[i];
501     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
503   }
504
505   if (!Subtarget->is64Bit()) {
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   // FIXME - use subtarget debug flags
516   if (!Subtarget->isTargetDarwin() &&
517       !Subtarget->isTargetELF() &&
518       !Subtarget->isTargetCygMing()) {
519     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526   if (Subtarget->is64Bit()) {
527     setExceptionPointerRegister(X86::RAX);
528     setExceptionSelectorRegister(X86::RDX);
529   } else {
530     setExceptionPointerRegister(X86::EAX);
531     setExceptionSelectorRegister(X86::EDX);
532   }
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539
540   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   if (Subtarget->is64Bit()) {
544     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
545     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
546   } else {
547     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
548     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
549   }
550
551   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
552   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
553   setOperationAction(ISD::DYNAMIC_STACKALLOC,
554                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555                      (Subtarget->isTargetCOFF()
556                       && !Subtarget->isTargetEnvMacho()
557                       ? Custom : Expand));
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // Lower this to FGETSIGNx86 plus an AND.
578     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
579     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
580
581     // We don't support sin/cos/fmod
582     setOperationAction(ISD::FSIN , MVT::f64, Expand);
583     setOperationAction(ISD::FCOS , MVT::f64, Expand);
584     setOperationAction(ISD::FSIN , MVT::f32, Expand);
585     setOperationAction(ISD::FCOS , MVT::f32, Expand);
586
587     // Expand FP immediates into loads from the stack, except for the special
588     // cases we handle.
589     addLegalFPImmediate(APFloat(+0.0)); // xorpd
590     addLegalFPImmediate(APFloat(+0.0f)); // xorps
591   } else if (!UseSoftFloat && X86ScalarSSEf32) {
592     // Use SSE for f32, x87 for f64.
593     // Set up the FP register classes.
594     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
595     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
596
597     // Use ANDPS to simulate FABS.
598     setOperationAction(ISD::FABS , MVT::f32, Custom);
599
600     // Use XORP to simulate FNEG.
601     setOperationAction(ISD::FNEG , MVT::f32, Custom);
602
603     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
604
605     // Use ANDPS and ORPS to simulate FCOPYSIGN.
606     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
607     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
608
609     // We don't support sin/cos/fmod
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Special cases we handle for FP constants.
614     addLegalFPImmediate(APFloat(+0.0f)); // xorps
615     addLegalFPImmediate(APFloat(+0.0)); // FLD0
616     addLegalFPImmediate(APFloat(+1.0)); // FLD1
617     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619
620     if (!UnsafeFPMath) {
621       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
622       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
623     }
624   } else if (!UseSoftFloat) {
625     // f32 and f64 in x87.
626     // Set up the FP register classes.
627     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
628     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
634
635     if (!UnsafeFPMath) {
636       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
637       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
638     }
639     addLegalFPImmediate(APFloat(+0.0)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
643     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
647   }
648
649   // Long double always uses X87.
650   if (!UseSoftFloat) {
651     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
652     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
653     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
654     {
655       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
656       addLegalFPImmediate(TmpFlt);  // FLD0
657       TmpFlt.changeSign();
658       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
659
660       bool ignored;
661       APFloat TmpFlt2(+1.0);
662       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
663                       &ignored);
664       addLegalFPImmediate(TmpFlt2);  // FLD1
665       TmpFlt2.changeSign();
666       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
667     }
668
669     if (!UnsafeFPMath) {
670       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
671       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
672     }
673   }
674
675   // Always use a library call for pow.
676   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
677   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
679
680   setOperationAction(ISD::FLOG, MVT::f80, Expand);
681   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
683   setOperationAction(ISD::FEXP, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
685
686   // First set operation action for all vector types to either promote
687   // (for widening) or expand (for scalarization). Then we will selectively
688   // turn on ones that can be effectively codegen'd.
689   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
690        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
691     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
706     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
708     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
741     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
746          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
747       setTruncStoreAction((MVT::SimpleValueType)VT,
748                           (MVT::SimpleValueType)InnerVT, Expand);
749     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
750     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
752   }
753
754   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
755   // with -msoft-float, disable use of MMX as well.
756   if (!UseSoftFloat && Subtarget->hasMMX()) {
757     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
758     // No operations on x86mmx supported, everything uses intrinsics.
759   }
760
761   // MMX-sized vectors (other than x86mmx) are expected to be expanded
762   // into smaller operations.
763   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
764   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
765   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
767   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
768   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
769   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
770   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
771   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
772   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
773   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
774   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
775   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
776   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
777   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
778   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
779   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
783   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
784   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
785   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
786   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
788   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
792
793   if (!UseSoftFloat && Subtarget->hasXMM()) {
794     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
795
796     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
801     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
802     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
803     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
804     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
805     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
807     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
808   }
809
810   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
811     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
812
813     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
814     // registers cannot be used even for integer operations.
815     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
816     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
819
820     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
821     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
822     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
823     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
825     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
826     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
827     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
828     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
829     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
830     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
831     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
835     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
836
837     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
838     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
841
842     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
847
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
853
854     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
856       EVT VT = (MVT::SimpleValueType)i;
857       // Do not attempt to custom lower non-power-of-2 vectors
858       if (!isPowerOf2_32(VT.getVectorNumElements()))
859         continue;
860       // Do not attempt to custom lower non-128-bit vectors
861       if (!VT.is128BitVector())
862         continue;
863       setOperationAction(ISD::BUILD_VECTOR,
864                          VT.getSimpleVT().SimpleTy, Custom);
865       setOperationAction(ISD::VECTOR_SHUFFLE,
866                          VT.getSimpleVT().SimpleTy, Custom);
867       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
868                          VT.getSimpleVT().SimpleTy, Custom);
869     }
870
871     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
873     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
876     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
877
878     if (Subtarget->is64Bit()) {
879       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
880       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
881     }
882
883     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
884     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
885       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
886       EVT VT = SVT;
887
888       // Do not attempt to promote non-128-bit vectors
889       if (!VT.is128BitVector())
890         continue;
891
892       setOperationAction(ISD::AND,    SVT, Promote);
893       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
894       setOperationAction(ISD::OR,     SVT, Promote);
895       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
896       setOperationAction(ISD::XOR,    SVT, Promote);
897       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
898       setOperationAction(ISD::LOAD,   SVT, Promote);
899       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
900       setOperationAction(ISD::SELECT, SVT, Promote);
901       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
902     }
903
904     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914   }
915
916   if (Subtarget->hasSSE41()) {
917     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
922     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
923     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
924     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
925     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
926     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
927
928     // FIXME: Do we need to handle scalar-to-vector here?
929     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
930
931     // Can turn SHL into an integer multiply.
932     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
933     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
934
935     // i8 and i16 vectors are custom , because the source register and source
936     // source memory operand types are not the same width.  f32 vectors are
937     // custom since the immediate controlling the insert encodes additional
938     // information.
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
943
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
948
949     if (Subtarget->is64Bit()) {
950       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
951       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
952     }
953   }
954
955   if (Subtarget->hasSSE2()) {
956     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
957     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
959
960     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
961     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
962     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
963
964     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
966   }
967
968   if (Subtarget->hasSSE42())
969     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
970
971   if (!UseSoftFloat && Subtarget->hasAVX()) {
972     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
973     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
974     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
976     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
977
978     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
979     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
982
983     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
989
990     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
995     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
996
997     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
998     // insert_vector_elt extract_subvector and extract_vector_elt for
999     // 256-bit types.
1000     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1002          ++i) {
1003       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1004       // Do not attempt to custom lower non-256-bit vectors
1005       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1006           || (MVT(VT).getSizeInBits() < 256))
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1013     }
1014     // Custom-lower insert_subvector and extract_subvector based on
1015     // the result type.
1016     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1017          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1018          ++i) {
1019       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1020       // Do not attempt to custom lower non-256-bit vectors
1021       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1022         continue;
1023
1024       if (MVT(VT).getSizeInBits() == 128) {
1025         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1026       }
1027       else if (MVT(VT).getSizeInBits() == 256) {
1028         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1029       }
1030     }
1031
1032     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1033     // Don't promote loads because we need them for VPERM vector index versions.
1034
1035     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1036          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1037          VT++) {
1038       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1039           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1040         continue;
1041       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1042       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1043       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1044       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1045       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1046       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1047       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1048       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1049       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1050       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1051     }
1052   }
1053
1054   // We want to custom lower some of our intrinsics.
1055   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1056
1057
1058   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1059   // handle type legalization for these operations here.
1060   //
1061   // FIXME: We really should do custom legalization for addition and
1062   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1063   // than generic legalization for 64-bit multiplication-with-overflow, though.
1064   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1065     // Add/Sub/Mul with overflow operations are custom lowered.
1066     MVT VT = IntVTs[i];
1067     setOperationAction(ISD::SADDO, VT, Custom);
1068     setOperationAction(ISD::UADDO, VT, Custom);
1069     setOperationAction(ISD::SSUBO, VT, Custom);
1070     setOperationAction(ISD::USUBO, VT, Custom);
1071     setOperationAction(ISD::SMULO, VT, Custom);
1072     setOperationAction(ISD::UMULO, VT, Custom);
1073   }
1074
1075   // There are no 8-bit 3-address imul/mul instructions
1076   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1077   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1078
1079   if (!Subtarget->is64Bit()) {
1080     // These libcalls are not available in 32-bit.
1081     setLibcallName(RTLIB::SHL_I128, 0);
1082     setLibcallName(RTLIB::SRL_I128, 0);
1083     setLibcallName(RTLIB::SRA_I128, 0);
1084   }
1085
1086   // We have target-specific dag combine patterns for the following nodes:
1087   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1088   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1089   setTargetDAGCombine(ISD::BUILD_VECTOR);
1090   setTargetDAGCombine(ISD::SELECT);
1091   setTargetDAGCombine(ISD::SHL);
1092   setTargetDAGCombine(ISD::SRA);
1093   setTargetDAGCombine(ISD::SRL);
1094   setTargetDAGCombine(ISD::OR);
1095   setTargetDAGCombine(ISD::AND);
1096   setTargetDAGCombine(ISD::ADD);
1097   setTargetDAGCombine(ISD::SUB);
1098   setTargetDAGCombine(ISD::STORE);
1099   setTargetDAGCombine(ISD::ZERO_EXTEND);
1100   if (Subtarget->is64Bit())
1101     setTargetDAGCombine(ISD::MUL);
1102
1103   computeRegisterProperties();
1104
1105   // On Darwin, -Os means optimize for size without hurting performance,
1106   // do not reduce the limit.
1107   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1108   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1109   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1110   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1111   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1112   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1113   setPrefLoopAlignment(16);
1114   benefitFromCodePlacementOpt = true;
1115
1116   setPrefFunctionAlignment(4);
1117 }
1118
1119
1120 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1121   return MVT::i8;
1122 }
1123
1124
1125 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1126 /// the desired ByVal argument alignment.
1127 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1128   if (MaxAlign == 16)
1129     return;
1130   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1131     if (VTy->getBitWidth() == 128)
1132       MaxAlign = 16;
1133   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1134     unsigned EltAlign = 0;
1135     getMaxByValAlign(ATy->getElementType(), EltAlign);
1136     if (EltAlign > MaxAlign)
1137       MaxAlign = EltAlign;
1138   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1139     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1140       unsigned EltAlign = 0;
1141       getMaxByValAlign(STy->getElementType(i), EltAlign);
1142       if (EltAlign > MaxAlign)
1143         MaxAlign = EltAlign;
1144       if (MaxAlign == 16)
1145         break;
1146     }
1147   }
1148   return;
1149 }
1150
1151 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1152 /// function arguments in the caller parameter area. For X86, aggregates
1153 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1154 /// are at 4-byte boundaries.
1155 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1156   if (Subtarget->is64Bit()) {
1157     // Max of 8 and alignment of type.
1158     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1159     if (TyAlign > 8)
1160       return TyAlign;
1161     return 8;
1162   }
1163
1164   unsigned Align = 4;
1165   if (Subtarget->hasXMM())
1166     getMaxByValAlign(Ty, Align);
1167   return Align;
1168 }
1169
1170 /// getOptimalMemOpType - Returns the target specific optimal type for load
1171 /// and store operations as a result of memset, memcpy, and memmove
1172 /// lowering. If DstAlign is zero that means it's safe to destination
1173 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1174 /// means there isn't a need to check it against alignment requirement,
1175 /// probably because the source does not need to be loaded. If
1176 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1177 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1178 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1179 /// constant so it does not need to be loaded.
1180 /// It returns EVT::Other if the type should be determined using generic
1181 /// target-independent logic.
1182 EVT
1183 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1184                                        unsigned DstAlign, unsigned SrcAlign,
1185                                        bool NonScalarIntSafe,
1186                                        bool MemcpyStrSrc,
1187                                        MachineFunction &MF) const {
1188   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1189   // linux.  This is because the stack realignment code can't handle certain
1190   // cases like PR2962.  This should be removed when PR2962 is fixed.
1191   const Function *F = MF.getFunction();
1192   if (NonScalarIntSafe &&
1193       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1194     if (Size >= 16 &&
1195         (Subtarget->isUnalignedMemAccessFast() ||
1196          ((DstAlign == 0 || DstAlign >= 16) &&
1197           (SrcAlign == 0 || SrcAlign >= 16))) &&
1198         Subtarget->getStackAlignment() >= 16) {
1199       if (Subtarget->hasSSE2())
1200         return MVT::v4i32;
1201       if (Subtarget->hasSSE1())
1202         return MVT::v4f32;
1203     } else if (!MemcpyStrSrc && Size >= 8 &&
1204                !Subtarget->is64Bit() &&
1205                Subtarget->getStackAlignment() >= 8 &&
1206                Subtarget->hasXMMInt()) {
1207       // Do not use f64 to lower memcpy if source is string constant. It's
1208       // better to use i32 to avoid the loads.
1209       return MVT::f64;
1210     }
1211   }
1212   if (Subtarget->is64Bit() && Size >= 8)
1213     return MVT::i64;
1214   return MVT::i32;
1215 }
1216
1217 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1218 /// current function.  The returned value is a member of the
1219 /// MachineJumpTableInfo::JTEntryKind enum.
1220 unsigned X86TargetLowering::getJumpTableEncoding() const {
1221   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1222   // symbol.
1223   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1224       Subtarget->isPICStyleGOT())
1225     return MachineJumpTableInfo::EK_Custom32;
1226
1227   // Otherwise, use the normal jump table encoding heuristics.
1228   return TargetLowering::getJumpTableEncoding();
1229 }
1230
1231 const MCExpr *
1232 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1233                                              const MachineBasicBlock *MBB,
1234                                              unsigned uid,MCContext &Ctx) const{
1235   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1236          Subtarget->isPICStyleGOT());
1237   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1238   // entries.
1239   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1240                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1241 }
1242
1243 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1244 /// jumptable.
1245 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1246                                                     SelectionDAG &DAG) const {
1247   if (!Subtarget->is64Bit())
1248     // This doesn't have DebugLoc associated with it, but is not really the
1249     // same as a Register.
1250     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1251   return Table;
1252 }
1253
1254 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1255 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1256 /// MCExpr.
1257 const MCExpr *X86TargetLowering::
1258 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1259                              MCContext &Ctx) const {
1260   // X86-64 uses RIP relative addressing based on the jump table label.
1261   if (Subtarget->isPICStyleRIPRel())
1262     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1263
1264   // Otherwise, the reference is relative to the PIC base.
1265   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1266 }
1267
1268 // FIXME: Why this routine is here? Move to RegInfo!
1269 std::pair<const TargetRegisterClass*, uint8_t>
1270 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1271   const TargetRegisterClass *RRC = 0;
1272   uint8_t Cost = 1;
1273   switch (VT.getSimpleVT().SimpleTy) {
1274   default:
1275     return TargetLowering::findRepresentativeClass(VT);
1276   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1277     RRC = (Subtarget->is64Bit()
1278            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1279     break;
1280   case MVT::x86mmx:
1281     RRC = X86::VR64RegisterClass;
1282     break;
1283   case MVT::f32: case MVT::f64:
1284   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1285   case MVT::v4f32: case MVT::v2f64:
1286   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1287   case MVT::v4f64:
1288     RRC = X86::VR128RegisterClass;
1289     break;
1290   }
1291   return std::make_pair(RRC, Cost);
1292 }
1293
1294 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1295                                                unsigned &Offset) const {
1296   if (!Subtarget->isTargetLinux())
1297     return false;
1298
1299   if (Subtarget->is64Bit()) {
1300     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1301     Offset = 0x28;
1302     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1303       AddressSpace = 256;
1304     else
1305       AddressSpace = 257;
1306   } else {
1307     // %gs:0x14 on i386
1308     Offset = 0x14;
1309     AddressSpace = 256;
1310   }
1311   return true;
1312 }
1313
1314
1315 //===----------------------------------------------------------------------===//
1316 //               Return Value Calling Convention Implementation
1317 //===----------------------------------------------------------------------===//
1318
1319 #include "X86GenCallingConv.inc"
1320
1321 bool
1322 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1323                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1324                         LLVMContext &Context) const {
1325   SmallVector<CCValAssign, 16> RVLocs;
1326   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1327                  RVLocs, Context);
1328   return CCInfo.CheckReturn(Outs, RetCC_X86);
1329 }
1330
1331 SDValue
1332 X86TargetLowering::LowerReturn(SDValue Chain,
1333                                CallingConv::ID CallConv, bool isVarArg,
1334                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1335                                const SmallVectorImpl<SDValue> &OutVals,
1336                                DebugLoc dl, SelectionDAG &DAG) const {
1337   MachineFunction &MF = DAG.getMachineFunction();
1338   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1339
1340   SmallVector<CCValAssign, 16> RVLocs;
1341   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1342                  RVLocs, *DAG.getContext());
1343   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1344
1345   // Add the regs to the liveout set for the function.
1346   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1347   for (unsigned i = 0; i != RVLocs.size(); ++i)
1348     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1349       MRI.addLiveOut(RVLocs[i].getLocReg());
1350
1351   SDValue Flag;
1352
1353   SmallVector<SDValue, 6> RetOps;
1354   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1355   // Operand #1 = Bytes To Pop
1356   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1357                    MVT::i16));
1358
1359   // Copy the result values into the output registers.
1360   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1361     CCValAssign &VA = RVLocs[i];
1362     assert(VA.isRegLoc() && "Can only return in registers!");
1363     SDValue ValToCopy = OutVals[i];
1364     EVT ValVT = ValToCopy.getValueType();
1365
1366     // If this is x86-64, and we disabled SSE, we can't return FP values,
1367     // or SSE or MMX vectors.
1368     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1369          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1370           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1371       report_fatal_error("SSE register return with SSE disabled");
1372     }
1373     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1374     // llvm-gcc has never done it right and no one has noticed, so this
1375     // should be OK for now.
1376     if (ValVT == MVT::f64 &&
1377         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1378       report_fatal_error("SSE2 register return with SSE2 disabled");
1379
1380     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1381     // the RET instruction and handled by the FP Stackifier.
1382     if (VA.getLocReg() == X86::ST0 ||
1383         VA.getLocReg() == X86::ST1) {
1384       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1385       // change the value to the FP stack register class.
1386       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1387         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1388       RetOps.push_back(ValToCopy);
1389       // Don't emit a copytoreg.
1390       continue;
1391     }
1392
1393     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1394     // which is returned in RAX / RDX.
1395     if (Subtarget->is64Bit()) {
1396       if (ValVT == MVT::x86mmx) {
1397         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1398           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1399           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1400                                   ValToCopy);
1401           // If we don't have SSE2 available, convert to v4f32 so the generated
1402           // register is legal.
1403           if (!Subtarget->hasSSE2())
1404             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1405         }
1406       }
1407     }
1408
1409     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1410     Flag = Chain.getValue(1);
1411   }
1412
1413   // The x86-64 ABI for returning structs by value requires that we copy
1414   // the sret argument into %rax for the return. We saved the argument into
1415   // a virtual register in the entry block, so now we copy the value out
1416   // and into %rax.
1417   if (Subtarget->is64Bit() &&
1418       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1419     MachineFunction &MF = DAG.getMachineFunction();
1420     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1421     unsigned Reg = FuncInfo->getSRetReturnReg();
1422     assert(Reg &&
1423            "SRetReturnReg should have been set in LowerFormalArguments().");
1424     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1425
1426     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1427     Flag = Chain.getValue(1);
1428
1429     // RAX now acts like a return value.
1430     MRI.addLiveOut(X86::RAX);
1431   }
1432
1433   RetOps[0] = Chain;  // Update chain.
1434
1435   // Add the flag if we have it.
1436   if (Flag.getNode())
1437     RetOps.push_back(Flag);
1438
1439   return DAG.getNode(X86ISD::RET_FLAG, dl,
1440                      MVT::Other, &RetOps[0], RetOps.size());
1441 }
1442
1443 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1444   if (N->getNumValues() != 1)
1445     return false;
1446   if (!N->hasNUsesOfValue(1, 0))
1447     return false;
1448
1449   SDNode *Copy = *N->use_begin();
1450   if (Copy->getOpcode() != ISD::CopyToReg &&
1451       Copy->getOpcode() != ISD::FP_EXTEND)
1452     return false;
1453
1454   bool HasRet = false;
1455   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1456        UI != UE; ++UI) {
1457     if (UI->getOpcode() != X86ISD::RET_FLAG)
1458       return false;
1459     HasRet = true;
1460   }
1461
1462   return HasRet;
1463 }
1464
1465 EVT
1466 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1467                                             ISD::NodeType ExtendKind) const {
1468   MVT ReturnMVT;
1469   // TODO: Is this also valid on 32-bit?
1470   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1471     ReturnMVT = MVT::i8;
1472   else
1473     ReturnMVT = MVT::i32;
1474
1475   EVT MinVT = getRegisterType(Context, ReturnMVT);
1476   return VT.bitsLT(MinVT) ? MinVT : VT;
1477 }
1478
1479 /// LowerCallResult - Lower the result values of a call into the
1480 /// appropriate copies out of appropriate physical registers.
1481 ///
1482 SDValue
1483 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1484                                    CallingConv::ID CallConv, bool isVarArg,
1485                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1486                                    DebugLoc dl, SelectionDAG &DAG,
1487                                    SmallVectorImpl<SDValue> &InVals) const {
1488
1489   // Assign locations to each value returned by this call.
1490   SmallVector<CCValAssign, 16> RVLocs;
1491   bool Is64Bit = Subtarget->is64Bit();
1492   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1493                  RVLocs, *DAG.getContext());
1494   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1495
1496   // Copy all of the result registers out of their specified physreg.
1497   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1498     CCValAssign &VA = RVLocs[i];
1499     EVT CopyVT = VA.getValVT();
1500
1501     // If this is x86-64, and we disabled SSE, we can't return FP values
1502     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1503         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1504       report_fatal_error("SSE register return with SSE disabled");
1505     }
1506
1507     SDValue Val;
1508
1509     // If this is a call to a function that returns an fp value on the floating
1510     // point stack, we must guarantee the the value is popped from the stack, so
1511     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1512     // if the return value is not used. We use the FpGET_ST0 instructions
1513     // instead.
1514     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1515       // If we prefer to use the value in xmm registers, copy it out as f80 and
1516       // use a truncate to move it from fp stack reg to xmm reg.
1517       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1518       bool isST0 = VA.getLocReg() == X86::ST0;
1519       unsigned Opc = 0;
1520       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1521       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1522       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1523       SDValue Ops[] = { Chain, InFlag };
1524       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1525                                          Ops, 2), 1);
1526       Val = Chain.getValue(0);
1527
1528       // Round the f80 to the right size, which also moves it to the appropriate
1529       // xmm register.
1530       if (CopyVT != VA.getValVT())
1531         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1532                           // This truncation won't change the value.
1533                           DAG.getIntPtrConstant(1));
1534     } else {
1535       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1536                                  CopyVT, InFlag).getValue(1);
1537       Val = Chain.getValue(0);
1538     }
1539     InFlag = Chain.getValue(2);
1540     InVals.push_back(Val);
1541   }
1542
1543   return Chain;
1544 }
1545
1546
1547 //===----------------------------------------------------------------------===//
1548 //                C & StdCall & Fast Calling Convention implementation
1549 //===----------------------------------------------------------------------===//
1550 //  StdCall calling convention seems to be standard for many Windows' API
1551 //  routines and around. It differs from C calling convention just a little:
1552 //  callee should clean up the stack, not caller. Symbols should be also
1553 //  decorated in some fancy way :) It doesn't support any vector arguments.
1554 //  For info on fast calling convention see Fast Calling Convention (tail call)
1555 //  implementation LowerX86_32FastCCCallTo.
1556
1557 /// CallIsStructReturn - Determines whether a call uses struct return
1558 /// semantics.
1559 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1560   if (Outs.empty())
1561     return false;
1562
1563   return Outs[0].Flags.isSRet();
1564 }
1565
1566 /// ArgsAreStructReturn - Determines whether a function uses struct
1567 /// return semantics.
1568 static bool
1569 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1570   if (Ins.empty())
1571     return false;
1572
1573   return Ins[0].Flags.isSRet();
1574 }
1575
1576 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1577 /// by "Src" to address "Dst" with size and alignment information specified by
1578 /// the specific parameter attribute. The copy will be passed as a byval
1579 /// function parameter.
1580 static SDValue
1581 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1582                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1583                           DebugLoc dl) {
1584   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1585
1586   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1587                        /*isVolatile*/false, /*AlwaysInline=*/true,
1588                        MachinePointerInfo(), MachinePointerInfo());
1589 }
1590
1591 /// IsTailCallConvention - Return true if the calling convention is one that
1592 /// supports tail call optimization.
1593 static bool IsTailCallConvention(CallingConv::ID CC) {
1594   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1595 }
1596
1597 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1598   if (!CI->isTailCall())
1599     return false;
1600
1601   CallSite CS(CI);
1602   CallingConv::ID CalleeCC = CS.getCallingConv();
1603   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1604     return false;
1605
1606   return true;
1607 }
1608
1609 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1610 /// a tailcall target by changing its ABI.
1611 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1612   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1613 }
1614
1615 SDValue
1616 X86TargetLowering::LowerMemArgument(SDValue Chain,
1617                                     CallingConv::ID CallConv,
1618                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1619                                     DebugLoc dl, SelectionDAG &DAG,
1620                                     const CCValAssign &VA,
1621                                     MachineFrameInfo *MFI,
1622                                     unsigned i) const {
1623   // Create the nodes corresponding to a load from this parameter slot.
1624   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1625   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1626   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1627   EVT ValVT;
1628
1629   // If value is passed by pointer we have address passed instead of the value
1630   // itself.
1631   if (VA.getLocInfo() == CCValAssign::Indirect)
1632     ValVT = VA.getLocVT();
1633   else
1634     ValVT = VA.getValVT();
1635
1636   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1637   // changed with more analysis.
1638   // In case of tail call optimization mark all arguments mutable. Since they
1639   // could be overwritten by lowering of arguments in case of a tail call.
1640   if (Flags.isByVal()) {
1641     unsigned Bytes = Flags.getByValSize();
1642     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1643     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1644     return DAG.getFrameIndex(FI, getPointerTy());
1645   } else {
1646     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1647                                     VA.getLocMemOffset(), isImmutable);
1648     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1649     return DAG.getLoad(ValVT, dl, Chain, FIN,
1650                        MachinePointerInfo::getFixedStack(FI),
1651                        false, false, 0);
1652   }
1653 }
1654
1655 SDValue
1656 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1657                                         CallingConv::ID CallConv,
1658                                         bool isVarArg,
1659                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1660                                         DebugLoc dl,
1661                                         SelectionDAG &DAG,
1662                                         SmallVectorImpl<SDValue> &InVals)
1663                                           const {
1664   MachineFunction &MF = DAG.getMachineFunction();
1665   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1666
1667   const Function* Fn = MF.getFunction();
1668   if (Fn->hasExternalLinkage() &&
1669       Subtarget->isTargetCygMing() &&
1670       Fn->getName() == "main")
1671     FuncInfo->setForceFramePointer(true);
1672
1673   MachineFrameInfo *MFI = MF.getFrameInfo();
1674   bool Is64Bit = Subtarget->is64Bit();
1675   bool IsWin64 = Subtarget->isTargetWin64();
1676
1677   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1678          "Var args not supported with calling convention fastcc or ghc");
1679
1680   // Assign locations to all of the incoming arguments.
1681   SmallVector<CCValAssign, 16> ArgLocs;
1682   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1683                  ArgLocs, *DAG.getContext());
1684
1685   // Allocate shadow area for Win64
1686   if (IsWin64) {
1687     CCInfo.AllocateStack(32, 8);
1688   }
1689
1690   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1691
1692   unsigned LastVal = ~0U;
1693   SDValue ArgValue;
1694   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1695     CCValAssign &VA = ArgLocs[i];
1696     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1697     // places.
1698     assert(VA.getValNo() != LastVal &&
1699            "Don't support value assigned to multiple locs yet");
1700     LastVal = VA.getValNo();
1701
1702     if (VA.isRegLoc()) {
1703       EVT RegVT = VA.getLocVT();
1704       TargetRegisterClass *RC = NULL;
1705       if (RegVT == MVT::i32)
1706         RC = X86::GR32RegisterClass;
1707       else if (Is64Bit && RegVT == MVT::i64)
1708         RC = X86::GR64RegisterClass;
1709       else if (RegVT == MVT::f32)
1710         RC = X86::FR32RegisterClass;
1711       else if (RegVT == MVT::f64)
1712         RC = X86::FR64RegisterClass;
1713       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1714         RC = X86::VR256RegisterClass;
1715       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1716         RC = X86::VR128RegisterClass;
1717       else if (RegVT == MVT::x86mmx)
1718         RC = X86::VR64RegisterClass;
1719       else
1720         llvm_unreachable("Unknown argument type!");
1721
1722       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1723       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1724
1725       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1726       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1727       // right size.
1728       if (VA.getLocInfo() == CCValAssign::SExt)
1729         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1730                                DAG.getValueType(VA.getValVT()));
1731       else if (VA.getLocInfo() == CCValAssign::ZExt)
1732         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1733                                DAG.getValueType(VA.getValVT()));
1734       else if (VA.getLocInfo() == CCValAssign::BCvt)
1735         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1736
1737       if (VA.isExtInLoc()) {
1738         // Handle MMX values passed in XMM regs.
1739         if (RegVT.isVector()) {
1740           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1741                                  ArgValue);
1742         } else
1743           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1744       }
1745     } else {
1746       assert(VA.isMemLoc());
1747       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1748     }
1749
1750     // If value is passed via pointer - do a load.
1751     if (VA.getLocInfo() == CCValAssign::Indirect)
1752       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1753                              MachinePointerInfo(), false, false, 0);
1754
1755     InVals.push_back(ArgValue);
1756   }
1757
1758   // The x86-64 ABI for returning structs by value requires that we copy
1759   // the sret argument into %rax for the return. Save the argument into
1760   // a virtual register so that we can access it from the return points.
1761   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1762     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1763     unsigned Reg = FuncInfo->getSRetReturnReg();
1764     if (!Reg) {
1765       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1766       FuncInfo->setSRetReturnReg(Reg);
1767     }
1768     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1769     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1770   }
1771
1772   unsigned StackSize = CCInfo.getNextStackOffset();
1773   // Align stack specially for tail calls.
1774   if (FuncIsMadeTailCallSafe(CallConv))
1775     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1776
1777   // If the function takes variable number of arguments, make a frame index for
1778   // the start of the first vararg value... for expansion of llvm.va_start.
1779   if (isVarArg) {
1780     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1781                     CallConv != CallingConv::X86_ThisCall)) {
1782       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1783     }
1784     if (Is64Bit) {
1785       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1786
1787       // FIXME: We should really autogenerate these arrays
1788       static const unsigned GPR64ArgRegsWin64[] = {
1789         X86::RCX, X86::RDX, X86::R8,  X86::R9
1790       };
1791       static const unsigned GPR64ArgRegs64Bit[] = {
1792         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1793       };
1794       static const unsigned XMMArgRegs64Bit[] = {
1795         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1796         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1797       };
1798       const unsigned *GPR64ArgRegs;
1799       unsigned NumXMMRegs = 0;
1800
1801       if (IsWin64) {
1802         // The XMM registers which might contain var arg parameters are shadowed
1803         // in their paired GPR.  So we only need to save the GPR to their home
1804         // slots.
1805         TotalNumIntRegs = 4;
1806         GPR64ArgRegs = GPR64ArgRegsWin64;
1807       } else {
1808         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1809         GPR64ArgRegs = GPR64ArgRegs64Bit;
1810
1811         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1812       }
1813       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1814                                                        TotalNumIntRegs);
1815
1816       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1817       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1818              "SSE register cannot be used when SSE is disabled!");
1819       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1820              "SSE register cannot be used when SSE is disabled!");
1821       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1822         // Kernel mode asks for SSE to be disabled, so don't push them
1823         // on the stack.
1824         TotalNumXMMRegs = 0;
1825
1826       if (IsWin64) {
1827         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1828         // Get to the caller-allocated home save location.  Add 8 to account
1829         // for the return address.
1830         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1831         FuncInfo->setRegSaveFrameIndex(
1832           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1833         // Fixup to set vararg frame on shadow area (4 x i64).
1834         if (NumIntRegs < 4)
1835           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1836       } else {
1837         // For X86-64, if there are vararg parameters that are passed via
1838         // registers, then we must store them to their spots on the stack so they
1839         // may be loaded by deferencing the result of va_next.
1840         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1841         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1842         FuncInfo->setRegSaveFrameIndex(
1843           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1844                                false));
1845       }
1846
1847       // Store the integer parameter registers.
1848       SmallVector<SDValue, 8> MemOps;
1849       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1850                                         getPointerTy());
1851       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1852       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1853         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1854                                   DAG.getIntPtrConstant(Offset));
1855         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1856                                      X86::GR64RegisterClass);
1857         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1858         SDValue Store =
1859           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1860                        MachinePointerInfo::getFixedStack(
1861                          FuncInfo->getRegSaveFrameIndex(), Offset),
1862                        false, false, 0);
1863         MemOps.push_back(Store);
1864         Offset += 8;
1865       }
1866
1867       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1868         // Now store the XMM (fp + vector) parameter registers.
1869         SmallVector<SDValue, 11> SaveXMMOps;
1870         SaveXMMOps.push_back(Chain);
1871
1872         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1873         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1874         SaveXMMOps.push_back(ALVal);
1875
1876         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1877                                FuncInfo->getRegSaveFrameIndex()));
1878         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1879                                FuncInfo->getVarArgsFPOffset()));
1880
1881         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1882           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1883                                        X86::VR128RegisterClass);
1884           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1885           SaveXMMOps.push_back(Val);
1886         }
1887         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1888                                      MVT::Other,
1889                                      &SaveXMMOps[0], SaveXMMOps.size()));
1890       }
1891
1892       if (!MemOps.empty())
1893         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1894                             &MemOps[0], MemOps.size());
1895     }
1896   }
1897
1898   // Some CCs need callee pop.
1899   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1900     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1901   } else {
1902     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1903     // If this is an sret function, the return should pop the hidden pointer.
1904     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1905       FuncInfo->setBytesToPopOnReturn(4);
1906   }
1907
1908   if (!Is64Bit) {
1909     // RegSaveFrameIndex is X86-64 only.
1910     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1911     if (CallConv == CallingConv::X86_FastCall ||
1912         CallConv == CallingConv::X86_ThisCall)
1913       // fastcc functions can't have varargs.
1914       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1915   }
1916
1917   return Chain;
1918 }
1919
1920 SDValue
1921 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1922                                     SDValue StackPtr, SDValue Arg,
1923                                     DebugLoc dl, SelectionDAG &DAG,
1924                                     const CCValAssign &VA,
1925                                     ISD::ArgFlagsTy Flags) const {
1926   unsigned LocMemOffset = VA.getLocMemOffset();
1927   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1928   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1929   if (Flags.isByVal())
1930     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1931
1932   return DAG.getStore(Chain, dl, Arg, PtrOff,
1933                       MachinePointerInfo::getStack(LocMemOffset),
1934                       false, false, 0);
1935 }
1936
1937 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1938 /// optimization is performed and it is required.
1939 SDValue
1940 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1941                                            SDValue &OutRetAddr, SDValue Chain,
1942                                            bool IsTailCall, bool Is64Bit,
1943                                            int FPDiff, DebugLoc dl) const {
1944   // Adjust the Return address stack slot.
1945   EVT VT = getPointerTy();
1946   OutRetAddr = getReturnAddressFrameIndex(DAG);
1947
1948   // Load the "old" Return address.
1949   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1950                            false, false, 0);
1951   return SDValue(OutRetAddr.getNode(), 1);
1952 }
1953
1954 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1955 /// optimization is performed and it is required (FPDiff!=0).
1956 static SDValue
1957 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1958                          SDValue Chain, SDValue RetAddrFrIdx,
1959                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1960   // Store the return address to the appropriate stack slot.
1961   if (!FPDiff) return Chain;
1962   // Calculate the new stack slot for the return address.
1963   int SlotSize = Is64Bit ? 8 : 4;
1964   int NewReturnAddrFI =
1965     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1966   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1967   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1968   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1969                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1970                        false, false, 0);
1971   return Chain;
1972 }
1973
1974 SDValue
1975 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1976                              CallingConv::ID CallConv, bool isVarArg,
1977                              bool &isTailCall,
1978                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1979                              const SmallVectorImpl<SDValue> &OutVals,
1980                              const SmallVectorImpl<ISD::InputArg> &Ins,
1981                              DebugLoc dl, SelectionDAG &DAG,
1982                              SmallVectorImpl<SDValue> &InVals) const {
1983   MachineFunction &MF = DAG.getMachineFunction();
1984   bool Is64Bit        = Subtarget->is64Bit();
1985   bool IsWin64        = Subtarget->isTargetWin64();
1986   bool IsStructRet    = CallIsStructReturn(Outs);
1987   bool IsSibcall      = false;
1988
1989   if (isTailCall) {
1990     // Check if it's really possible to do a tail call.
1991     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1992                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1993                                                    Outs, OutVals, Ins, DAG);
1994
1995     // Sibcalls are automatically detected tailcalls which do not require
1996     // ABI changes.
1997     if (!GuaranteedTailCallOpt && isTailCall)
1998       IsSibcall = true;
1999
2000     if (isTailCall)
2001       ++NumTailCalls;
2002   }
2003
2004   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2005          "Var args not supported with calling convention fastcc or ghc");
2006
2007   // Analyze operands of the call, assigning locations to each operand.
2008   SmallVector<CCValAssign, 16> ArgLocs;
2009   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2010                  ArgLocs, *DAG.getContext());
2011
2012   // Allocate shadow area for Win64
2013   if (IsWin64) {
2014     CCInfo.AllocateStack(32, 8);
2015   }
2016
2017   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2018
2019   // Get a count of how many bytes are to be pushed on the stack.
2020   unsigned NumBytes = CCInfo.getNextStackOffset();
2021   if (IsSibcall)
2022     // This is a sibcall. The memory operands are available in caller's
2023     // own caller's stack.
2024     NumBytes = 0;
2025   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2026     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2027
2028   int FPDiff = 0;
2029   if (isTailCall && !IsSibcall) {
2030     // Lower arguments at fp - stackoffset + fpdiff.
2031     unsigned NumBytesCallerPushed =
2032       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2033     FPDiff = NumBytesCallerPushed - NumBytes;
2034
2035     // Set the delta of movement of the returnaddr stackslot.
2036     // But only set if delta is greater than previous delta.
2037     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2038       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2039   }
2040
2041   if (!IsSibcall)
2042     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2043
2044   SDValue RetAddrFrIdx;
2045   // Load return address for tail calls.
2046   if (isTailCall && FPDiff)
2047     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2048                                     Is64Bit, FPDiff, dl);
2049
2050   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2051   SmallVector<SDValue, 8> MemOpChains;
2052   SDValue StackPtr;
2053
2054   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2055   // of tail call optimization arguments are handle later.
2056   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2057     CCValAssign &VA = ArgLocs[i];
2058     EVT RegVT = VA.getLocVT();
2059     SDValue Arg = OutVals[i];
2060     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2061     bool isByVal = Flags.isByVal();
2062
2063     // Promote the value if needed.
2064     switch (VA.getLocInfo()) {
2065     default: llvm_unreachable("Unknown loc info!");
2066     case CCValAssign::Full: break;
2067     case CCValAssign::SExt:
2068       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2069       break;
2070     case CCValAssign::ZExt:
2071       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2072       break;
2073     case CCValAssign::AExt:
2074       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2075         // Special case: passing MMX values in XMM registers.
2076         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2077         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2078         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2079       } else
2080         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2081       break;
2082     case CCValAssign::BCvt:
2083       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2084       break;
2085     case CCValAssign::Indirect: {
2086       // Store the argument.
2087       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2088       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2089       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2090                            MachinePointerInfo::getFixedStack(FI),
2091                            false, false, 0);
2092       Arg = SpillSlot;
2093       break;
2094     }
2095     }
2096
2097     if (VA.isRegLoc()) {
2098       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2099       if (isVarArg && IsWin64) {
2100         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2101         // shadow reg if callee is a varargs function.
2102         unsigned ShadowReg = 0;
2103         switch (VA.getLocReg()) {
2104         case X86::XMM0: ShadowReg = X86::RCX; break;
2105         case X86::XMM1: ShadowReg = X86::RDX; break;
2106         case X86::XMM2: ShadowReg = X86::R8; break;
2107         case X86::XMM3: ShadowReg = X86::R9; break;
2108         }
2109         if (ShadowReg)
2110           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2111       }
2112     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2113       assert(VA.isMemLoc());
2114       if (StackPtr.getNode() == 0)
2115         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2116       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2117                                              dl, DAG, VA, Flags));
2118     }
2119   }
2120
2121   if (!MemOpChains.empty())
2122     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2123                         &MemOpChains[0], MemOpChains.size());
2124
2125   // Build a sequence of copy-to-reg nodes chained together with token chain
2126   // and flag operands which copy the outgoing args into registers.
2127   SDValue InFlag;
2128   // Tail call byval lowering might overwrite argument registers so in case of
2129   // tail call optimization the copies to registers are lowered later.
2130   if (!isTailCall)
2131     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2132       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2133                                RegsToPass[i].second, InFlag);
2134       InFlag = Chain.getValue(1);
2135     }
2136
2137   if (Subtarget->isPICStyleGOT()) {
2138     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2139     // GOT pointer.
2140     if (!isTailCall) {
2141       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2142                                DAG.getNode(X86ISD::GlobalBaseReg,
2143                                            DebugLoc(), getPointerTy()),
2144                                InFlag);
2145       InFlag = Chain.getValue(1);
2146     } else {
2147       // If we are tail calling and generating PIC/GOT style code load the
2148       // address of the callee into ECX. The value in ecx is used as target of
2149       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2150       // for tail calls on PIC/GOT architectures. Normally we would just put the
2151       // address of GOT into ebx and then call target@PLT. But for tail calls
2152       // ebx would be restored (since ebx is callee saved) before jumping to the
2153       // target@PLT.
2154
2155       // Note: The actual moving to ECX is done further down.
2156       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2157       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2158           !G->getGlobal()->hasProtectedVisibility())
2159         Callee = LowerGlobalAddress(Callee, DAG);
2160       else if (isa<ExternalSymbolSDNode>(Callee))
2161         Callee = LowerExternalSymbol(Callee, DAG);
2162     }
2163   }
2164
2165   if (Is64Bit && isVarArg && !IsWin64) {
2166     // From AMD64 ABI document:
2167     // For calls that may call functions that use varargs or stdargs
2168     // (prototype-less calls or calls to functions containing ellipsis (...) in
2169     // the declaration) %al is used as hidden argument to specify the number
2170     // of SSE registers used. The contents of %al do not need to match exactly
2171     // the number of registers, but must be an ubound on the number of SSE
2172     // registers used and is in the range 0 - 8 inclusive.
2173
2174     // Count the number of XMM registers allocated.
2175     static const unsigned XMMArgRegs[] = {
2176       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2177       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2178     };
2179     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2180     assert((Subtarget->hasXMM() || !NumXMMRegs)
2181            && "SSE registers cannot be used when SSE is disabled");
2182
2183     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2184                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2185     InFlag = Chain.getValue(1);
2186   }
2187
2188
2189   // For tail calls lower the arguments to the 'real' stack slot.
2190   if (isTailCall) {
2191     // Force all the incoming stack arguments to be loaded from the stack
2192     // before any new outgoing arguments are stored to the stack, because the
2193     // outgoing stack slots may alias the incoming argument stack slots, and
2194     // the alias isn't otherwise explicit. This is slightly more conservative
2195     // than necessary, because it means that each store effectively depends
2196     // on every argument instead of just those arguments it would clobber.
2197     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2198
2199     SmallVector<SDValue, 8> MemOpChains2;
2200     SDValue FIN;
2201     int FI = 0;
2202     // Do not flag preceding copytoreg stuff together with the following stuff.
2203     InFlag = SDValue();
2204     if (GuaranteedTailCallOpt) {
2205       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2206         CCValAssign &VA = ArgLocs[i];
2207         if (VA.isRegLoc())
2208           continue;
2209         assert(VA.isMemLoc());
2210         SDValue Arg = OutVals[i];
2211         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2212         // Create frame index.
2213         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2214         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2215         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2216         FIN = DAG.getFrameIndex(FI, getPointerTy());
2217
2218         if (Flags.isByVal()) {
2219           // Copy relative to framepointer.
2220           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2221           if (StackPtr.getNode() == 0)
2222             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2223                                           getPointerTy());
2224           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2225
2226           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2227                                                            ArgChain,
2228                                                            Flags, DAG, dl));
2229         } else {
2230           // Store relative to framepointer.
2231           MemOpChains2.push_back(
2232             DAG.getStore(ArgChain, dl, Arg, FIN,
2233                          MachinePointerInfo::getFixedStack(FI),
2234                          false, false, 0));
2235         }
2236       }
2237     }
2238
2239     if (!MemOpChains2.empty())
2240       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2241                           &MemOpChains2[0], MemOpChains2.size());
2242
2243     // Copy arguments to their registers.
2244     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2245       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2246                                RegsToPass[i].second, InFlag);
2247       InFlag = Chain.getValue(1);
2248     }
2249     InFlag =SDValue();
2250
2251     // Store the return address to the appropriate stack slot.
2252     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2253                                      FPDiff, dl);
2254   }
2255
2256   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2257     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2258     // In the 64-bit large code model, we have to make all calls
2259     // through a register, since the call instruction's 32-bit
2260     // pc-relative offset may not be large enough to hold the whole
2261     // address.
2262   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2263     // If the callee is a GlobalAddress node (quite common, every direct call
2264     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2265     // it.
2266
2267     // We should use extra load for direct calls to dllimported functions in
2268     // non-JIT mode.
2269     const GlobalValue *GV = G->getGlobal();
2270     if (!GV->hasDLLImportLinkage()) {
2271       unsigned char OpFlags = 0;
2272
2273       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2274       // external symbols most go through the PLT in PIC mode.  If the symbol
2275       // has hidden or protected visibility, or if it is static or local, then
2276       // we don't need to use the PLT - we can directly call it.
2277       if (Subtarget->isTargetELF() &&
2278           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2279           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2280         OpFlags = X86II::MO_PLT;
2281       } else if (Subtarget->isPICStyleStubAny() &&
2282                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2283                  (!Subtarget->getTargetTriple().isMacOSX() ||
2284                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2285         // PC-relative references to external symbols should go through $stub,
2286         // unless we're building with the leopard linker or later, which
2287         // automatically synthesizes these stubs.
2288         OpFlags = X86II::MO_DARWIN_STUB;
2289       }
2290
2291       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2292                                           G->getOffset(), OpFlags);
2293     }
2294   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2295     unsigned char OpFlags = 0;
2296
2297     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2298     // external symbols should go through the PLT.
2299     if (Subtarget->isTargetELF() &&
2300         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2301       OpFlags = X86II::MO_PLT;
2302     } else if (Subtarget->isPICStyleStubAny() &&
2303                (!Subtarget->getTargetTriple().isMacOSX() ||
2304                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2305       // PC-relative references to external symbols should go through $stub,
2306       // unless we're building with the leopard linker or later, which
2307       // automatically synthesizes these stubs.
2308       OpFlags = X86II::MO_DARWIN_STUB;
2309     }
2310
2311     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2312                                          OpFlags);
2313   }
2314
2315   // Returns a chain & a flag for retval copy to use.
2316   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2317   SmallVector<SDValue, 8> Ops;
2318
2319   if (!IsSibcall && isTailCall) {
2320     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2321                            DAG.getIntPtrConstant(0, true), InFlag);
2322     InFlag = Chain.getValue(1);
2323   }
2324
2325   Ops.push_back(Chain);
2326   Ops.push_back(Callee);
2327
2328   if (isTailCall)
2329     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2330
2331   // Add argument registers to the end of the list so that they are known live
2332   // into the call.
2333   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2334     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2335                                   RegsToPass[i].second.getValueType()));
2336
2337   // Add an implicit use GOT pointer in EBX.
2338   if (!isTailCall && Subtarget->isPICStyleGOT())
2339     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2340
2341   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2342   if (Is64Bit && isVarArg && !IsWin64)
2343     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2344
2345   if (InFlag.getNode())
2346     Ops.push_back(InFlag);
2347
2348   if (isTailCall) {
2349     // We used to do:
2350     //// If this is the first return lowered for this function, add the regs
2351     //// to the liveout set for the function.
2352     // This isn't right, although it's probably harmless on x86; liveouts
2353     // should be computed from returns not tail calls.  Consider a void
2354     // function making a tail call to a function returning int.
2355     return DAG.getNode(X86ISD::TC_RETURN, dl,
2356                        NodeTys, &Ops[0], Ops.size());
2357   }
2358
2359   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2360   InFlag = Chain.getValue(1);
2361
2362   // Create the CALLSEQ_END node.
2363   unsigned NumBytesForCalleeToPush;
2364   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2365     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2366   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2367     // If this is a call to a struct-return function, the callee
2368     // pops the hidden struct pointer, so we have to push it back.
2369     // This is common for Darwin/X86, Linux & Mingw32 targets.
2370     NumBytesForCalleeToPush = 4;
2371   else
2372     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2373
2374   // Returns a flag for retval copy to use.
2375   if (!IsSibcall) {
2376     Chain = DAG.getCALLSEQ_END(Chain,
2377                                DAG.getIntPtrConstant(NumBytes, true),
2378                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2379                                                      true),
2380                                InFlag);
2381     InFlag = Chain.getValue(1);
2382   }
2383
2384   // Handle result values, copying them out of physregs into vregs that we
2385   // return.
2386   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2387                          Ins, dl, DAG, InVals);
2388 }
2389
2390
2391 //===----------------------------------------------------------------------===//
2392 //                Fast Calling Convention (tail call) implementation
2393 //===----------------------------------------------------------------------===//
2394
2395 //  Like std call, callee cleans arguments, convention except that ECX is
2396 //  reserved for storing the tail called function address. Only 2 registers are
2397 //  free for argument passing (inreg). Tail call optimization is performed
2398 //  provided:
2399 //                * tailcallopt is enabled
2400 //                * caller/callee are fastcc
2401 //  On X86_64 architecture with GOT-style position independent code only local
2402 //  (within module) calls are supported at the moment.
2403 //  To keep the stack aligned according to platform abi the function
2404 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2405 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2406 //  If a tail called function callee has more arguments than the caller the
2407 //  caller needs to make sure that there is room to move the RETADDR to. This is
2408 //  achieved by reserving an area the size of the argument delta right after the
2409 //  original REtADDR, but before the saved framepointer or the spilled registers
2410 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2411 //  stack layout:
2412 //    arg1
2413 //    arg2
2414 //    RETADDR
2415 //    [ new RETADDR
2416 //      move area ]
2417 //    (possible EBP)
2418 //    ESI
2419 //    EDI
2420 //    local1 ..
2421
2422 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2423 /// for a 16 byte align requirement.
2424 unsigned
2425 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2426                                                SelectionDAG& DAG) const {
2427   MachineFunction &MF = DAG.getMachineFunction();
2428   const TargetMachine &TM = MF.getTarget();
2429   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2430   unsigned StackAlignment = TFI.getStackAlignment();
2431   uint64_t AlignMask = StackAlignment - 1;
2432   int64_t Offset = StackSize;
2433   uint64_t SlotSize = TD->getPointerSize();
2434   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2435     // Number smaller than 12 so just add the difference.
2436     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2437   } else {
2438     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2439     Offset = ((~AlignMask) & Offset) + StackAlignment +
2440       (StackAlignment-SlotSize);
2441   }
2442   return Offset;
2443 }
2444
2445 /// MatchingStackOffset - Return true if the given stack call argument is
2446 /// already available in the same position (relatively) of the caller's
2447 /// incoming argument stack.
2448 static
2449 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2450                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2451                          const X86InstrInfo *TII) {
2452   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2453   int FI = INT_MAX;
2454   if (Arg.getOpcode() == ISD::CopyFromReg) {
2455     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2456     if (!TargetRegisterInfo::isVirtualRegister(VR))
2457       return false;
2458     MachineInstr *Def = MRI->getVRegDef(VR);
2459     if (!Def)
2460       return false;
2461     if (!Flags.isByVal()) {
2462       if (!TII->isLoadFromStackSlot(Def, FI))
2463         return false;
2464     } else {
2465       unsigned Opcode = Def->getOpcode();
2466       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2467           Def->getOperand(1).isFI()) {
2468         FI = Def->getOperand(1).getIndex();
2469         Bytes = Flags.getByValSize();
2470       } else
2471         return false;
2472     }
2473   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2474     if (Flags.isByVal())
2475       // ByVal argument is passed in as a pointer but it's now being
2476       // dereferenced. e.g.
2477       // define @foo(%struct.X* %A) {
2478       //   tail call @bar(%struct.X* byval %A)
2479       // }
2480       return false;
2481     SDValue Ptr = Ld->getBasePtr();
2482     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2483     if (!FINode)
2484       return false;
2485     FI = FINode->getIndex();
2486   } else
2487     return false;
2488
2489   assert(FI != INT_MAX);
2490   if (!MFI->isFixedObjectIndex(FI))
2491     return false;
2492   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2493 }
2494
2495 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2496 /// for tail call optimization. Targets which want to do tail call
2497 /// optimization should implement this function.
2498 bool
2499 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2500                                                      CallingConv::ID CalleeCC,
2501                                                      bool isVarArg,
2502                                                      bool isCalleeStructRet,
2503                                                      bool isCallerStructRet,
2504                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2505                                     const SmallVectorImpl<SDValue> &OutVals,
2506                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2507                                                      SelectionDAG& DAG) const {
2508   if (!IsTailCallConvention(CalleeCC) &&
2509       CalleeCC != CallingConv::C)
2510     return false;
2511
2512   // If -tailcallopt is specified, make fastcc functions tail-callable.
2513   const MachineFunction &MF = DAG.getMachineFunction();
2514   const Function *CallerF = DAG.getMachineFunction().getFunction();
2515   CallingConv::ID CallerCC = CallerF->getCallingConv();
2516   bool CCMatch = CallerCC == CalleeCC;
2517
2518   if (GuaranteedTailCallOpt) {
2519     if (IsTailCallConvention(CalleeCC) && CCMatch)
2520       return true;
2521     return false;
2522   }
2523
2524   // Look for obvious safe cases to perform tail call optimization that do not
2525   // require ABI changes. This is what gcc calls sibcall.
2526
2527   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2528   // emit a special epilogue.
2529   if (RegInfo->needsStackRealignment(MF))
2530     return false;
2531
2532   // Also avoid sibcall optimization if either caller or callee uses struct
2533   // return semantics.
2534   if (isCalleeStructRet || isCallerStructRet)
2535     return false;
2536
2537   // Do not sibcall optimize vararg calls unless all arguments are passed via
2538   // registers.
2539   if (isVarArg && !Outs.empty()) {
2540
2541     // Optimizing for varargs on Win64 is unlikely to be safe without
2542     // additional testing.
2543     if (Subtarget->isTargetWin64())
2544       return false;
2545
2546     SmallVector<CCValAssign, 16> ArgLocs;
2547     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2548                    ArgLocs, *DAG.getContext());
2549
2550     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2551     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2552       if (!ArgLocs[i].isRegLoc())
2553         return false;
2554   }
2555
2556   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2557   // Therefore if it's not used by the call it is not safe to optimize this into
2558   // a sibcall.
2559   bool Unused = false;
2560   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2561     if (!Ins[i].Used) {
2562       Unused = true;
2563       break;
2564     }
2565   }
2566   if (Unused) {
2567     SmallVector<CCValAssign, 16> RVLocs;
2568     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2569                    RVLocs, *DAG.getContext());
2570     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2571     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2572       CCValAssign &VA = RVLocs[i];
2573       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2574         return false;
2575     }
2576   }
2577
2578   // If the calling conventions do not match, then we'd better make sure the
2579   // results are returned in the same way as what the caller expects.
2580   if (!CCMatch) {
2581     SmallVector<CCValAssign, 16> RVLocs1;
2582     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2583                     RVLocs1, *DAG.getContext());
2584     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2585
2586     SmallVector<CCValAssign, 16> RVLocs2;
2587     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2588                     RVLocs2, *DAG.getContext());
2589     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2590
2591     if (RVLocs1.size() != RVLocs2.size())
2592       return false;
2593     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2594       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2595         return false;
2596       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2597         return false;
2598       if (RVLocs1[i].isRegLoc()) {
2599         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2600           return false;
2601       } else {
2602         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2603           return false;
2604       }
2605     }
2606   }
2607
2608   // If the callee takes no arguments then go on to check the results of the
2609   // call.
2610   if (!Outs.empty()) {
2611     // Check if stack adjustment is needed. For now, do not do this if any
2612     // argument is passed on the stack.
2613     SmallVector<CCValAssign, 16> ArgLocs;
2614     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2615                    ArgLocs, *DAG.getContext());
2616
2617     // Allocate shadow area for Win64
2618     if (Subtarget->isTargetWin64()) {
2619       CCInfo.AllocateStack(32, 8);
2620     }
2621
2622     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2623     if (CCInfo.getNextStackOffset()) {
2624       MachineFunction &MF = DAG.getMachineFunction();
2625       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2626         return false;
2627
2628       // Check if the arguments are already laid out in the right way as
2629       // the caller's fixed stack objects.
2630       MachineFrameInfo *MFI = MF.getFrameInfo();
2631       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2632       const X86InstrInfo *TII =
2633         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2634       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2635         CCValAssign &VA = ArgLocs[i];
2636         SDValue Arg = OutVals[i];
2637         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2638         if (VA.getLocInfo() == CCValAssign::Indirect)
2639           return false;
2640         if (!VA.isRegLoc()) {
2641           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2642                                    MFI, MRI, TII))
2643             return false;
2644         }
2645       }
2646     }
2647
2648     // If the tailcall address may be in a register, then make sure it's
2649     // possible to register allocate for it. In 32-bit, the call address can
2650     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2651     // callee-saved registers are restored. These happen to be the same
2652     // registers used to pass 'inreg' arguments so watch out for those.
2653     if (!Subtarget->is64Bit() &&
2654         !isa<GlobalAddressSDNode>(Callee) &&
2655         !isa<ExternalSymbolSDNode>(Callee)) {
2656       unsigned NumInRegs = 0;
2657       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2658         CCValAssign &VA = ArgLocs[i];
2659         if (!VA.isRegLoc())
2660           continue;
2661         unsigned Reg = VA.getLocReg();
2662         switch (Reg) {
2663         default: break;
2664         case X86::EAX: case X86::EDX: case X86::ECX:
2665           if (++NumInRegs == 3)
2666             return false;
2667           break;
2668         }
2669       }
2670     }
2671   }
2672
2673   // An stdcall caller is expected to clean up its arguments; the callee
2674   // isn't going to do that.
2675   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2676     return false;
2677
2678   return true;
2679 }
2680
2681 FastISel *
2682 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2683   return X86::createFastISel(funcInfo);
2684 }
2685
2686
2687 //===----------------------------------------------------------------------===//
2688 //                           Other Lowering Hooks
2689 //===----------------------------------------------------------------------===//
2690
2691 static bool MayFoldLoad(SDValue Op) {
2692   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2693 }
2694
2695 static bool MayFoldIntoStore(SDValue Op) {
2696   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2697 }
2698
2699 static bool isTargetShuffle(unsigned Opcode) {
2700   switch(Opcode) {
2701   default: return false;
2702   case X86ISD::PSHUFD:
2703   case X86ISD::PSHUFHW:
2704   case X86ISD::PSHUFLW:
2705   case X86ISD::SHUFPD:
2706   case X86ISD::PALIGN:
2707   case X86ISD::SHUFPS:
2708   case X86ISD::MOVLHPS:
2709   case X86ISD::MOVLHPD:
2710   case X86ISD::MOVHLPS:
2711   case X86ISD::MOVLPS:
2712   case X86ISD::MOVLPD:
2713   case X86ISD::MOVSHDUP:
2714   case X86ISD::MOVSLDUP:
2715   case X86ISD::MOVDDUP:
2716   case X86ISD::MOVSS:
2717   case X86ISD::MOVSD:
2718   case X86ISD::UNPCKLPS:
2719   case X86ISD::UNPCKLPD:
2720   case X86ISD::VUNPCKLPS:
2721   case X86ISD::VUNPCKLPD:
2722   case X86ISD::VUNPCKLPSY:
2723   case X86ISD::VUNPCKLPDY:
2724   case X86ISD::PUNPCKLWD:
2725   case X86ISD::PUNPCKLBW:
2726   case X86ISD::PUNPCKLDQ:
2727   case X86ISD::PUNPCKLQDQ:
2728   case X86ISD::UNPCKHPS:
2729   case X86ISD::UNPCKHPD:
2730   case X86ISD::PUNPCKHWD:
2731   case X86ISD::PUNPCKHBW:
2732   case X86ISD::PUNPCKHDQ:
2733   case X86ISD::PUNPCKHQDQ:
2734     return true;
2735   }
2736   return false;
2737 }
2738
2739 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2740                                                SDValue V1, SelectionDAG &DAG) {
2741   switch(Opc) {
2742   default: llvm_unreachable("Unknown x86 shuffle node");
2743   case X86ISD::MOVSHDUP:
2744   case X86ISD::MOVSLDUP:
2745   case X86ISD::MOVDDUP:
2746     return DAG.getNode(Opc, dl, VT, V1);
2747   }
2748
2749   return SDValue();
2750 }
2751
2752 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2753                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2754   switch(Opc) {
2755   default: llvm_unreachable("Unknown x86 shuffle node");
2756   case X86ISD::PSHUFD:
2757   case X86ISD::PSHUFHW:
2758   case X86ISD::PSHUFLW:
2759     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2760   }
2761
2762   return SDValue();
2763 }
2764
2765 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2766                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2767   switch(Opc) {
2768   default: llvm_unreachable("Unknown x86 shuffle node");
2769   case X86ISD::PALIGN:
2770   case X86ISD::SHUFPD:
2771   case X86ISD::SHUFPS:
2772     return DAG.getNode(Opc, dl, VT, V1, V2,
2773                        DAG.getConstant(TargetMask, MVT::i8));
2774   }
2775   return SDValue();
2776 }
2777
2778 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2779                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2780   switch(Opc) {
2781   default: llvm_unreachable("Unknown x86 shuffle node");
2782   case X86ISD::MOVLHPS:
2783   case X86ISD::MOVLHPD:
2784   case X86ISD::MOVHLPS:
2785   case X86ISD::MOVLPS:
2786   case X86ISD::MOVLPD:
2787   case X86ISD::MOVSS:
2788   case X86ISD::MOVSD:
2789   case X86ISD::UNPCKLPS:
2790   case X86ISD::UNPCKLPD:
2791   case X86ISD::VUNPCKLPS:
2792   case X86ISD::VUNPCKLPD:
2793   case X86ISD::VUNPCKLPSY:
2794   case X86ISD::VUNPCKLPDY:
2795   case X86ISD::PUNPCKLWD:
2796   case X86ISD::PUNPCKLBW:
2797   case X86ISD::PUNPCKLDQ:
2798   case X86ISD::PUNPCKLQDQ:
2799   case X86ISD::UNPCKHPS:
2800   case X86ISD::UNPCKHPD:
2801   case X86ISD::PUNPCKHWD:
2802   case X86ISD::PUNPCKHBW:
2803   case X86ISD::PUNPCKHDQ:
2804   case X86ISD::PUNPCKHQDQ:
2805     return DAG.getNode(Opc, dl, VT, V1, V2);
2806   }
2807   return SDValue();
2808 }
2809
2810 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2811   MachineFunction &MF = DAG.getMachineFunction();
2812   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2813   int ReturnAddrIndex = FuncInfo->getRAIndex();
2814
2815   if (ReturnAddrIndex == 0) {
2816     // Set up a frame object for the return address.
2817     uint64_t SlotSize = TD->getPointerSize();
2818     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2819                                                            false);
2820     FuncInfo->setRAIndex(ReturnAddrIndex);
2821   }
2822
2823   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2824 }
2825
2826
2827 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2828                                        bool hasSymbolicDisplacement) {
2829   // Offset should fit into 32 bit immediate field.
2830   if (!isInt<32>(Offset))
2831     return false;
2832
2833   // If we don't have a symbolic displacement - we don't have any extra
2834   // restrictions.
2835   if (!hasSymbolicDisplacement)
2836     return true;
2837
2838   // FIXME: Some tweaks might be needed for medium code model.
2839   if (M != CodeModel::Small && M != CodeModel::Kernel)
2840     return false;
2841
2842   // For small code model we assume that latest object is 16MB before end of 31
2843   // bits boundary. We may also accept pretty large negative constants knowing
2844   // that all objects are in the positive half of address space.
2845   if (M == CodeModel::Small && Offset < 16*1024*1024)
2846     return true;
2847
2848   // For kernel code model we know that all object resist in the negative half
2849   // of 32bits address space. We may not accept negative offsets, since they may
2850   // be just off and we may accept pretty large positive ones.
2851   if (M == CodeModel::Kernel && Offset > 0)
2852     return true;
2853
2854   return false;
2855 }
2856
2857 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2858 /// specific condition code, returning the condition code and the LHS/RHS of the
2859 /// comparison to make.
2860 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2861                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2862   if (!isFP) {
2863     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2864       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2865         // X > -1   -> X == 0, jump !sign.
2866         RHS = DAG.getConstant(0, RHS.getValueType());
2867         return X86::COND_NS;
2868       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2869         // X < 0   -> X == 0, jump on sign.
2870         return X86::COND_S;
2871       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2872         // X < 1   -> X <= 0
2873         RHS = DAG.getConstant(0, RHS.getValueType());
2874         return X86::COND_LE;
2875       }
2876     }
2877
2878     switch (SetCCOpcode) {
2879     default: llvm_unreachable("Invalid integer condition!");
2880     case ISD::SETEQ:  return X86::COND_E;
2881     case ISD::SETGT:  return X86::COND_G;
2882     case ISD::SETGE:  return X86::COND_GE;
2883     case ISD::SETLT:  return X86::COND_L;
2884     case ISD::SETLE:  return X86::COND_LE;
2885     case ISD::SETNE:  return X86::COND_NE;
2886     case ISD::SETULT: return X86::COND_B;
2887     case ISD::SETUGT: return X86::COND_A;
2888     case ISD::SETULE: return X86::COND_BE;
2889     case ISD::SETUGE: return X86::COND_AE;
2890     }
2891   }
2892
2893   // First determine if it is required or is profitable to flip the operands.
2894
2895   // If LHS is a foldable load, but RHS is not, flip the condition.
2896   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2897       !ISD::isNON_EXTLoad(RHS.getNode())) {
2898     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2899     std::swap(LHS, RHS);
2900   }
2901
2902   switch (SetCCOpcode) {
2903   default: break;
2904   case ISD::SETOLT:
2905   case ISD::SETOLE:
2906   case ISD::SETUGT:
2907   case ISD::SETUGE:
2908     std::swap(LHS, RHS);
2909     break;
2910   }
2911
2912   // On a floating point condition, the flags are set as follows:
2913   // ZF  PF  CF   op
2914   //  0 | 0 | 0 | X > Y
2915   //  0 | 0 | 1 | X < Y
2916   //  1 | 0 | 0 | X == Y
2917   //  1 | 1 | 1 | unordered
2918   switch (SetCCOpcode) {
2919   default: llvm_unreachable("Condcode should be pre-legalized away");
2920   case ISD::SETUEQ:
2921   case ISD::SETEQ:   return X86::COND_E;
2922   case ISD::SETOLT:              // flipped
2923   case ISD::SETOGT:
2924   case ISD::SETGT:   return X86::COND_A;
2925   case ISD::SETOLE:              // flipped
2926   case ISD::SETOGE:
2927   case ISD::SETGE:   return X86::COND_AE;
2928   case ISD::SETUGT:              // flipped
2929   case ISD::SETULT:
2930   case ISD::SETLT:   return X86::COND_B;
2931   case ISD::SETUGE:              // flipped
2932   case ISD::SETULE:
2933   case ISD::SETLE:   return X86::COND_BE;
2934   case ISD::SETONE:
2935   case ISD::SETNE:   return X86::COND_NE;
2936   case ISD::SETUO:   return X86::COND_P;
2937   case ISD::SETO:    return X86::COND_NP;
2938   case ISD::SETOEQ:
2939   case ISD::SETUNE:  return X86::COND_INVALID;
2940   }
2941 }
2942
2943 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2944 /// code. Current x86 isa includes the following FP cmov instructions:
2945 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2946 static bool hasFPCMov(unsigned X86CC) {
2947   switch (X86CC) {
2948   default:
2949     return false;
2950   case X86::COND_B:
2951   case X86::COND_BE:
2952   case X86::COND_E:
2953   case X86::COND_P:
2954   case X86::COND_A:
2955   case X86::COND_AE:
2956   case X86::COND_NE:
2957   case X86::COND_NP:
2958     return true;
2959   }
2960 }
2961
2962 /// isFPImmLegal - Returns true if the target can instruction select the
2963 /// specified FP immediate natively. If false, the legalizer will
2964 /// materialize the FP immediate as a load from a constant pool.
2965 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2966   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2967     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2968       return true;
2969   }
2970   return false;
2971 }
2972
2973 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2974 /// the specified range (L, H].
2975 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2976   return (Val < 0) || (Val >= Low && Val < Hi);
2977 }
2978
2979 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2980 /// specified value.
2981 static bool isUndefOrEqual(int Val, int CmpVal) {
2982   if (Val < 0 || Val == CmpVal)
2983     return true;
2984   return false;
2985 }
2986
2987 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2988 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2989 /// the second operand.
2990 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2991   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2992     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2993   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2994     return (Mask[0] < 2 && Mask[1] < 2);
2995   return false;
2996 }
2997
2998 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2999   SmallVector<int, 8> M;
3000   N->getMask(M);
3001   return ::isPSHUFDMask(M, N->getValueType(0));
3002 }
3003
3004 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3005 /// is suitable for input to PSHUFHW.
3006 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3007   if (VT != MVT::v8i16)
3008     return false;
3009
3010   // Lower quadword copied in order or undef.
3011   for (int i = 0; i != 4; ++i)
3012     if (Mask[i] >= 0 && Mask[i] != i)
3013       return false;
3014
3015   // Upper quadword shuffled.
3016   for (int i = 4; i != 8; ++i)
3017     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3018       return false;
3019
3020   return true;
3021 }
3022
3023 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3024   SmallVector<int, 8> M;
3025   N->getMask(M);
3026   return ::isPSHUFHWMask(M, N->getValueType(0));
3027 }
3028
3029 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3030 /// is suitable for input to PSHUFLW.
3031 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3032   if (VT != MVT::v8i16)
3033     return false;
3034
3035   // Upper quadword copied in order.
3036   for (int i = 4; i != 8; ++i)
3037     if (Mask[i] >= 0 && Mask[i] != i)
3038       return false;
3039
3040   // Lower quadword shuffled.
3041   for (int i = 0; i != 4; ++i)
3042     if (Mask[i] >= 4)
3043       return false;
3044
3045   return true;
3046 }
3047
3048 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3049   SmallVector<int, 8> M;
3050   N->getMask(M);
3051   return ::isPSHUFLWMask(M, N->getValueType(0));
3052 }
3053
3054 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3055 /// is suitable for input to PALIGNR.
3056 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3057                           bool hasSSSE3) {
3058   int i, e = VT.getVectorNumElements();
3059
3060   // Do not handle v2i64 / v2f64 shuffles with palignr.
3061   if (e < 4 || !hasSSSE3)
3062     return false;
3063
3064   for (i = 0; i != e; ++i)
3065     if (Mask[i] >= 0)
3066       break;
3067
3068   // All undef, not a palignr.
3069   if (i == e)
3070     return false;
3071
3072   // Determine if it's ok to perform a palignr with only the LHS, since we
3073   // don't have access to the actual shuffle elements to see if RHS is undef.
3074   bool Unary = Mask[i] < (int)e;
3075   bool NeedsUnary = false;
3076
3077   int s = Mask[i] - i;
3078
3079   // Check the rest of the elements to see if they are consecutive.
3080   for (++i; i != e; ++i) {
3081     int m = Mask[i];
3082     if (m < 0)
3083       continue;
3084
3085     Unary = Unary && (m < (int)e);
3086     NeedsUnary = NeedsUnary || (m < s);
3087
3088     if (NeedsUnary && !Unary)
3089       return false;
3090     if (Unary && m != ((s+i) & (e-1)))
3091       return false;
3092     if (!Unary && m != (s+i))
3093       return false;
3094   }
3095   return true;
3096 }
3097
3098 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3099   SmallVector<int, 8> M;
3100   N->getMask(M);
3101   return ::isPALIGNRMask(M, N->getValueType(0), true);
3102 }
3103
3104 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3105 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3106 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3107   int NumElems = VT.getVectorNumElements();
3108   if (NumElems != 2 && NumElems != 4)
3109     return false;
3110
3111   int Half = NumElems / 2;
3112   for (int i = 0; i < Half; ++i)
3113     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3114       return false;
3115   for (int i = Half; i < NumElems; ++i)
3116     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3117       return false;
3118
3119   return true;
3120 }
3121
3122 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3123   SmallVector<int, 8> M;
3124   N->getMask(M);
3125   return ::isSHUFPMask(M, N->getValueType(0));
3126 }
3127
3128 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3129 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3130 /// half elements to come from vector 1 (which would equal the dest.) and
3131 /// the upper half to come from vector 2.
3132 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3133   int NumElems = VT.getVectorNumElements();
3134
3135   if (NumElems != 2 && NumElems != 4)
3136     return false;
3137
3138   int Half = NumElems / 2;
3139   for (int i = 0; i < Half; ++i)
3140     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3141       return false;
3142   for (int i = Half; i < NumElems; ++i)
3143     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3144       return false;
3145   return true;
3146 }
3147
3148 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3149   SmallVector<int, 8> M;
3150   N->getMask(M);
3151   return isCommutedSHUFPMask(M, N->getValueType(0));
3152 }
3153
3154 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3155 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3156 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3157   if (N->getValueType(0).getVectorNumElements() != 4)
3158     return false;
3159
3160   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3161   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3162          isUndefOrEqual(N->getMaskElt(1), 7) &&
3163          isUndefOrEqual(N->getMaskElt(2), 2) &&
3164          isUndefOrEqual(N->getMaskElt(3), 3);
3165 }
3166
3167 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3168 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3169 /// <2, 3, 2, 3>
3170 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3171   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3172
3173   if (NumElems != 4)
3174     return false;
3175
3176   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3177   isUndefOrEqual(N->getMaskElt(1), 3) &&
3178   isUndefOrEqual(N->getMaskElt(2), 2) &&
3179   isUndefOrEqual(N->getMaskElt(3), 3);
3180 }
3181
3182 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3183 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3184 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3185   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3186
3187   if (NumElems != 2 && NumElems != 4)
3188     return false;
3189
3190   for (unsigned i = 0; i < NumElems/2; ++i)
3191     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3192       return false;
3193
3194   for (unsigned i = NumElems/2; i < NumElems; ++i)
3195     if (!isUndefOrEqual(N->getMaskElt(i), i))
3196       return false;
3197
3198   return true;
3199 }
3200
3201 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3202 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3203 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3204   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3205
3206   if ((NumElems != 2 && NumElems != 4)
3207       || N->getValueType(0).getSizeInBits() > 128)
3208     return false;
3209
3210   for (unsigned i = 0; i < NumElems/2; ++i)
3211     if (!isUndefOrEqual(N->getMaskElt(i), i))
3212       return false;
3213
3214   for (unsigned i = 0; i < NumElems/2; ++i)
3215     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3216       return false;
3217
3218   return true;
3219 }
3220
3221 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3222 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3223 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3224                          bool V2IsSplat = false) {
3225   int NumElts = VT.getVectorNumElements();
3226   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3227     return false;
3228
3229   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3230   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3231   // sections.
3232   unsigned NumSections = VT.getSizeInBits() / 128;
3233   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3234   unsigned NumSectionElts = NumElts / NumSections;
3235
3236   unsigned Start = 0;
3237   unsigned End = NumSectionElts;
3238   for (unsigned s = 0; s < NumSections; ++s) {
3239     for (unsigned i = Start, j = s * NumSectionElts;
3240          i != End;
3241          i += 2, ++j) {
3242       int BitI  = Mask[i];
3243       int BitI1 = Mask[i+1];
3244       if (!isUndefOrEqual(BitI, j))
3245         return false;
3246       if (V2IsSplat) {
3247         if (!isUndefOrEqual(BitI1, NumElts))
3248           return false;
3249       } else {
3250         if (!isUndefOrEqual(BitI1, j + NumElts))
3251           return false;
3252       }
3253     }
3254     // Process the next 128 bits.
3255     Start += NumSectionElts;
3256     End += NumSectionElts;
3257   }
3258
3259   return true;
3260 }
3261
3262 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3263   SmallVector<int, 8> M;
3264   N->getMask(M);
3265   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3266 }
3267
3268 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3269 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3270 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3271                          bool V2IsSplat = false) {
3272   int NumElts = VT.getVectorNumElements();
3273   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3274     return false;
3275
3276   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3277     int BitI  = Mask[i];
3278     int BitI1 = Mask[i+1];
3279     if (!isUndefOrEqual(BitI, j + NumElts/2))
3280       return false;
3281     if (V2IsSplat) {
3282       if (isUndefOrEqual(BitI1, NumElts))
3283         return false;
3284     } else {
3285       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3286         return false;
3287     }
3288   }
3289   return true;
3290 }
3291
3292 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3293   SmallVector<int, 8> M;
3294   N->getMask(M);
3295   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3296 }
3297
3298 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3299 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3300 /// <0, 0, 1, 1>
3301 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3302   int NumElems = VT.getVectorNumElements();
3303   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3304     return false;
3305
3306   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3307   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3308   // sections.
3309   unsigned NumSections = VT.getSizeInBits() / 128;
3310   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3311   unsigned NumSectionElts = NumElems / NumSections;
3312
3313   for (unsigned s = 0; s < NumSections; ++s) {
3314     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3315          i != NumSectionElts * (s + 1);
3316          i += 2, ++j) {
3317       int BitI  = Mask[i];
3318       int BitI1 = Mask[i+1];
3319
3320       if (!isUndefOrEqual(BitI, j))
3321         return false;
3322       if (!isUndefOrEqual(BitI1, j))
3323         return false;
3324     }
3325   }
3326
3327   return true;
3328 }
3329
3330 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3331   SmallVector<int, 8> M;
3332   N->getMask(M);
3333   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3334 }
3335
3336 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3337 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3338 /// <2, 2, 3, 3>
3339 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3340   int NumElems = VT.getVectorNumElements();
3341   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3342     return false;
3343
3344   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3345     int BitI  = Mask[i];
3346     int BitI1 = Mask[i+1];
3347     if (!isUndefOrEqual(BitI, j))
3348       return false;
3349     if (!isUndefOrEqual(BitI1, j))
3350       return false;
3351   }
3352   return true;
3353 }
3354
3355 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3356   SmallVector<int, 8> M;
3357   N->getMask(M);
3358   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3359 }
3360
3361 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3362 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3363 /// MOVSD, and MOVD, i.e. setting the lowest element.
3364 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3365   if (VT.getVectorElementType().getSizeInBits() < 32)
3366     return false;
3367
3368   int NumElts = VT.getVectorNumElements();
3369
3370   if (!isUndefOrEqual(Mask[0], NumElts))
3371     return false;
3372
3373   for (int i = 1; i < NumElts; ++i)
3374     if (!isUndefOrEqual(Mask[i], i))
3375       return false;
3376
3377   return true;
3378 }
3379
3380 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3381   SmallVector<int, 8> M;
3382   N->getMask(M);
3383   return ::isMOVLMask(M, N->getValueType(0));
3384 }
3385
3386 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3387 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3388 /// element of vector 2 and the other elements to come from vector 1 in order.
3389 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3390                                bool V2IsSplat = false, bool V2IsUndef = false) {
3391   int NumOps = VT.getVectorNumElements();
3392   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3393     return false;
3394
3395   if (!isUndefOrEqual(Mask[0], 0))
3396     return false;
3397
3398   for (int i = 1; i < NumOps; ++i)
3399     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3400           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3401           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3402       return false;
3403
3404   return true;
3405 }
3406
3407 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3408                            bool V2IsUndef = false) {
3409   SmallVector<int, 8> M;
3410   N->getMask(M);
3411   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3412 }
3413
3414 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3415 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3416 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3417   if (N->getValueType(0).getVectorNumElements() != 4)
3418     return false;
3419
3420   // Expect 1, 1, 3, 3
3421   for (unsigned i = 0; i < 2; ++i) {
3422     int Elt = N->getMaskElt(i);
3423     if (Elt >= 0 && Elt != 1)
3424       return false;
3425   }
3426
3427   bool HasHi = false;
3428   for (unsigned i = 2; i < 4; ++i) {
3429     int Elt = N->getMaskElt(i);
3430     if (Elt >= 0 && Elt != 3)
3431       return false;
3432     if (Elt == 3)
3433       HasHi = true;
3434   }
3435   // Don't use movshdup if it can be done with a shufps.
3436   // FIXME: verify that matching u, u, 3, 3 is what we want.
3437   return HasHi;
3438 }
3439
3440 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3442 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3443   if (N->getValueType(0).getVectorNumElements() != 4)
3444     return false;
3445
3446   // Expect 0, 0, 2, 2
3447   for (unsigned i = 0; i < 2; ++i)
3448     if (N->getMaskElt(i) > 0)
3449       return false;
3450
3451   bool HasHi = false;
3452   for (unsigned i = 2; i < 4; ++i) {
3453     int Elt = N->getMaskElt(i);
3454     if (Elt >= 0 && Elt != 2)
3455       return false;
3456     if (Elt == 2)
3457       HasHi = true;
3458   }
3459   // Don't use movsldup if it can be done with a shufps.
3460   return HasHi;
3461 }
3462
3463 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3464 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3465 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3466   int e = N->getValueType(0).getVectorNumElements() / 2;
3467
3468   for (int i = 0; i < e; ++i)
3469     if (!isUndefOrEqual(N->getMaskElt(i), i))
3470       return false;
3471   for (int i = 0; i < e; ++i)
3472     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3473       return false;
3474   return true;
3475 }
3476
3477 /// isVEXTRACTF128Index - Return true if the specified
3478 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3479 /// suitable for input to VEXTRACTF128.
3480 bool X86::isVEXTRACTF128Index(SDNode *N) {
3481   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3482     return false;
3483
3484   // The index should be aligned on a 128-bit boundary.
3485   uint64_t Index =
3486     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3487
3488   unsigned VL = N->getValueType(0).getVectorNumElements();
3489   unsigned VBits = N->getValueType(0).getSizeInBits();
3490   unsigned ElSize = VBits / VL;
3491   bool Result = (Index * ElSize) % 128 == 0;
3492
3493   return Result;
3494 }
3495
3496 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3497 /// operand specifies a subvector insert that is suitable for input to
3498 /// VINSERTF128.
3499 bool X86::isVINSERTF128Index(SDNode *N) {
3500   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3501     return false;
3502
3503   // The index should be aligned on a 128-bit boundary.
3504   uint64_t Index =
3505     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3506
3507   unsigned VL = N->getValueType(0).getVectorNumElements();
3508   unsigned VBits = N->getValueType(0).getSizeInBits();
3509   unsigned ElSize = VBits / VL;
3510   bool Result = (Index * ElSize) % 128 == 0;
3511
3512   return Result;
3513 }
3514
3515 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3516 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3517 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3518   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3519   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3520
3521   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3522   unsigned Mask = 0;
3523   for (int i = 0; i < NumOperands; ++i) {
3524     int Val = SVOp->getMaskElt(NumOperands-i-1);
3525     if (Val < 0) Val = 0;
3526     if (Val >= NumOperands) Val -= NumOperands;
3527     Mask |= Val;
3528     if (i != NumOperands - 1)
3529       Mask <<= Shift;
3530   }
3531   return Mask;
3532 }
3533
3534 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3535 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3536 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3537   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3538   unsigned Mask = 0;
3539   // 8 nodes, but we only care about the last 4.
3540   for (unsigned i = 7; i >= 4; --i) {
3541     int Val = SVOp->getMaskElt(i);
3542     if (Val >= 0)
3543       Mask |= (Val - 4);
3544     if (i != 4)
3545       Mask <<= 2;
3546   }
3547   return Mask;
3548 }
3549
3550 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3551 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3552 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3553   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3554   unsigned Mask = 0;
3555   // 8 nodes, but we only care about the first 4.
3556   for (int i = 3; i >= 0; --i) {
3557     int Val = SVOp->getMaskElt(i);
3558     if (Val >= 0)
3559       Mask |= Val;
3560     if (i != 0)
3561       Mask <<= 2;
3562   }
3563   return Mask;
3564 }
3565
3566 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3567 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3568 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3569   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3570   EVT VVT = N->getValueType(0);
3571   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3572   int Val = 0;
3573
3574   unsigned i, e;
3575   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3576     Val = SVOp->getMaskElt(i);
3577     if (Val >= 0)
3578       break;
3579   }
3580   return (Val - i) * EltSize;
3581 }
3582
3583 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3584 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3585 /// instructions.
3586 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3587   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3588     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3589
3590   uint64_t Index =
3591     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3592
3593   EVT VecVT = N->getOperand(0).getValueType();
3594   EVT ElVT = VecVT.getVectorElementType();
3595
3596   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3597
3598   return Index / NumElemsPerChunk;
3599 }
3600
3601 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3602 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3603 /// instructions.
3604 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3605   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3606     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3607
3608   uint64_t Index =
3609     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3610
3611   EVT VecVT = N->getValueType(0);
3612   EVT ElVT = VecVT.getVectorElementType();
3613
3614   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3615
3616   return Index / NumElemsPerChunk;
3617 }
3618
3619 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3620 /// constant +0.0.
3621 bool X86::isZeroNode(SDValue Elt) {
3622   return ((isa<ConstantSDNode>(Elt) &&
3623            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3624           (isa<ConstantFPSDNode>(Elt) &&
3625            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3626 }
3627
3628 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3629 /// their permute mask.
3630 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3631                                     SelectionDAG &DAG) {
3632   EVT VT = SVOp->getValueType(0);
3633   unsigned NumElems = VT.getVectorNumElements();
3634   SmallVector<int, 8> MaskVec;
3635
3636   for (unsigned i = 0; i != NumElems; ++i) {
3637     int idx = SVOp->getMaskElt(i);
3638     if (idx < 0)
3639       MaskVec.push_back(idx);
3640     else if (idx < (int)NumElems)
3641       MaskVec.push_back(idx + NumElems);
3642     else
3643       MaskVec.push_back(idx - NumElems);
3644   }
3645   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3646                               SVOp->getOperand(0), &MaskVec[0]);
3647 }
3648
3649 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3650 /// the two vector operands have swapped position.
3651 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3652   unsigned NumElems = VT.getVectorNumElements();
3653   for (unsigned i = 0; i != NumElems; ++i) {
3654     int idx = Mask[i];
3655     if (idx < 0)
3656       continue;
3657     else if (idx < (int)NumElems)
3658       Mask[i] = idx + NumElems;
3659     else
3660       Mask[i] = idx - NumElems;
3661   }
3662 }
3663
3664 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3665 /// match movhlps. The lower half elements should come from upper half of
3666 /// V1 (and in order), and the upper half elements should come from the upper
3667 /// half of V2 (and in order).
3668 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3669   if (Op->getValueType(0).getVectorNumElements() != 4)
3670     return false;
3671   for (unsigned i = 0, e = 2; i != e; ++i)
3672     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3673       return false;
3674   for (unsigned i = 2; i != 4; ++i)
3675     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3676       return false;
3677   return true;
3678 }
3679
3680 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3681 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3682 /// required.
3683 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3684   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3685     return false;
3686   N = N->getOperand(0).getNode();
3687   if (!ISD::isNON_EXTLoad(N))
3688     return false;
3689   if (LD)
3690     *LD = cast<LoadSDNode>(N);
3691   return true;
3692 }
3693
3694 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3695 /// match movlp{s|d}. The lower half elements should come from lower half of
3696 /// V1 (and in order), and the upper half elements should come from the upper
3697 /// half of V2 (and in order). And since V1 will become the source of the
3698 /// MOVLP, it must be either a vector load or a scalar load to vector.
3699 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3700                                ShuffleVectorSDNode *Op) {
3701   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3702     return false;
3703   // Is V2 is a vector load, don't do this transformation. We will try to use
3704   // load folding shufps op.
3705   if (ISD::isNON_EXTLoad(V2))
3706     return false;
3707
3708   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3709
3710   if (NumElems != 2 && NumElems != 4)
3711     return false;
3712   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3713     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3714       return false;
3715   for (unsigned i = NumElems/2; i != NumElems; ++i)
3716     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3717       return false;
3718   return true;
3719 }
3720
3721 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3722 /// all the same.
3723 static bool isSplatVector(SDNode *N) {
3724   if (N->getOpcode() != ISD::BUILD_VECTOR)
3725     return false;
3726
3727   SDValue SplatValue = N->getOperand(0);
3728   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3729     if (N->getOperand(i) != SplatValue)
3730       return false;
3731   return true;
3732 }
3733
3734 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3735 /// to an zero vector.
3736 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3737 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3738   SDValue V1 = N->getOperand(0);
3739   SDValue V2 = N->getOperand(1);
3740   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3741   for (unsigned i = 0; i != NumElems; ++i) {
3742     int Idx = N->getMaskElt(i);
3743     if (Idx >= (int)NumElems) {
3744       unsigned Opc = V2.getOpcode();
3745       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3746         continue;
3747       if (Opc != ISD::BUILD_VECTOR ||
3748           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3749         return false;
3750     } else if (Idx >= 0) {
3751       unsigned Opc = V1.getOpcode();
3752       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3753         continue;
3754       if (Opc != ISD::BUILD_VECTOR ||
3755           !X86::isZeroNode(V1.getOperand(Idx)))
3756         return false;
3757     }
3758   }
3759   return true;
3760 }
3761
3762 /// getZeroVector - Returns a vector of specified type with all zero elements.
3763 ///
3764 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3765                              DebugLoc dl) {
3766   assert(VT.isVector() && "Expected a vector type");
3767
3768   // Always build SSE zero vectors as <4 x i32> bitcasted
3769   // to their dest type. This ensures they get CSE'd.
3770   SDValue Vec;
3771   if (VT.getSizeInBits() == 128) {  // SSE
3772     if (HasSSE2) {  // SSE2
3773       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3774       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3775     } else { // SSE1
3776       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3777       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3778     }
3779   } else if (VT.getSizeInBits() == 256) { // AVX
3780     // 256-bit logic and arithmetic instructions in AVX are
3781     // all floating-point, no support for integer ops. Default
3782     // to emitting fp zeroed vectors then.
3783     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3784     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3785     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3786   }
3787   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3788 }
3789
3790 /// getOnesVector - Returns a vector of specified type with all bits set.
3791 ///
3792 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3793   assert(VT.isVector() && "Expected a vector type");
3794
3795   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3796   // type.  This ensures they get CSE'd.
3797   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3798   SDValue Vec;
3799   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3800   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3801 }
3802
3803
3804 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3805 /// that point to V2 points to its first element.
3806 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3807   EVT VT = SVOp->getValueType(0);
3808   unsigned NumElems = VT.getVectorNumElements();
3809
3810   bool Changed = false;
3811   SmallVector<int, 8> MaskVec;
3812   SVOp->getMask(MaskVec);
3813
3814   for (unsigned i = 0; i != NumElems; ++i) {
3815     if (MaskVec[i] > (int)NumElems) {
3816       MaskVec[i] = NumElems;
3817       Changed = true;
3818     }
3819   }
3820   if (Changed)
3821     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3822                                 SVOp->getOperand(1), &MaskVec[0]);
3823   return SDValue(SVOp, 0);
3824 }
3825
3826 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3827 /// operation of specified width.
3828 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3829                        SDValue V2) {
3830   unsigned NumElems = VT.getVectorNumElements();
3831   SmallVector<int, 8> Mask;
3832   Mask.push_back(NumElems);
3833   for (unsigned i = 1; i != NumElems; ++i)
3834     Mask.push_back(i);
3835   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3836 }
3837
3838 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3839 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3840                           SDValue V2) {
3841   unsigned NumElems = VT.getVectorNumElements();
3842   SmallVector<int, 8> Mask;
3843   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3844     Mask.push_back(i);
3845     Mask.push_back(i + NumElems);
3846   }
3847   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3848 }
3849
3850 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3851 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3852                           SDValue V2) {
3853   unsigned NumElems = VT.getVectorNumElements();
3854   unsigned Half = NumElems/2;
3855   SmallVector<int, 8> Mask;
3856   for (unsigned i = 0; i != Half; ++i) {
3857     Mask.push_back(i + Half);
3858     Mask.push_back(i + NumElems + Half);
3859   }
3860   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3861 }
3862
3863 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3864 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3865   EVT PVT = MVT::v4f32;
3866   EVT VT = SV->getValueType(0);
3867   DebugLoc dl = SV->getDebugLoc();
3868   SDValue V1 = SV->getOperand(0);
3869   int NumElems = VT.getVectorNumElements();
3870   int EltNo = SV->getSplatIndex();
3871
3872   // unpack elements to the correct location
3873   while (NumElems > 4) {
3874     if (EltNo < NumElems/2) {
3875       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3876     } else {
3877       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3878       EltNo -= NumElems/2;
3879     }
3880     NumElems >>= 1;
3881   }
3882
3883   // Perform the splat.
3884   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3885   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3886   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3887   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3888 }
3889
3890 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3891 /// vector of zero or undef vector.  This produces a shuffle where the low
3892 /// element of V2 is swizzled into the zero/undef vector, landing at element
3893 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3894 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3895                                              bool isZero, bool HasSSE2,
3896                                              SelectionDAG &DAG) {
3897   EVT VT = V2.getValueType();
3898   SDValue V1 = isZero
3899     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3900   unsigned NumElems = VT.getVectorNumElements();
3901   SmallVector<int, 16> MaskVec;
3902   for (unsigned i = 0; i != NumElems; ++i)
3903     // If this is the insertion idx, put the low elt of V2 here.
3904     MaskVec.push_back(i == Idx ? NumElems : i);
3905   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3906 }
3907
3908 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3909 /// element of the result of the vector shuffle.
3910 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3911                                    unsigned Depth) {
3912   if (Depth == 6)
3913     return SDValue();  // Limit search depth.
3914
3915   SDValue V = SDValue(N, 0);
3916   EVT VT = V.getValueType();
3917   unsigned Opcode = V.getOpcode();
3918
3919   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3920   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3921     Index = SV->getMaskElt(Index);
3922
3923     if (Index < 0)
3924       return DAG.getUNDEF(VT.getVectorElementType());
3925
3926     int NumElems = VT.getVectorNumElements();
3927     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3928     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3929   }
3930
3931   // Recurse into target specific vector shuffles to find scalars.
3932   if (isTargetShuffle(Opcode)) {
3933     int NumElems = VT.getVectorNumElements();
3934     SmallVector<unsigned, 16> ShuffleMask;
3935     SDValue ImmN;
3936
3937     switch(Opcode) {
3938     case X86ISD::SHUFPS:
3939     case X86ISD::SHUFPD:
3940       ImmN = N->getOperand(N->getNumOperands()-1);
3941       DecodeSHUFPSMask(NumElems,
3942                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3943                        ShuffleMask);
3944       break;
3945     case X86ISD::PUNPCKHBW:
3946     case X86ISD::PUNPCKHWD:
3947     case X86ISD::PUNPCKHDQ:
3948     case X86ISD::PUNPCKHQDQ:
3949       DecodePUNPCKHMask(NumElems, ShuffleMask);
3950       break;
3951     case X86ISD::UNPCKHPS:
3952     case X86ISD::UNPCKHPD:
3953       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3954       break;
3955     case X86ISD::PUNPCKLBW:
3956     case X86ISD::PUNPCKLWD:
3957     case X86ISD::PUNPCKLDQ:
3958     case X86ISD::PUNPCKLQDQ:
3959       DecodePUNPCKLMask(VT, ShuffleMask);
3960       break;
3961     case X86ISD::UNPCKLPS:
3962     case X86ISD::UNPCKLPD:
3963     case X86ISD::VUNPCKLPS:
3964     case X86ISD::VUNPCKLPD:
3965     case X86ISD::VUNPCKLPSY:
3966     case X86ISD::VUNPCKLPDY:
3967       DecodeUNPCKLPMask(VT, ShuffleMask);
3968       break;
3969     case X86ISD::MOVHLPS:
3970       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3971       break;
3972     case X86ISD::MOVLHPS:
3973       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3974       break;
3975     case X86ISD::PSHUFD:
3976       ImmN = N->getOperand(N->getNumOperands()-1);
3977       DecodePSHUFMask(NumElems,
3978                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3979                       ShuffleMask);
3980       break;
3981     case X86ISD::PSHUFHW:
3982       ImmN = N->getOperand(N->getNumOperands()-1);
3983       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3984                         ShuffleMask);
3985       break;
3986     case X86ISD::PSHUFLW:
3987       ImmN = N->getOperand(N->getNumOperands()-1);
3988       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3989                         ShuffleMask);
3990       break;
3991     case X86ISD::MOVSS:
3992     case X86ISD::MOVSD: {
3993       // The index 0 always comes from the first element of the second source,
3994       // this is why MOVSS and MOVSD are used in the first place. The other
3995       // elements come from the other positions of the first source vector.
3996       unsigned OpNum = (Index == 0) ? 1 : 0;
3997       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3998                                  Depth+1);
3999     }
4000     default:
4001       assert("not implemented for target shuffle node");
4002       return SDValue();
4003     }
4004
4005     Index = ShuffleMask[Index];
4006     if (Index < 0)
4007       return DAG.getUNDEF(VT.getVectorElementType());
4008
4009     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4010     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4011                                Depth+1);
4012   }
4013
4014   // Actual nodes that may contain scalar elements
4015   if (Opcode == ISD::BITCAST) {
4016     V = V.getOperand(0);
4017     EVT SrcVT = V.getValueType();
4018     unsigned NumElems = VT.getVectorNumElements();
4019
4020     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4021       return SDValue();
4022   }
4023
4024   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4025     return (Index == 0) ? V.getOperand(0)
4026                           : DAG.getUNDEF(VT.getVectorElementType());
4027
4028   if (V.getOpcode() == ISD::BUILD_VECTOR)
4029     return V.getOperand(Index);
4030
4031   return SDValue();
4032 }
4033
4034 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4035 /// shuffle operation which come from a consecutively from a zero. The
4036 /// search can start in two different directions, from left or right.
4037 static
4038 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4039                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4040   int i = 0;
4041
4042   while (i < NumElems) {
4043     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4044     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4045     if (!(Elt.getNode() &&
4046          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4047       break;
4048     ++i;
4049   }
4050
4051   return i;
4052 }
4053
4054 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4055 /// MaskE correspond consecutively to elements from one of the vector operands,
4056 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4057 static
4058 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4059                               int OpIdx, int NumElems, unsigned &OpNum) {
4060   bool SeenV1 = false;
4061   bool SeenV2 = false;
4062
4063   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4064     int Idx = SVOp->getMaskElt(i);
4065     // Ignore undef indicies
4066     if (Idx < 0)
4067       continue;
4068
4069     if (Idx < NumElems)
4070       SeenV1 = true;
4071     else
4072       SeenV2 = true;
4073
4074     // Only accept consecutive elements from the same vector
4075     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4076       return false;
4077   }
4078
4079   OpNum = SeenV1 ? 0 : 1;
4080   return true;
4081 }
4082
4083 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4084 /// logical left shift of a vector.
4085 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4086                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4087   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4088   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4089               false /* check zeros from right */, DAG);
4090   unsigned OpSrc;
4091
4092   if (!NumZeros)
4093     return false;
4094
4095   // Considering the elements in the mask that are not consecutive zeros,
4096   // check if they consecutively come from only one of the source vectors.
4097   //
4098   //               V1 = {X, A, B, C}     0
4099   //                         \  \  \    /
4100   //   vector_shuffle V1, V2 <1, 2, 3, X>
4101   //
4102   if (!isShuffleMaskConsecutive(SVOp,
4103             0,                   // Mask Start Index
4104             NumElems-NumZeros-1, // Mask End Index
4105             NumZeros,            // Where to start looking in the src vector
4106             NumElems,            // Number of elements in vector
4107             OpSrc))              // Which source operand ?
4108     return false;
4109
4110   isLeft = false;
4111   ShAmt = NumZeros;
4112   ShVal = SVOp->getOperand(OpSrc);
4113   return true;
4114 }
4115
4116 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4117 /// logical left shift of a vector.
4118 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4119                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4120   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4121   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4122               true /* check zeros from left */, DAG);
4123   unsigned OpSrc;
4124
4125   if (!NumZeros)
4126     return false;
4127
4128   // Considering the elements in the mask that are not consecutive zeros,
4129   // check if they consecutively come from only one of the source vectors.
4130   //
4131   //                           0    { A, B, X, X } = V2
4132   //                          / \    /  /
4133   //   vector_shuffle V1, V2 <X, X, 4, 5>
4134   //
4135   if (!isShuffleMaskConsecutive(SVOp,
4136             NumZeros,     // Mask Start Index
4137             NumElems-1,   // Mask End Index
4138             0,            // Where to start looking in the src vector
4139             NumElems,     // Number of elements in vector
4140             OpSrc))       // Which source operand ?
4141     return false;
4142
4143   isLeft = true;
4144   ShAmt = NumZeros;
4145   ShVal = SVOp->getOperand(OpSrc);
4146   return true;
4147 }
4148
4149 /// isVectorShift - Returns true if the shuffle can be implemented as a
4150 /// logical left or right shift of a vector.
4151 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4152                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4153   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4154       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4155     return true;
4156
4157   return false;
4158 }
4159
4160 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4161 ///
4162 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4163                                        unsigned NumNonZero, unsigned NumZero,
4164                                        SelectionDAG &DAG,
4165                                        const TargetLowering &TLI) {
4166   if (NumNonZero > 8)
4167     return SDValue();
4168
4169   DebugLoc dl = Op.getDebugLoc();
4170   SDValue V(0, 0);
4171   bool First = true;
4172   for (unsigned i = 0; i < 16; ++i) {
4173     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4174     if (ThisIsNonZero && First) {
4175       if (NumZero)
4176         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4177       else
4178         V = DAG.getUNDEF(MVT::v8i16);
4179       First = false;
4180     }
4181
4182     if ((i & 1) != 0) {
4183       SDValue ThisElt(0, 0), LastElt(0, 0);
4184       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4185       if (LastIsNonZero) {
4186         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4187                               MVT::i16, Op.getOperand(i-1));
4188       }
4189       if (ThisIsNonZero) {
4190         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4191         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4192                               ThisElt, DAG.getConstant(8, MVT::i8));
4193         if (LastIsNonZero)
4194           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4195       } else
4196         ThisElt = LastElt;
4197
4198       if (ThisElt.getNode())
4199         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4200                         DAG.getIntPtrConstant(i/2));
4201     }
4202   }
4203
4204   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4205 }
4206
4207 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4208 ///
4209 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4210                                      unsigned NumNonZero, unsigned NumZero,
4211                                      SelectionDAG &DAG,
4212                                      const TargetLowering &TLI) {
4213   if (NumNonZero > 4)
4214     return SDValue();
4215
4216   DebugLoc dl = Op.getDebugLoc();
4217   SDValue V(0, 0);
4218   bool First = true;
4219   for (unsigned i = 0; i < 8; ++i) {
4220     bool isNonZero = (NonZeros & (1 << i)) != 0;
4221     if (isNonZero) {
4222       if (First) {
4223         if (NumZero)
4224           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4225         else
4226           V = DAG.getUNDEF(MVT::v8i16);
4227         First = false;
4228       }
4229       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4230                       MVT::v8i16, V, Op.getOperand(i),
4231                       DAG.getIntPtrConstant(i));
4232     }
4233   }
4234
4235   return V;
4236 }
4237
4238 /// getVShift - Return a vector logical shift node.
4239 ///
4240 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4241                          unsigned NumBits, SelectionDAG &DAG,
4242                          const TargetLowering &TLI, DebugLoc dl) {
4243   EVT ShVT = MVT::v2i64;
4244   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4245   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4246   return DAG.getNode(ISD::BITCAST, dl, VT,
4247                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4248                              DAG.getConstant(NumBits,
4249                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4250 }
4251
4252 SDValue
4253 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4254                                           SelectionDAG &DAG) const {
4255
4256   // Check if the scalar load can be widened into a vector load. And if
4257   // the address is "base + cst" see if the cst can be "absorbed" into
4258   // the shuffle mask.
4259   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4260     SDValue Ptr = LD->getBasePtr();
4261     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4262       return SDValue();
4263     EVT PVT = LD->getValueType(0);
4264     if (PVT != MVT::i32 && PVT != MVT::f32)
4265       return SDValue();
4266
4267     int FI = -1;
4268     int64_t Offset = 0;
4269     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4270       FI = FINode->getIndex();
4271       Offset = 0;
4272     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4273                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4274       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4275       Offset = Ptr.getConstantOperandVal(1);
4276       Ptr = Ptr.getOperand(0);
4277     } else {
4278       return SDValue();
4279     }
4280
4281     SDValue Chain = LD->getChain();
4282     // Make sure the stack object alignment is at least 16.
4283     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4284     if (DAG.InferPtrAlignment(Ptr) < 16) {
4285       if (MFI->isFixedObjectIndex(FI)) {
4286         // Can't change the alignment. FIXME: It's possible to compute
4287         // the exact stack offset and reference FI + adjust offset instead.
4288         // If someone *really* cares about this. That's the way to implement it.
4289         return SDValue();
4290       } else {
4291         MFI->setObjectAlignment(FI, 16);
4292       }
4293     }
4294
4295     // (Offset % 16) must be multiple of 4. Then address is then
4296     // Ptr + (Offset & ~15).
4297     if (Offset < 0)
4298       return SDValue();
4299     if ((Offset % 16) & 3)
4300       return SDValue();
4301     int64_t StartOffset = Offset & ~15;
4302     if (StartOffset)
4303       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4304                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4305
4306     int EltNo = (Offset - StartOffset) >> 2;
4307     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4308     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4309     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4310                              LD->getPointerInfo().getWithOffset(StartOffset),
4311                              false, false, 0);
4312     // Canonicalize it to a v4i32 shuffle.
4313     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4314     return DAG.getNode(ISD::BITCAST, dl, VT,
4315                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4316                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4317   }
4318
4319   return SDValue();
4320 }
4321
4322 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4323 /// vector of type 'VT', see if the elements can be replaced by a single large
4324 /// load which has the same value as a build_vector whose operands are 'elts'.
4325 ///
4326 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4327 ///
4328 /// FIXME: we'd also like to handle the case where the last elements are zero
4329 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4330 /// There's even a handy isZeroNode for that purpose.
4331 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4332                                         DebugLoc &DL, SelectionDAG &DAG) {
4333   EVT EltVT = VT.getVectorElementType();
4334   unsigned NumElems = Elts.size();
4335
4336   LoadSDNode *LDBase = NULL;
4337   unsigned LastLoadedElt = -1U;
4338
4339   // For each element in the initializer, see if we've found a load or an undef.
4340   // If we don't find an initial load element, or later load elements are
4341   // non-consecutive, bail out.
4342   for (unsigned i = 0; i < NumElems; ++i) {
4343     SDValue Elt = Elts[i];
4344
4345     if (!Elt.getNode() ||
4346         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4347       return SDValue();
4348     if (!LDBase) {
4349       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4350         return SDValue();
4351       LDBase = cast<LoadSDNode>(Elt.getNode());
4352       LastLoadedElt = i;
4353       continue;
4354     }
4355     if (Elt.getOpcode() == ISD::UNDEF)
4356       continue;
4357
4358     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4359     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4360       return SDValue();
4361     LastLoadedElt = i;
4362   }
4363
4364   // If we have found an entire vector of loads and undefs, then return a large
4365   // load of the entire vector width starting at the base pointer.  If we found
4366   // consecutive loads for the low half, generate a vzext_load node.
4367   if (LastLoadedElt == NumElems - 1) {
4368     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4369       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4370                          LDBase->getPointerInfo(),
4371                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4372     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4373                        LDBase->getPointerInfo(),
4374                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4375                        LDBase->getAlignment());
4376   } else if (NumElems == 4 && LastLoadedElt == 1) {
4377     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4378     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4379     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4380                                               Ops, 2, MVT::i32,
4381                                               LDBase->getMemOperand());
4382     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4383   }
4384   return SDValue();
4385 }
4386
4387 SDValue
4388 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4389   DebugLoc dl = Op.getDebugLoc();
4390
4391   EVT VT = Op.getValueType();
4392   EVT ExtVT = VT.getVectorElementType();
4393
4394   unsigned NumElems = Op.getNumOperands();
4395
4396   // For AVX-length vectors, build the individual 128-bit pieces and
4397   // use shuffles to put them in place.
4398   if (VT.getSizeInBits() > 256 &&
4399       Subtarget->hasAVX() &&
4400       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4401     SmallVector<SDValue, 8> V;
4402     V.resize(NumElems);
4403     for (unsigned i = 0; i < NumElems; ++i) {
4404       V[i] = Op.getOperand(i);
4405     }
4406
4407     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4408
4409     // Build the lower subvector.
4410     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4411     // Build the upper subvector.
4412     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4413                                 NumElems/2);
4414
4415     return ConcatVectors(Lower, Upper, DAG);
4416   }
4417
4418   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4419   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4420   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4421   // is present, so AllOnes is ignored.
4422   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4423       (Op.getValueType().getSizeInBits() != 256 &&
4424        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4425     // Canonicalize this to <4 x i32> (SSE) to
4426     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4427     // eliminated on x86-32 hosts.
4428     if (Op.getValueType() == MVT::v4i32)
4429       return Op;
4430
4431     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4432       return getOnesVector(Op.getValueType(), DAG, dl);
4433     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4434   }
4435
4436   unsigned EVTBits = ExtVT.getSizeInBits();
4437
4438   unsigned NumZero  = 0;
4439   unsigned NumNonZero = 0;
4440   unsigned NonZeros = 0;
4441   bool IsAllConstants = true;
4442   SmallSet<SDValue, 8> Values;
4443   for (unsigned i = 0; i < NumElems; ++i) {
4444     SDValue Elt = Op.getOperand(i);
4445     if (Elt.getOpcode() == ISD::UNDEF)
4446       continue;
4447     Values.insert(Elt);
4448     if (Elt.getOpcode() != ISD::Constant &&
4449         Elt.getOpcode() != ISD::ConstantFP)
4450       IsAllConstants = false;
4451     if (X86::isZeroNode(Elt))
4452       NumZero++;
4453     else {
4454       NonZeros |= (1 << i);
4455       NumNonZero++;
4456     }
4457   }
4458
4459   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4460   if (NumNonZero == 0)
4461     return DAG.getUNDEF(VT);
4462
4463   // Special case for single non-zero, non-undef, element.
4464   if (NumNonZero == 1) {
4465     unsigned Idx = CountTrailingZeros_32(NonZeros);
4466     SDValue Item = Op.getOperand(Idx);
4467
4468     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4469     // the value are obviously zero, truncate the value to i32 and do the
4470     // insertion that way.  Only do this if the value is non-constant or if the
4471     // value is a constant being inserted into element 0.  It is cheaper to do
4472     // a constant pool load than it is to do a movd + shuffle.
4473     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4474         (!IsAllConstants || Idx == 0)) {
4475       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4476         // Handle SSE only.
4477         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4478         EVT VecVT = MVT::v4i32;
4479         unsigned VecElts = 4;
4480
4481         // Truncate the value (which may itself be a constant) to i32, and
4482         // convert it to a vector with movd (S2V+shuffle to zero extend).
4483         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4484         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4485         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4486                                            Subtarget->hasSSE2(), DAG);
4487
4488         // Now we have our 32-bit value zero extended in the low element of
4489         // a vector.  If Idx != 0, swizzle it into place.
4490         if (Idx != 0) {
4491           SmallVector<int, 4> Mask;
4492           Mask.push_back(Idx);
4493           for (unsigned i = 1; i != VecElts; ++i)
4494             Mask.push_back(i);
4495           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4496                                       DAG.getUNDEF(Item.getValueType()),
4497                                       &Mask[0]);
4498         }
4499         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4500       }
4501     }
4502
4503     // If we have a constant or non-constant insertion into the low element of
4504     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4505     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4506     // depending on what the source datatype is.
4507     if (Idx == 0) {
4508       if (NumZero == 0) {
4509         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4510       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4511           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4512         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4513         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4514         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4515                                            DAG);
4516       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4517         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4518         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4519         EVT MiddleVT = MVT::v4i32;
4520         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4521         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4522                                            Subtarget->hasSSE2(), DAG);
4523         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4524       }
4525     }
4526
4527     // Is it a vector logical left shift?
4528     if (NumElems == 2 && Idx == 1 &&
4529         X86::isZeroNode(Op.getOperand(0)) &&
4530         !X86::isZeroNode(Op.getOperand(1))) {
4531       unsigned NumBits = VT.getSizeInBits();
4532       return getVShift(true, VT,
4533                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4534                                    VT, Op.getOperand(1)),
4535                        NumBits/2, DAG, *this, dl);
4536     }
4537
4538     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4539       return SDValue();
4540
4541     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4542     // is a non-constant being inserted into an element other than the low one,
4543     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4544     // movd/movss) to move this into the low element, then shuffle it into
4545     // place.
4546     if (EVTBits == 32) {
4547       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4548
4549       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4550       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4551                                          Subtarget->hasSSE2(), DAG);
4552       SmallVector<int, 8> MaskVec;
4553       for (unsigned i = 0; i < NumElems; i++)
4554         MaskVec.push_back(i == Idx ? 0 : 1);
4555       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4556     }
4557   }
4558
4559   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4560   if (Values.size() == 1) {
4561     if (EVTBits == 32) {
4562       // Instead of a shuffle like this:
4563       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4564       // Check if it's possible to issue this instead.
4565       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4566       unsigned Idx = CountTrailingZeros_32(NonZeros);
4567       SDValue Item = Op.getOperand(Idx);
4568       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4569         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4570     }
4571     return SDValue();
4572   }
4573
4574   // A vector full of immediates; various special cases are already
4575   // handled, so this is best done with a single constant-pool load.
4576   if (IsAllConstants)
4577     return SDValue();
4578
4579   // Let legalizer expand 2-wide build_vectors.
4580   if (EVTBits == 64) {
4581     if (NumNonZero == 1) {
4582       // One half is zero or undef.
4583       unsigned Idx = CountTrailingZeros_32(NonZeros);
4584       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4585                                  Op.getOperand(Idx));
4586       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4587                                          Subtarget->hasSSE2(), DAG);
4588     }
4589     return SDValue();
4590   }
4591
4592   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4593   if (EVTBits == 8 && NumElems == 16) {
4594     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4595                                         *this);
4596     if (V.getNode()) return V;
4597   }
4598
4599   if (EVTBits == 16 && NumElems == 8) {
4600     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4601                                       *this);
4602     if (V.getNode()) return V;
4603   }
4604
4605   // If element VT is == 32 bits, turn it into a number of shuffles.
4606   SmallVector<SDValue, 8> V;
4607   V.resize(NumElems);
4608   if (NumElems == 4 && NumZero > 0) {
4609     for (unsigned i = 0; i < 4; ++i) {
4610       bool isZero = !(NonZeros & (1 << i));
4611       if (isZero)
4612         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4613       else
4614         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4615     }
4616
4617     for (unsigned i = 0; i < 2; ++i) {
4618       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4619         default: break;
4620         case 0:
4621           V[i] = V[i*2];  // Must be a zero vector.
4622           break;
4623         case 1:
4624           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4625           break;
4626         case 2:
4627           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4628           break;
4629         case 3:
4630           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4631           break;
4632       }
4633     }
4634
4635     SmallVector<int, 8> MaskVec;
4636     bool Reverse = (NonZeros & 0x3) == 2;
4637     for (unsigned i = 0; i < 2; ++i)
4638       MaskVec.push_back(Reverse ? 1-i : i);
4639     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4640     for (unsigned i = 0; i < 2; ++i)
4641       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4642     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4643   }
4644
4645   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4646     // Check for a build vector of consecutive loads.
4647     for (unsigned i = 0; i < NumElems; ++i)
4648       V[i] = Op.getOperand(i);
4649
4650     // Check for elements which are consecutive loads.
4651     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4652     if (LD.getNode())
4653       return LD;
4654
4655     // For SSE 4.1, use insertps to put the high elements into the low element.
4656     if (getSubtarget()->hasSSE41()) {
4657       SDValue Result;
4658       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4659         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4660       else
4661         Result = DAG.getUNDEF(VT);
4662
4663       for (unsigned i = 1; i < NumElems; ++i) {
4664         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4665         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4666                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4667       }
4668       return Result;
4669     }
4670
4671     // Otherwise, expand into a number of unpckl*, start by extending each of
4672     // our (non-undef) elements to the full vector width with the element in the
4673     // bottom slot of the vector (which generates no code for SSE).
4674     for (unsigned i = 0; i < NumElems; ++i) {
4675       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4676         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4677       else
4678         V[i] = DAG.getUNDEF(VT);
4679     }
4680
4681     // Next, we iteratively mix elements, e.g. for v4f32:
4682     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4683     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4684     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4685     unsigned EltStride = NumElems >> 1;
4686     while (EltStride != 0) {
4687       for (unsigned i = 0; i < EltStride; ++i) {
4688         // If V[i+EltStride] is undef and this is the first round of mixing,
4689         // then it is safe to just drop this shuffle: V[i] is already in the
4690         // right place, the one element (since it's the first round) being
4691         // inserted as undef can be dropped.  This isn't safe for successive
4692         // rounds because they will permute elements within both vectors.
4693         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4694             EltStride == NumElems/2)
4695           continue;
4696
4697         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4698       }
4699       EltStride >>= 1;
4700     }
4701     return V[0];
4702   }
4703   return SDValue();
4704 }
4705
4706 SDValue
4707 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4708   // We support concatenate two MMX registers and place them in a MMX
4709   // register.  This is better than doing a stack convert.
4710   DebugLoc dl = Op.getDebugLoc();
4711   EVT ResVT = Op.getValueType();
4712   assert(Op.getNumOperands() == 2);
4713   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4714          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4715   int Mask[2];
4716   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4717   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4718   InVec = Op.getOperand(1);
4719   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4720     unsigned NumElts = ResVT.getVectorNumElements();
4721     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4722     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4723                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4724   } else {
4725     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4726     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4727     Mask[0] = 0; Mask[1] = 2;
4728     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4729   }
4730   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4731 }
4732
4733 // v8i16 shuffles - Prefer shuffles in the following order:
4734 // 1. [all]   pshuflw, pshufhw, optional move
4735 // 2. [ssse3] 1 x pshufb
4736 // 3. [ssse3] 2 x pshufb + 1 x por
4737 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4738 SDValue
4739 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4740                                             SelectionDAG &DAG) const {
4741   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4742   SDValue V1 = SVOp->getOperand(0);
4743   SDValue V2 = SVOp->getOperand(1);
4744   DebugLoc dl = SVOp->getDebugLoc();
4745   SmallVector<int, 8> MaskVals;
4746
4747   // Determine if more than 1 of the words in each of the low and high quadwords
4748   // of the result come from the same quadword of one of the two inputs.  Undef
4749   // mask values count as coming from any quadword, for better codegen.
4750   SmallVector<unsigned, 4> LoQuad(4);
4751   SmallVector<unsigned, 4> HiQuad(4);
4752   BitVector InputQuads(4);
4753   for (unsigned i = 0; i < 8; ++i) {
4754     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4755     int EltIdx = SVOp->getMaskElt(i);
4756     MaskVals.push_back(EltIdx);
4757     if (EltIdx < 0) {
4758       ++Quad[0];
4759       ++Quad[1];
4760       ++Quad[2];
4761       ++Quad[3];
4762       continue;
4763     }
4764     ++Quad[EltIdx / 4];
4765     InputQuads.set(EltIdx / 4);
4766   }
4767
4768   int BestLoQuad = -1;
4769   unsigned MaxQuad = 1;
4770   for (unsigned i = 0; i < 4; ++i) {
4771     if (LoQuad[i] > MaxQuad) {
4772       BestLoQuad = i;
4773       MaxQuad = LoQuad[i];
4774     }
4775   }
4776
4777   int BestHiQuad = -1;
4778   MaxQuad = 1;
4779   for (unsigned i = 0; i < 4; ++i) {
4780     if (HiQuad[i] > MaxQuad) {
4781       BestHiQuad = i;
4782       MaxQuad = HiQuad[i];
4783     }
4784   }
4785
4786   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4787   // of the two input vectors, shuffle them into one input vector so only a
4788   // single pshufb instruction is necessary. If There are more than 2 input
4789   // quads, disable the next transformation since it does not help SSSE3.
4790   bool V1Used = InputQuads[0] || InputQuads[1];
4791   bool V2Used = InputQuads[2] || InputQuads[3];
4792   if (Subtarget->hasSSSE3()) {
4793     if (InputQuads.count() == 2 && V1Used && V2Used) {
4794       BestLoQuad = InputQuads.find_first();
4795       BestHiQuad = InputQuads.find_next(BestLoQuad);
4796     }
4797     if (InputQuads.count() > 2) {
4798       BestLoQuad = -1;
4799       BestHiQuad = -1;
4800     }
4801   }
4802
4803   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4804   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4805   // words from all 4 input quadwords.
4806   SDValue NewV;
4807   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4808     SmallVector<int, 8> MaskV;
4809     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4810     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4811     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4812                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4813                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4814     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4815
4816     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4817     // source words for the shuffle, to aid later transformations.
4818     bool AllWordsInNewV = true;
4819     bool InOrder[2] = { true, true };
4820     for (unsigned i = 0; i != 8; ++i) {
4821       int idx = MaskVals[i];
4822       if (idx != (int)i)
4823         InOrder[i/4] = false;
4824       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4825         continue;
4826       AllWordsInNewV = false;
4827       break;
4828     }
4829
4830     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4831     if (AllWordsInNewV) {
4832       for (int i = 0; i != 8; ++i) {
4833         int idx = MaskVals[i];
4834         if (idx < 0)
4835           continue;
4836         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4837         if ((idx != i) && idx < 4)
4838           pshufhw = false;
4839         if ((idx != i) && idx > 3)
4840           pshuflw = false;
4841       }
4842       V1 = NewV;
4843       V2Used = false;
4844       BestLoQuad = 0;
4845       BestHiQuad = 1;
4846     }
4847
4848     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4849     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4850     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4851       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4852       unsigned TargetMask = 0;
4853       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4854                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4855       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4856                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4857       V1 = NewV.getOperand(0);
4858       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4859     }
4860   }
4861
4862   // If we have SSSE3, and all words of the result are from 1 input vector,
4863   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4864   // is present, fall back to case 4.
4865   if (Subtarget->hasSSSE3()) {
4866     SmallVector<SDValue,16> pshufbMask;
4867
4868     // If we have elements from both input vectors, set the high bit of the
4869     // shuffle mask element to zero out elements that come from V2 in the V1
4870     // mask, and elements that come from V1 in the V2 mask, so that the two
4871     // results can be OR'd together.
4872     bool TwoInputs = V1Used && V2Used;
4873     for (unsigned i = 0; i != 8; ++i) {
4874       int EltIdx = MaskVals[i] * 2;
4875       if (TwoInputs && (EltIdx >= 16)) {
4876         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4877         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4878         continue;
4879       }
4880       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4881       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4882     }
4883     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4884     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4885                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4886                                  MVT::v16i8, &pshufbMask[0], 16));
4887     if (!TwoInputs)
4888       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4889
4890     // Calculate the shuffle mask for the second input, shuffle it, and
4891     // OR it with the first shuffled input.
4892     pshufbMask.clear();
4893     for (unsigned i = 0; i != 8; ++i) {
4894       int EltIdx = MaskVals[i] * 2;
4895       if (EltIdx < 16) {
4896         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4897         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4898         continue;
4899       }
4900       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4901       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4902     }
4903     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4904     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4905                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4906                                  MVT::v16i8, &pshufbMask[0], 16));
4907     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4908     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4909   }
4910
4911   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4912   // and update MaskVals with new element order.
4913   BitVector InOrder(8);
4914   if (BestLoQuad >= 0) {
4915     SmallVector<int, 8> MaskV;
4916     for (int i = 0; i != 4; ++i) {
4917       int idx = MaskVals[i];
4918       if (idx < 0) {
4919         MaskV.push_back(-1);
4920         InOrder.set(i);
4921       } else if ((idx / 4) == BestLoQuad) {
4922         MaskV.push_back(idx & 3);
4923         InOrder.set(i);
4924       } else {
4925         MaskV.push_back(-1);
4926       }
4927     }
4928     for (unsigned i = 4; i != 8; ++i)
4929       MaskV.push_back(i);
4930     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4931                                 &MaskV[0]);
4932
4933     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4934       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4935                                NewV.getOperand(0),
4936                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4937                                DAG);
4938   }
4939
4940   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4941   // and update MaskVals with the new element order.
4942   if (BestHiQuad >= 0) {
4943     SmallVector<int, 8> MaskV;
4944     for (unsigned i = 0; i != 4; ++i)
4945       MaskV.push_back(i);
4946     for (unsigned i = 4; i != 8; ++i) {
4947       int idx = MaskVals[i];
4948       if (idx < 0) {
4949         MaskV.push_back(-1);
4950         InOrder.set(i);
4951       } else if ((idx / 4) == BestHiQuad) {
4952         MaskV.push_back((idx & 3) + 4);
4953         InOrder.set(i);
4954       } else {
4955         MaskV.push_back(-1);
4956       }
4957     }
4958     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4959                                 &MaskV[0]);
4960
4961     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4962       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4963                               NewV.getOperand(0),
4964                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4965                               DAG);
4966   }
4967
4968   // In case BestHi & BestLo were both -1, which means each quadword has a word
4969   // from each of the four input quadwords, calculate the InOrder bitvector now
4970   // before falling through to the insert/extract cleanup.
4971   if (BestLoQuad == -1 && BestHiQuad == -1) {
4972     NewV = V1;
4973     for (int i = 0; i != 8; ++i)
4974       if (MaskVals[i] < 0 || MaskVals[i] == i)
4975         InOrder.set(i);
4976   }
4977
4978   // The other elements are put in the right place using pextrw and pinsrw.
4979   for (unsigned i = 0; i != 8; ++i) {
4980     if (InOrder[i])
4981       continue;
4982     int EltIdx = MaskVals[i];
4983     if (EltIdx < 0)
4984       continue;
4985     SDValue ExtOp = (EltIdx < 8)
4986     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4987                   DAG.getIntPtrConstant(EltIdx))
4988     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4989                   DAG.getIntPtrConstant(EltIdx - 8));
4990     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4991                        DAG.getIntPtrConstant(i));
4992   }
4993   return NewV;
4994 }
4995
4996 // v16i8 shuffles - Prefer shuffles in the following order:
4997 // 1. [ssse3] 1 x pshufb
4998 // 2. [ssse3] 2 x pshufb + 1 x por
4999 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5000 static
5001 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5002                                  SelectionDAG &DAG,
5003                                  const X86TargetLowering &TLI) {
5004   SDValue V1 = SVOp->getOperand(0);
5005   SDValue V2 = SVOp->getOperand(1);
5006   DebugLoc dl = SVOp->getDebugLoc();
5007   SmallVector<int, 16> MaskVals;
5008   SVOp->getMask(MaskVals);
5009
5010   // If we have SSSE3, case 1 is generated when all result bytes come from
5011   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5012   // present, fall back to case 3.
5013   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5014   bool V1Only = true;
5015   bool V2Only = true;
5016   for (unsigned i = 0; i < 16; ++i) {
5017     int EltIdx = MaskVals[i];
5018     if (EltIdx < 0)
5019       continue;
5020     if (EltIdx < 16)
5021       V2Only = false;
5022     else
5023       V1Only = false;
5024   }
5025
5026   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5027   if (TLI.getSubtarget()->hasSSSE3()) {
5028     SmallVector<SDValue,16> pshufbMask;
5029
5030     // If all result elements are from one input vector, then only translate
5031     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5032     //
5033     // Otherwise, we have elements from both input vectors, and must zero out
5034     // elements that come from V2 in the first mask, and V1 in the second mask
5035     // so that we can OR them together.
5036     bool TwoInputs = !(V1Only || V2Only);
5037     for (unsigned i = 0; i != 16; ++i) {
5038       int EltIdx = MaskVals[i];
5039       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5040         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5041         continue;
5042       }
5043       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5044     }
5045     // If all the elements are from V2, assign it to V1 and return after
5046     // building the first pshufb.
5047     if (V2Only)
5048       V1 = V2;
5049     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5050                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5051                                  MVT::v16i8, &pshufbMask[0], 16));
5052     if (!TwoInputs)
5053       return V1;
5054
5055     // Calculate the shuffle mask for the second input, shuffle it, and
5056     // OR it with the first shuffled input.
5057     pshufbMask.clear();
5058     for (unsigned i = 0; i != 16; ++i) {
5059       int EltIdx = MaskVals[i];
5060       if (EltIdx < 16) {
5061         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5062         continue;
5063       }
5064       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5065     }
5066     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5067                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5068                                  MVT::v16i8, &pshufbMask[0], 16));
5069     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5070   }
5071
5072   // No SSSE3 - Calculate in place words and then fix all out of place words
5073   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5074   // the 16 different words that comprise the two doublequadword input vectors.
5075   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5076   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5077   SDValue NewV = V2Only ? V2 : V1;
5078   for (int i = 0; i != 8; ++i) {
5079     int Elt0 = MaskVals[i*2];
5080     int Elt1 = MaskVals[i*2+1];
5081
5082     // This word of the result is all undef, skip it.
5083     if (Elt0 < 0 && Elt1 < 0)
5084       continue;
5085
5086     // This word of the result is already in the correct place, skip it.
5087     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5088       continue;
5089     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5090       continue;
5091
5092     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5093     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5094     SDValue InsElt;
5095
5096     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5097     // using a single extract together, load it and store it.
5098     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5099       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5100                            DAG.getIntPtrConstant(Elt1 / 2));
5101       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5102                         DAG.getIntPtrConstant(i));
5103       continue;
5104     }
5105
5106     // If Elt1 is defined, extract it from the appropriate source.  If the
5107     // source byte is not also odd, shift the extracted word left 8 bits
5108     // otherwise clear the bottom 8 bits if we need to do an or.
5109     if (Elt1 >= 0) {
5110       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5111                            DAG.getIntPtrConstant(Elt1 / 2));
5112       if ((Elt1 & 1) == 0)
5113         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5114                              DAG.getConstant(8,
5115                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5116       else if (Elt0 >= 0)
5117         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5118                              DAG.getConstant(0xFF00, MVT::i16));
5119     }
5120     // If Elt0 is defined, extract it from the appropriate source.  If the
5121     // source byte is not also even, shift the extracted word right 8 bits. If
5122     // Elt1 was also defined, OR the extracted values together before
5123     // inserting them in the result.
5124     if (Elt0 >= 0) {
5125       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5126                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5127       if ((Elt0 & 1) != 0)
5128         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5129                               DAG.getConstant(8,
5130                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5131       else if (Elt1 >= 0)
5132         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5133                              DAG.getConstant(0x00FF, MVT::i16));
5134       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5135                          : InsElt0;
5136     }
5137     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5138                        DAG.getIntPtrConstant(i));
5139   }
5140   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5141 }
5142
5143 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5144 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5145 /// done when every pair / quad of shuffle mask elements point to elements in
5146 /// the right sequence. e.g.
5147 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5148 static
5149 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5150                                  SelectionDAG &DAG, DebugLoc dl) {
5151   EVT VT = SVOp->getValueType(0);
5152   SDValue V1 = SVOp->getOperand(0);
5153   SDValue V2 = SVOp->getOperand(1);
5154   unsigned NumElems = VT.getVectorNumElements();
5155   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5156   EVT NewVT;
5157   switch (VT.getSimpleVT().SimpleTy) {
5158   default: assert(false && "Unexpected!");
5159   case MVT::v4f32: NewVT = MVT::v2f64; break;
5160   case MVT::v4i32: NewVT = MVT::v2i64; break;
5161   case MVT::v8i16: NewVT = MVT::v4i32; break;
5162   case MVT::v16i8: NewVT = MVT::v4i32; break;
5163   }
5164
5165   int Scale = NumElems / NewWidth;
5166   SmallVector<int, 8> MaskVec;
5167   for (unsigned i = 0; i < NumElems; i += Scale) {
5168     int StartIdx = -1;
5169     for (int j = 0; j < Scale; ++j) {
5170       int EltIdx = SVOp->getMaskElt(i+j);
5171       if (EltIdx < 0)
5172         continue;
5173       if (StartIdx == -1)
5174         StartIdx = EltIdx - (EltIdx % Scale);
5175       if (EltIdx != StartIdx + j)
5176         return SDValue();
5177     }
5178     if (StartIdx == -1)
5179       MaskVec.push_back(-1);
5180     else
5181       MaskVec.push_back(StartIdx / Scale);
5182   }
5183
5184   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5185   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5186   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5187 }
5188
5189 /// getVZextMovL - Return a zero-extending vector move low node.
5190 ///
5191 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5192                             SDValue SrcOp, SelectionDAG &DAG,
5193                             const X86Subtarget *Subtarget, DebugLoc dl) {
5194   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5195     LoadSDNode *LD = NULL;
5196     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5197       LD = dyn_cast<LoadSDNode>(SrcOp);
5198     if (!LD) {
5199       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5200       // instead.
5201       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5202       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5203           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5204           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5205           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5206         // PR2108
5207         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5208         return DAG.getNode(ISD::BITCAST, dl, VT,
5209                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5210                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5211                                                    OpVT,
5212                                                    SrcOp.getOperand(0)
5213                                                           .getOperand(0))));
5214       }
5215     }
5216   }
5217
5218   return DAG.getNode(ISD::BITCAST, dl, VT,
5219                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5220                                  DAG.getNode(ISD::BITCAST, dl,
5221                                              OpVT, SrcOp)));
5222 }
5223
5224 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5225 /// shuffles.
5226 static SDValue
5227 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5228   SDValue V1 = SVOp->getOperand(0);
5229   SDValue V2 = SVOp->getOperand(1);
5230   DebugLoc dl = SVOp->getDebugLoc();
5231   EVT VT = SVOp->getValueType(0);
5232
5233   SmallVector<std::pair<int, int>, 8> Locs;
5234   Locs.resize(4);
5235   SmallVector<int, 8> Mask1(4U, -1);
5236   SmallVector<int, 8> PermMask;
5237   SVOp->getMask(PermMask);
5238
5239   unsigned NumHi = 0;
5240   unsigned NumLo = 0;
5241   for (unsigned i = 0; i != 4; ++i) {
5242     int Idx = PermMask[i];
5243     if (Idx < 0) {
5244       Locs[i] = std::make_pair(-1, -1);
5245     } else {
5246       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5247       if (Idx < 4) {
5248         Locs[i] = std::make_pair(0, NumLo);
5249         Mask1[NumLo] = Idx;
5250         NumLo++;
5251       } else {
5252         Locs[i] = std::make_pair(1, NumHi);
5253         if (2+NumHi < 4)
5254           Mask1[2+NumHi] = Idx;
5255         NumHi++;
5256       }
5257     }
5258   }
5259
5260   if (NumLo <= 2 && NumHi <= 2) {
5261     // If no more than two elements come from either vector. This can be
5262     // implemented with two shuffles. First shuffle gather the elements.
5263     // The second shuffle, which takes the first shuffle as both of its
5264     // vector operands, put the elements into the right order.
5265     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5266
5267     SmallVector<int, 8> Mask2(4U, -1);
5268
5269     for (unsigned i = 0; i != 4; ++i) {
5270       if (Locs[i].first == -1)
5271         continue;
5272       else {
5273         unsigned Idx = (i < 2) ? 0 : 4;
5274         Idx += Locs[i].first * 2 + Locs[i].second;
5275         Mask2[i] = Idx;
5276       }
5277     }
5278
5279     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5280   } else if (NumLo == 3 || NumHi == 3) {
5281     // Otherwise, we must have three elements from one vector, call it X, and
5282     // one element from the other, call it Y.  First, use a shufps to build an
5283     // intermediate vector with the one element from Y and the element from X
5284     // that will be in the same half in the final destination (the indexes don't
5285     // matter). Then, use a shufps to build the final vector, taking the half
5286     // containing the element from Y from the intermediate, and the other half
5287     // from X.
5288     if (NumHi == 3) {
5289       // Normalize it so the 3 elements come from V1.
5290       CommuteVectorShuffleMask(PermMask, VT);
5291       std::swap(V1, V2);
5292     }
5293
5294     // Find the element from V2.
5295     unsigned HiIndex;
5296     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5297       int Val = PermMask[HiIndex];
5298       if (Val < 0)
5299         continue;
5300       if (Val >= 4)
5301         break;
5302     }
5303
5304     Mask1[0] = PermMask[HiIndex];
5305     Mask1[1] = -1;
5306     Mask1[2] = PermMask[HiIndex^1];
5307     Mask1[3] = -1;
5308     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5309
5310     if (HiIndex >= 2) {
5311       Mask1[0] = PermMask[0];
5312       Mask1[1] = PermMask[1];
5313       Mask1[2] = HiIndex & 1 ? 6 : 4;
5314       Mask1[3] = HiIndex & 1 ? 4 : 6;
5315       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5316     } else {
5317       Mask1[0] = HiIndex & 1 ? 2 : 0;
5318       Mask1[1] = HiIndex & 1 ? 0 : 2;
5319       Mask1[2] = PermMask[2];
5320       Mask1[3] = PermMask[3];
5321       if (Mask1[2] >= 0)
5322         Mask1[2] += 4;
5323       if (Mask1[3] >= 0)
5324         Mask1[3] += 4;
5325       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5326     }
5327   }
5328
5329   // Break it into (shuffle shuffle_hi, shuffle_lo).
5330   Locs.clear();
5331   Locs.resize(4);
5332   SmallVector<int,8> LoMask(4U, -1);
5333   SmallVector<int,8> HiMask(4U, -1);
5334
5335   SmallVector<int,8> *MaskPtr = &LoMask;
5336   unsigned MaskIdx = 0;
5337   unsigned LoIdx = 0;
5338   unsigned HiIdx = 2;
5339   for (unsigned i = 0; i != 4; ++i) {
5340     if (i == 2) {
5341       MaskPtr = &HiMask;
5342       MaskIdx = 1;
5343       LoIdx = 0;
5344       HiIdx = 2;
5345     }
5346     int Idx = PermMask[i];
5347     if (Idx < 0) {
5348       Locs[i] = std::make_pair(-1, -1);
5349     } else if (Idx < 4) {
5350       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5351       (*MaskPtr)[LoIdx] = Idx;
5352       LoIdx++;
5353     } else {
5354       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5355       (*MaskPtr)[HiIdx] = Idx;
5356       HiIdx++;
5357     }
5358   }
5359
5360   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5361   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5362   SmallVector<int, 8> MaskOps;
5363   for (unsigned i = 0; i != 4; ++i) {
5364     if (Locs[i].first == -1) {
5365       MaskOps.push_back(-1);
5366     } else {
5367       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5368       MaskOps.push_back(Idx);
5369     }
5370   }
5371   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5372 }
5373
5374 static bool MayFoldVectorLoad(SDValue V) {
5375   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5376     V = V.getOperand(0);
5377   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5378     V = V.getOperand(0);
5379   if (MayFoldLoad(V))
5380     return true;
5381   return false;
5382 }
5383
5384 // FIXME: the version above should always be used. Since there's
5385 // a bug where several vector shuffles can't be folded because the
5386 // DAG is not updated during lowering and a node claims to have two
5387 // uses while it only has one, use this version, and let isel match
5388 // another instruction if the load really happens to have more than
5389 // one use. Remove this version after this bug get fixed.
5390 // rdar://8434668, PR8156
5391 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5392   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5393     V = V.getOperand(0);
5394   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5395     V = V.getOperand(0);
5396   if (ISD::isNormalLoad(V.getNode()))
5397     return true;
5398   return false;
5399 }
5400
5401 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5402 /// a vector extract, and if both can be later optimized into a single load.
5403 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5404 /// here because otherwise a target specific shuffle node is going to be
5405 /// emitted for this shuffle, and the optimization not done.
5406 /// FIXME: This is probably not the best approach, but fix the problem
5407 /// until the right path is decided.
5408 static
5409 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5410                                          const TargetLowering &TLI) {
5411   EVT VT = V.getValueType();
5412   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5413
5414   // Be sure that the vector shuffle is present in a pattern like this:
5415   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5416   if (!V.hasOneUse())
5417     return false;
5418
5419   SDNode *N = *V.getNode()->use_begin();
5420   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5421     return false;
5422
5423   SDValue EltNo = N->getOperand(1);
5424   if (!isa<ConstantSDNode>(EltNo))
5425     return false;
5426
5427   // If the bit convert changed the number of elements, it is unsafe
5428   // to examine the mask.
5429   bool HasShuffleIntoBitcast = false;
5430   if (V.getOpcode() == ISD::BITCAST) {
5431     EVT SrcVT = V.getOperand(0).getValueType();
5432     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5433       return false;
5434     V = V.getOperand(0);
5435     HasShuffleIntoBitcast = true;
5436   }
5437
5438   // Select the input vector, guarding against out of range extract vector.
5439   unsigned NumElems = VT.getVectorNumElements();
5440   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5441   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5442   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5443
5444   // Skip one more bit_convert if necessary
5445   if (V.getOpcode() == ISD::BITCAST)
5446     V = V.getOperand(0);
5447
5448   if (ISD::isNormalLoad(V.getNode())) {
5449     // Is the original load suitable?
5450     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5451
5452     // FIXME: avoid the multi-use bug that is preventing lots of
5453     // of foldings to be detected, this is still wrong of course, but
5454     // give the temporary desired behavior, and if it happens that
5455     // the load has real more uses, during isel it will not fold, and
5456     // will generate poor code.
5457     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5458       return false;
5459
5460     if (!HasShuffleIntoBitcast)
5461       return true;
5462
5463     // If there's a bitcast before the shuffle, check if the load type and
5464     // alignment is valid.
5465     unsigned Align = LN0->getAlignment();
5466     unsigned NewAlign =
5467       TLI.getTargetData()->getABITypeAlignment(
5468                                     VT.getTypeForEVT(*DAG.getContext()));
5469
5470     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5471       return false;
5472   }
5473
5474   return true;
5475 }
5476
5477 static
5478 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5479   EVT VT = Op.getValueType();
5480
5481   // Canonizalize to v2f64.
5482   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5483   return DAG.getNode(ISD::BITCAST, dl, VT,
5484                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5485                                           V1, DAG));
5486 }
5487
5488 static
5489 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5490                         bool HasSSE2) {
5491   SDValue V1 = Op.getOperand(0);
5492   SDValue V2 = Op.getOperand(1);
5493   EVT VT = Op.getValueType();
5494
5495   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5496
5497   if (HasSSE2 && VT == MVT::v2f64)
5498     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5499
5500   // v4f32 or v4i32
5501   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5502 }
5503
5504 static
5505 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5506   SDValue V1 = Op.getOperand(0);
5507   SDValue V2 = Op.getOperand(1);
5508   EVT VT = Op.getValueType();
5509
5510   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5511          "unsupported shuffle type");
5512
5513   if (V2.getOpcode() == ISD::UNDEF)
5514     V2 = V1;
5515
5516   // v4i32 or v4f32
5517   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5518 }
5519
5520 static
5521 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5522   SDValue V1 = Op.getOperand(0);
5523   SDValue V2 = Op.getOperand(1);
5524   EVT VT = Op.getValueType();
5525   unsigned NumElems = VT.getVectorNumElements();
5526
5527   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5528   // operand of these instructions is only memory, so check if there's a
5529   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5530   // same masks.
5531   bool CanFoldLoad = false;
5532
5533   // Trivial case, when V2 comes from a load.
5534   if (MayFoldVectorLoad(V2))
5535     CanFoldLoad = true;
5536
5537   // When V1 is a load, it can be folded later into a store in isel, example:
5538   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5539   //    turns into:
5540   //  (MOVLPSmr addr:$src1, VR128:$src2)
5541   // So, recognize this potential and also use MOVLPS or MOVLPD
5542   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5543     CanFoldLoad = true;
5544
5545   // Both of them can't be memory operations though.
5546   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5547     CanFoldLoad = false;
5548
5549   if (CanFoldLoad) {
5550     if (HasSSE2 && NumElems == 2)
5551       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5552
5553     if (NumElems == 4)
5554       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5555   }
5556
5557   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5558   // movl and movlp will both match v2i64, but v2i64 is never matched by
5559   // movl earlier because we make it strict to avoid messing with the movlp load
5560   // folding logic (see the code above getMOVLP call). Match it here then,
5561   // this is horrible, but will stay like this until we move all shuffle
5562   // matching to x86 specific nodes. Note that for the 1st condition all
5563   // types are matched with movsd.
5564   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5565     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5566   else if (HasSSE2)
5567     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5568
5569
5570   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5571
5572   // Invert the operand order and use SHUFPS to match it.
5573   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5574                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5575 }
5576
5577 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5578   switch(VT.getSimpleVT().SimpleTy) {
5579   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5580   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5581   case MVT::v4f32:
5582     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5583   case MVT::v2f64:
5584     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5585   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5586   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5587   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5588   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5589   default:
5590     llvm_unreachable("Unknown type for unpckl");
5591   }
5592   return 0;
5593 }
5594
5595 static inline unsigned getUNPCKHOpcode(EVT VT) {
5596   switch(VT.getSimpleVT().SimpleTy) {
5597   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5598   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5599   case MVT::v4f32: return X86ISD::UNPCKHPS;
5600   case MVT::v2f64: return X86ISD::UNPCKHPD;
5601   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5602   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5603   default:
5604     llvm_unreachable("Unknown type for unpckh");
5605   }
5606   return 0;
5607 }
5608
5609 static
5610 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5611                                const TargetLowering &TLI,
5612                                const X86Subtarget *Subtarget) {
5613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5614   EVT VT = Op.getValueType();
5615   DebugLoc dl = Op.getDebugLoc();
5616   SDValue V1 = Op.getOperand(0);
5617   SDValue V2 = Op.getOperand(1);
5618
5619   if (isZeroShuffle(SVOp))
5620     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5621
5622   // Handle splat operations
5623   if (SVOp->isSplat()) {
5624     // Special case, this is the only place now where it's
5625     // allowed to return a vector_shuffle operation without
5626     // using a target specific node, because *hopefully* it
5627     // will be optimized away by the dag combiner.
5628     if (VT.getVectorNumElements() <= 4 &&
5629         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5630       return Op;
5631
5632     // Handle splats by matching through known masks
5633     if (VT.getVectorNumElements() <= 4)
5634       return SDValue();
5635
5636     // Canonicalize all of the remaining to v4f32.
5637     return PromoteSplat(SVOp, DAG);
5638   }
5639
5640   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5641   // do it!
5642   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5643     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5644     if (NewOp.getNode())
5645       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5646   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5647     // FIXME: Figure out a cleaner way to do this.
5648     // Try to make use of movq to zero out the top part.
5649     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5650       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5651       if (NewOp.getNode()) {
5652         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5653           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5654                               DAG, Subtarget, dl);
5655       }
5656     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5657       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5658       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5659         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5660                             DAG, Subtarget, dl);
5661     }
5662   }
5663   return SDValue();
5664 }
5665
5666 SDValue
5667 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5668   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5669   SDValue V1 = Op.getOperand(0);
5670   SDValue V2 = Op.getOperand(1);
5671   EVT VT = Op.getValueType();
5672   DebugLoc dl = Op.getDebugLoc();
5673   unsigned NumElems = VT.getVectorNumElements();
5674   bool isMMX = VT.getSizeInBits() == 64;
5675   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5676   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5677   bool V1IsSplat = false;
5678   bool V2IsSplat = false;
5679   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5680   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5681   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5682   MachineFunction &MF = DAG.getMachineFunction();
5683   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5684
5685   // Shuffle operations on MMX not supported.
5686   if (isMMX)
5687     return Op;
5688
5689   // Vector shuffle lowering takes 3 steps:
5690   //
5691   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5692   //    narrowing and commutation of operands should be handled.
5693   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5694   //    shuffle nodes.
5695   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5696   //    so the shuffle can be broken into other shuffles and the legalizer can
5697   //    try the lowering again.
5698   //
5699   // The general ideia is that no vector_shuffle operation should be left to
5700   // be matched during isel, all of them must be converted to a target specific
5701   // node here.
5702
5703   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5704   // narrowing and commutation of operands should be handled. The actual code
5705   // doesn't include all of those, work in progress...
5706   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5707   if (NewOp.getNode())
5708     return NewOp;
5709
5710   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5711   // unpckh_undef). Only use pshufd if speed is more important than size.
5712   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5713     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5714       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5715   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5716     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5717       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5718
5719   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5720       RelaxedMayFoldVectorLoad(V1))
5721     return getMOVDDup(Op, dl, V1, DAG);
5722
5723   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5724     return getMOVHighToLow(Op, dl, DAG);
5725
5726   // Use to match splats
5727   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5728       (VT == MVT::v2f64 || VT == MVT::v2i64))
5729     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5730
5731   if (X86::isPSHUFDMask(SVOp)) {
5732     // The actual implementation will match the mask in the if above and then
5733     // during isel it can match several different instructions, not only pshufd
5734     // as its name says, sad but true, emulate the behavior for now...
5735     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5736         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5737
5738     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5739
5740     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5741       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5742
5743     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5744       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5745                                   TargetMask, DAG);
5746
5747     if (VT == MVT::v4f32)
5748       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5749                                   TargetMask, DAG);
5750   }
5751
5752   // Check if this can be converted into a logical shift.
5753   bool isLeft = false;
5754   unsigned ShAmt = 0;
5755   SDValue ShVal;
5756   bool isShift = getSubtarget()->hasSSE2() &&
5757     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5758   if (isShift && ShVal.hasOneUse()) {
5759     // If the shifted value has multiple uses, it may be cheaper to use
5760     // v_set0 + movlhps or movhlps, etc.
5761     EVT EltVT = VT.getVectorElementType();
5762     ShAmt *= EltVT.getSizeInBits();
5763     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5764   }
5765
5766   if (X86::isMOVLMask(SVOp)) {
5767     if (V1IsUndef)
5768       return V2;
5769     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5770       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5771     if (!X86::isMOVLPMask(SVOp)) {
5772       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5773         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5774
5775       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5776         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5777     }
5778   }
5779
5780   // FIXME: fold these into legal mask.
5781   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5782     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5783
5784   if (X86::isMOVHLPSMask(SVOp))
5785     return getMOVHighToLow(Op, dl, DAG);
5786
5787   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5788     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5789
5790   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5791     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5792
5793   if (X86::isMOVLPMask(SVOp))
5794     return getMOVLP(Op, dl, DAG, HasSSE2);
5795
5796   if (ShouldXformToMOVHLPS(SVOp) ||
5797       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5798     return CommuteVectorShuffle(SVOp, DAG);
5799
5800   if (isShift) {
5801     // No better options. Use a vshl / vsrl.
5802     EVT EltVT = VT.getVectorElementType();
5803     ShAmt *= EltVT.getSizeInBits();
5804     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5805   }
5806
5807   bool Commuted = false;
5808   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5809   // 1,1,1,1 -> v8i16 though.
5810   V1IsSplat = isSplatVector(V1.getNode());
5811   V2IsSplat = isSplatVector(V2.getNode());
5812
5813   // Canonicalize the splat or undef, if present, to be on the RHS.
5814   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5815     Op = CommuteVectorShuffle(SVOp, DAG);
5816     SVOp = cast<ShuffleVectorSDNode>(Op);
5817     V1 = SVOp->getOperand(0);
5818     V2 = SVOp->getOperand(1);
5819     std::swap(V1IsSplat, V2IsSplat);
5820     std::swap(V1IsUndef, V2IsUndef);
5821     Commuted = true;
5822   }
5823
5824   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5825     // Shuffling low element of v1 into undef, just return v1.
5826     if (V2IsUndef)
5827       return V1;
5828     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5829     // the instruction selector will not match, so get a canonical MOVL with
5830     // swapped operands to undo the commute.
5831     return getMOVL(DAG, dl, VT, V2, V1);
5832   }
5833
5834   if (X86::isUNPCKLMask(SVOp))
5835     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5836                                 dl, VT, V1, V2, DAG);
5837
5838   if (X86::isUNPCKHMask(SVOp))
5839     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5840
5841   if (V2IsSplat) {
5842     // Normalize mask so all entries that point to V2 points to its first
5843     // element then try to match unpck{h|l} again. If match, return a
5844     // new vector_shuffle with the corrected mask.
5845     SDValue NewMask = NormalizeMask(SVOp, DAG);
5846     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5847     if (NSVOp != SVOp) {
5848       if (X86::isUNPCKLMask(NSVOp, true)) {
5849         return NewMask;
5850       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5851         return NewMask;
5852       }
5853     }
5854   }
5855
5856   if (Commuted) {
5857     // Commute is back and try unpck* again.
5858     // FIXME: this seems wrong.
5859     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5860     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5861
5862     if (X86::isUNPCKLMask(NewSVOp))
5863       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5864                                   dl, VT, V2, V1, DAG);
5865
5866     if (X86::isUNPCKHMask(NewSVOp))
5867       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5868   }
5869
5870   // Normalize the node to match x86 shuffle ops if needed
5871   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5872     return CommuteVectorShuffle(SVOp, DAG);
5873
5874   // The checks below are all present in isShuffleMaskLegal, but they are
5875   // inlined here right now to enable us to directly emit target specific
5876   // nodes, and remove one by one until they don't return Op anymore.
5877   SmallVector<int, 16> M;
5878   SVOp->getMask(M);
5879
5880   if (isPALIGNRMask(M, VT, HasSSSE3))
5881     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5882                                 X86::getShufflePALIGNRImmediate(SVOp),
5883                                 DAG);
5884
5885   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5886       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5887     if (VT == MVT::v2f64) {
5888       X86ISD::NodeType Opcode =
5889         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5890       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5891     }
5892     if (VT == MVT::v2i64)
5893       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5894   }
5895
5896   if (isPSHUFHWMask(M, VT))
5897     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5898                                 X86::getShufflePSHUFHWImmediate(SVOp),
5899                                 DAG);
5900
5901   if (isPSHUFLWMask(M, VT))
5902     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5903                                 X86::getShufflePSHUFLWImmediate(SVOp),
5904                                 DAG);
5905
5906   if (isSHUFPMask(M, VT)) {
5907     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5908     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5909       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5910                                   TargetMask, DAG);
5911     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5912       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5913                                   TargetMask, DAG);
5914   }
5915
5916   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5917     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5918       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5919                                   dl, VT, V1, V1, DAG);
5920   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5921     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5922       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5923
5924   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5925   if (VT == MVT::v8i16) {
5926     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5927     if (NewOp.getNode())
5928       return NewOp;
5929   }
5930
5931   if (VT == MVT::v16i8) {
5932     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5933     if (NewOp.getNode())
5934       return NewOp;
5935   }
5936
5937   // Handle all 4 wide cases with a number of shuffles.
5938   if (NumElems == 4)
5939     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5940
5941   return SDValue();
5942 }
5943
5944 SDValue
5945 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5946                                                 SelectionDAG &DAG) const {
5947   EVT VT = Op.getValueType();
5948   DebugLoc dl = Op.getDebugLoc();
5949   if (VT.getSizeInBits() == 8) {
5950     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5951                                     Op.getOperand(0), Op.getOperand(1));
5952     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5953                                     DAG.getValueType(VT));
5954     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5955   } else if (VT.getSizeInBits() == 16) {
5956     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5957     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5958     if (Idx == 0)
5959       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5960                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5961                                      DAG.getNode(ISD::BITCAST, dl,
5962                                                  MVT::v4i32,
5963                                                  Op.getOperand(0)),
5964                                      Op.getOperand(1)));
5965     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5966                                     Op.getOperand(0), Op.getOperand(1));
5967     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5968                                     DAG.getValueType(VT));
5969     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5970   } else if (VT == MVT::f32) {
5971     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5972     // the result back to FR32 register. It's only worth matching if the
5973     // result has a single use which is a store or a bitcast to i32.  And in
5974     // the case of a store, it's not worth it if the index is a constant 0,
5975     // because a MOVSSmr can be used instead, which is smaller and faster.
5976     if (!Op.hasOneUse())
5977       return SDValue();
5978     SDNode *User = *Op.getNode()->use_begin();
5979     if ((User->getOpcode() != ISD::STORE ||
5980          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5981           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5982         (User->getOpcode() != ISD::BITCAST ||
5983          User->getValueType(0) != MVT::i32))
5984       return SDValue();
5985     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5986                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5987                                               Op.getOperand(0)),
5988                                               Op.getOperand(1));
5989     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5990   } else if (VT == MVT::i32) {
5991     // ExtractPS works with constant index.
5992     if (isa<ConstantSDNode>(Op.getOperand(1)))
5993       return Op;
5994   }
5995   return SDValue();
5996 }
5997
5998
5999 SDValue
6000 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6001                                            SelectionDAG &DAG) const {
6002   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6003     return SDValue();
6004
6005   SDValue Vec = Op.getOperand(0);
6006   EVT VecVT = Vec.getValueType();
6007
6008   // If this is a 256-bit vector result, first extract the 128-bit
6009   // vector and then extract from the 128-bit vector.
6010   if (VecVT.getSizeInBits() > 128) {
6011     DebugLoc dl = Op.getNode()->getDebugLoc();
6012     unsigned NumElems = VecVT.getVectorNumElements();
6013     SDValue Idx = Op.getOperand(1);
6014
6015     if (!isa<ConstantSDNode>(Idx))
6016       return SDValue();
6017
6018     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6019     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6020
6021     // Get the 128-bit vector.
6022     bool Upper = IdxVal >= ExtractNumElems;
6023     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6024
6025     // Extract from it.
6026     SDValue ScaledIdx = Idx;
6027     if (Upper)
6028       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6029                               DAG.getConstant(ExtractNumElems,
6030                                               Idx.getValueType()));
6031     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6032                        ScaledIdx);
6033   }
6034
6035   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6036
6037   if (Subtarget->hasSSE41()) {
6038     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6039     if (Res.getNode())
6040       return Res;
6041   }
6042
6043   EVT VT = Op.getValueType();
6044   DebugLoc dl = Op.getDebugLoc();
6045   // TODO: handle v16i8.
6046   if (VT.getSizeInBits() == 16) {
6047     SDValue Vec = Op.getOperand(0);
6048     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6049     if (Idx == 0)
6050       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6051                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6052                                      DAG.getNode(ISD::BITCAST, dl,
6053                                                  MVT::v4i32, Vec),
6054                                      Op.getOperand(1)));
6055     // Transform it so it match pextrw which produces a 32-bit result.
6056     EVT EltVT = MVT::i32;
6057     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6058                                     Op.getOperand(0), Op.getOperand(1));
6059     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6060                                     DAG.getValueType(VT));
6061     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6062   } else if (VT.getSizeInBits() == 32) {
6063     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6064     if (Idx == 0)
6065       return Op;
6066
6067     // SHUFPS the element to the lowest double word, then movss.
6068     int Mask[4] = { Idx, -1, -1, -1 };
6069     EVT VVT = Op.getOperand(0).getValueType();
6070     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6071                                        DAG.getUNDEF(VVT), Mask);
6072     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6073                        DAG.getIntPtrConstant(0));
6074   } else if (VT.getSizeInBits() == 64) {
6075     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6076     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6077     //        to match extract_elt for f64.
6078     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6079     if (Idx == 0)
6080       return Op;
6081
6082     // UNPCKHPD the element to the lowest double word, then movsd.
6083     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6084     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6085     int Mask[2] = { 1, -1 };
6086     EVT VVT = Op.getOperand(0).getValueType();
6087     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6088                                        DAG.getUNDEF(VVT), Mask);
6089     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6090                        DAG.getIntPtrConstant(0));
6091   }
6092
6093   return SDValue();
6094 }
6095
6096 SDValue
6097 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6098                                                SelectionDAG &DAG) const {
6099   EVT VT = Op.getValueType();
6100   EVT EltVT = VT.getVectorElementType();
6101   DebugLoc dl = Op.getDebugLoc();
6102
6103   SDValue N0 = Op.getOperand(0);
6104   SDValue N1 = Op.getOperand(1);
6105   SDValue N2 = Op.getOperand(2);
6106
6107   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6108       isa<ConstantSDNode>(N2)) {
6109     unsigned Opc;
6110     if (VT == MVT::v8i16)
6111       Opc = X86ISD::PINSRW;
6112     else if (VT == MVT::v16i8)
6113       Opc = X86ISD::PINSRB;
6114     else
6115       Opc = X86ISD::PINSRB;
6116
6117     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6118     // argument.
6119     if (N1.getValueType() != MVT::i32)
6120       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6121     if (N2.getValueType() != MVT::i32)
6122       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6123     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6124   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6125     // Bits [7:6] of the constant are the source select.  This will always be
6126     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6127     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6128     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6129     // Bits [5:4] of the constant are the destination select.  This is the
6130     //  value of the incoming immediate.
6131     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6132     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6133     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6134     // Create this as a scalar to vector..
6135     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6136     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6137   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6138     // PINSR* works with constant index.
6139     return Op;
6140   }
6141   return SDValue();
6142 }
6143
6144 SDValue
6145 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6146   EVT VT = Op.getValueType();
6147   EVT EltVT = VT.getVectorElementType();
6148
6149   DebugLoc dl = Op.getDebugLoc();
6150   SDValue N0 = Op.getOperand(0);
6151   SDValue N1 = Op.getOperand(1);
6152   SDValue N2 = Op.getOperand(2);
6153
6154   // If this is a 256-bit vector result, first insert into a 128-bit
6155   // vector and then insert into the 256-bit vector.
6156   if (VT.getSizeInBits() > 128) {
6157     if (!isa<ConstantSDNode>(N2))
6158       return SDValue();
6159
6160     // Get the 128-bit vector.
6161     unsigned NumElems = VT.getVectorNumElements();
6162     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6163     bool Upper = IdxVal >= NumElems / 2;
6164
6165     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6166
6167     // Insert into it.
6168     SDValue ScaledN2 = N2;
6169     if (Upper)
6170       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6171                              DAG.getConstant(NumElems /
6172                                              (VT.getSizeInBits() / 128),
6173                                              N2.getValueType()));
6174     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6175                      N1, ScaledN2);
6176
6177     // Insert the 128-bit vector
6178     // FIXME: Why UNDEF?
6179     return Insert128BitVector(N0, Op, N2, DAG, dl);
6180   }
6181
6182   if (Subtarget->hasSSE41())
6183     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6184
6185   if (EltVT == MVT::i8)
6186     return SDValue();
6187
6188   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6189     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6190     // as its second argument.
6191     if (N1.getValueType() != MVT::i32)
6192       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6193     if (N2.getValueType() != MVT::i32)
6194       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6195     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6196   }
6197   return SDValue();
6198 }
6199
6200 SDValue
6201 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6202   LLVMContext *Context = DAG.getContext();
6203   DebugLoc dl = Op.getDebugLoc();
6204   EVT OpVT = Op.getValueType();
6205
6206   // If this is a 256-bit vector result, first insert into a 128-bit
6207   // vector and then insert into the 256-bit vector.
6208   if (OpVT.getSizeInBits() > 128) {
6209     // Insert into a 128-bit vector.
6210     EVT VT128 = EVT::getVectorVT(*Context,
6211                                  OpVT.getVectorElementType(),
6212                                  OpVT.getVectorNumElements() / 2);
6213
6214     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6215
6216     // Insert the 128-bit vector.
6217     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6218                               DAG.getConstant(0, MVT::i32),
6219                               DAG, dl);
6220   }
6221
6222   if (Op.getValueType() == MVT::v1i64 &&
6223       Op.getOperand(0).getValueType() == MVT::i64)
6224     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6225
6226   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6227   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6228          "Expected an SSE type!");
6229   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6230                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6231 }
6232
6233 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6234 // a simple subregister reference or explicit instructions to grab
6235 // upper bits of a vector.
6236 SDValue
6237 X86TargetLowering::LowerEXTRACT_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 Idx = Op.getNode()->getOperand(1);
6242
6243     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6244         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6245         return Extract128BitVector(Vec, Idx, DAG, dl);
6246     }
6247   }
6248   return SDValue();
6249 }
6250
6251 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6252 // simple superregister reference or explicit instructions to insert
6253 // the upper bits of a vector.
6254 SDValue
6255 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6256   if (Subtarget->hasAVX()) {
6257     DebugLoc dl = Op.getNode()->getDebugLoc();
6258     SDValue Vec = Op.getNode()->getOperand(0);
6259     SDValue SubVec = Op.getNode()->getOperand(1);
6260     SDValue Idx = Op.getNode()->getOperand(2);
6261
6262     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6263         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6264       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6265     }
6266   }
6267   return SDValue();
6268 }
6269
6270 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6271 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6272 // one of the above mentioned nodes. It has to be wrapped because otherwise
6273 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6274 // be used to form addressing mode. These wrapped nodes will be selected
6275 // into MOV32ri.
6276 SDValue
6277 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6278   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6279
6280   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6281   // global base reg.
6282   unsigned char OpFlag = 0;
6283   unsigned WrapperKind = X86ISD::Wrapper;
6284   CodeModel::Model M = getTargetMachine().getCodeModel();
6285
6286   if (Subtarget->isPICStyleRIPRel() &&
6287       (M == CodeModel::Small || M == CodeModel::Kernel))
6288     WrapperKind = X86ISD::WrapperRIP;
6289   else if (Subtarget->isPICStyleGOT())
6290     OpFlag = X86II::MO_GOTOFF;
6291   else if (Subtarget->isPICStyleStubPIC())
6292     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6293
6294   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6295                                              CP->getAlignment(),
6296                                              CP->getOffset(), OpFlag);
6297   DebugLoc DL = CP->getDebugLoc();
6298   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6299   // With PIC, the address is actually $g + Offset.
6300   if (OpFlag) {
6301     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6302                          DAG.getNode(X86ISD::GlobalBaseReg,
6303                                      DebugLoc(), getPointerTy()),
6304                          Result);
6305   }
6306
6307   return Result;
6308 }
6309
6310 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6311   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6312
6313   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6314   // global base reg.
6315   unsigned char OpFlag = 0;
6316   unsigned WrapperKind = X86ISD::Wrapper;
6317   CodeModel::Model M = getTargetMachine().getCodeModel();
6318
6319   if (Subtarget->isPICStyleRIPRel() &&
6320       (M == CodeModel::Small || M == CodeModel::Kernel))
6321     WrapperKind = X86ISD::WrapperRIP;
6322   else if (Subtarget->isPICStyleGOT())
6323     OpFlag = X86II::MO_GOTOFF;
6324   else if (Subtarget->isPICStyleStubPIC())
6325     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6326
6327   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6328                                           OpFlag);
6329   DebugLoc DL = JT->getDebugLoc();
6330   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6331
6332   // With PIC, the address is actually $g + Offset.
6333   if (OpFlag)
6334     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6335                          DAG.getNode(X86ISD::GlobalBaseReg,
6336                                      DebugLoc(), getPointerTy()),
6337                          Result);
6338
6339   return Result;
6340 }
6341
6342 SDValue
6343 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6344   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6345
6346   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6347   // global base reg.
6348   unsigned char OpFlag = 0;
6349   unsigned WrapperKind = X86ISD::Wrapper;
6350   CodeModel::Model M = getTargetMachine().getCodeModel();
6351
6352   if (Subtarget->isPICStyleRIPRel() &&
6353       (M == CodeModel::Small || M == CodeModel::Kernel))
6354     WrapperKind = X86ISD::WrapperRIP;
6355   else if (Subtarget->isPICStyleGOT())
6356     OpFlag = X86II::MO_GOTOFF;
6357   else if (Subtarget->isPICStyleStubPIC())
6358     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6359
6360   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6361
6362   DebugLoc DL = Op.getDebugLoc();
6363   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6364
6365
6366   // With PIC, the address is actually $g + Offset.
6367   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6368       !Subtarget->is64Bit()) {
6369     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6370                          DAG.getNode(X86ISD::GlobalBaseReg,
6371                                      DebugLoc(), getPointerTy()),
6372                          Result);
6373   }
6374
6375   return Result;
6376 }
6377
6378 SDValue
6379 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6380   // Create the TargetBlockAddressAddress node.
6381   unsigned char OpFlags =
6382     Subtarget->ClassifyBlockAddressReference();
6383   CodeModel::Model M = getTargetMachine().getCodeModel();
6384   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6385   DebugLoc dl = Op.getDebugLoc();
6386   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6387                                        /*isTarget=*/true, OpFlags);
6388
6389   if (Subtarget->isPICStyleRIPRel() &&
6390       (M == CodeModel::Small || M == CodeModel::Kernel))
6391     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6392   else
6393     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6394
6395   // With PIC, the address is actually $g + Offset.
6396   if (isGlobalRelativeToPICBase(OpFlags)) {
6397     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6398                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6399                          Result);
6400   }
6401
6402   return Result;
6403 }
6404
6405 SDValue
6406 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6407                                       int64_t Offset,
6408                                       SelectionDAG &DAG) const {
6409   // Create the TargetGlobalAddress node, folding in the constant
6410   // offset if it is legal.
6411   unsigned char OpFlags =
6412     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6413   CodeModel::Model M = getTargetMachine().getCodeModel();
6414   SDValue Result;
6415   if (OpFlags == X86II::MO_NO_FLAG &&
6416       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6417     // A direct static reference to a global.
6418     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6419     Offset = 0;
6420   } else {
6421     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6422   }
6423
6424   if (Subtarget->isPICStyleRIPRel() &&
6425       (M == CodeModel::Small || M == CodeModel::Kernel))
6426     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6427   else
6428     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6429
6430   // With PIC, the address is actually $g + Offset.
6431   if (isGlobalRelativeToPICBase(OpFlags)) {
6432     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6433                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6434                          Result);
6435   }
6436
6437   // For globals that require a load from a stub to get the address, emit the
6438   // load.
6439   if (isGlobalStubReference(OpFlags))
6440     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6441                          MachinePointerInfo::getGOT(), false, false, 0);
6442
6443   // If there was a non-zero offset that we didn't fold, create an explicit
6444   // addition for it.
6445   if (Offset != 0)
6446     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6447                          DAG.getConstant(Offset, getPointerTy()));
6448
6449   return Result;
6450 }
6451
6452 SDValue
6453 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6454   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6455   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6456   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6457 }
6458
6459 static SDValue
6460 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6461            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6462            unsigned char OperandFlags) {
6463   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6464   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6465   DebugLoc dl = GA->getDebugLoc();
6466   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6467                                            GA->getValueType(0),
6468                                            GA->getOffset(),
6469                                            OperandFlags);
6470   if (InFlag) {
6471     SDValue Ops[] = { Chain,  TGA, *InFlag };
6472     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6473   } else {
6474     SDValue Ops[]  = { Chain, TGA };
6475     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6476   }
6477
6478   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6479   MFI->setAdjustsStack(true);
6480
6481   SDValue Flag = Chain.getValue(1);
6482   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6483 }
6484
6485 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6486 static SDValue
6487 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6488                                 const EVT PtrVT) {
6489   SDValue InFlag;
6490   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6491   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6492                                      DAG.getNode(X86ISD::GlobalBaseReg,
6493                                                  DebugLoc(), PtrVT), InFlag);
6494   InFlag = Chain.getValue(1);
6495
6496   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6497 }
6498
6499 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6500 static SDValue
6501 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6502                                 const EVT PtrVT) {
6503   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6504                     X86::RAX, X86II::MO_TLSGD);
6505 }
6506
6507 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6508 // "local exec" model.
6509 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6510                                    const EVT PtrVT, TLSModel::Model model,
6511                                    bool is64Bit) {
6512   DebugLoc dl = GA->getDebugLoc();
6513
6514   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6515   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6516                                                          is64Bit ? 257 : 256));
6517
6518   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6519                                       DAG.getIntPtrConstant(0),
6520                                       MachinePointerInfo(Ptr), false, false, 0);
6521
6522   unsigned char OperandFlags = 0;
6523   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6524   // initialexec.
6525   unsigned WrapperKind = X86ISD::Wrapper;
6526   if (model == TLSModel::LocalExec) {
6527     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6528   } else if (is64Bit) {
6529     assert(model == TLSModel::InitialExec);
6530     OperandFlags = X86II::MO_GOTTPOFF;
6531     WrapperKind = X86ISD::WrapperRIP;
6532   } else {
6533     assert(model == TLSModel::InitialExec);
6534     OperandFlags = X86II::MO_INDNTPOFF;
6535   }
6536
6537   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6538   // exec)
6539   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6540                                            GA->getValueType(0),
6541                                            GA->getOffset(), OperandFlags);
6542   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6543
6544   if (model == TLSModel::InitialExec)
6545     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6546                          MachinePointerInfo::getGOT(), false, false, 0);
6547
6548   // The address of the thread local variable is the add of the thread
6549   // pointer with the offset of the variable.
6550   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6551 }
6552
6553 SDValue
6554 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6555
6556   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6557   const GlobalValue *GV = GA->getGlobal();
6558
6559   if (Subtarget->isTargetELF()) {
6560     // TODO: implement the "local dynamic" model
6561     // TODO: implement the "initial exec"model for pic executables
6562
6563     // If GV is an alias then use the aliasee for determining
6564     // thread-localness.
6565     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6566       GV = GA->resolveAliasedGlobal(false);
6567
6568     TLSModel::Model model
6569       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6570
6571     switch (model) {
6572       case TLSModel::GeneralDynamic:
6573       case TLSModel::LocalDynamic: // not implemented
6574         if (Subtarget->is64Bit())
6575           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6576         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6577
6578       case TLSModel::InitialExec:
6579       case TLSModel::LocalExec:
6580         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6581                                    Subtarget->is64Bit());
6582     }
6583   } else if (Subtarget->isTargetDarwin()) {
6584     // Darwin only has one model of TLS.  Lower to that.
6585     unsigned char OpFlag = 0;
6586     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6587                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6588
6589     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6590     // global base reg.
6591     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6592                   !Subtarget->is64Bit();
6593     if (PIC32)
6594       OpFlag = X86II::MO_TLVP_PIC_BASE;
6595     else
6596       OpFlag = X86II::MO_TLVP;
6597     DebugLoc DL = Op.getDebugLoc();
6598     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6599                                                 GA->getValueType(0),
6600                                                 GA->getOffset(), OpFlag);
6601     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6602
6603     // With PIC32, the address is actually $g + Offset.
6604     if (PIC32)
6605       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6606                            DAG.getNode(X86ISD::GlobalBaseReg,
6607                                        DebugLoc(), getPointerTy()),
6608                            Offset);
6609
6610     // Lowering the machine isd will make sure everything is in the right
6611     // location.
6612     SDValue Chain = DAG.getEntryNode();
6613     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6614     SDValue Args[] = { Chain, Offset };
6615     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6616
6617     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6618     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6619     MFI->setAdjustsStack(true);
6620
6621     // And our return value (tls address) is in the standard call return value
6622     // location.
6623     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6624     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6625   }
6626
6627   assert(false &&
6628          "TLS not implemented for this target.");
6629
6630   llvm_unreachable("Unreachable");
6631   return SDValue();
6632 }
6633
6634
6635 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6636 /// take a 2 x i32 value to shift plus a shift amount.
6637 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6638   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6639   EVT VT = Op.getValueType();
6640   unsigned VTBits = VT.getSizeInBits();
6641   DebugLoc dl = Op.getDebugLoc();
6642   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6643   SDValue ShOpLo = Op.getOperand(0);
6644   SDValue ShOpHi = Op.getOperand(1);
6645   SDValue ShAmt  = Op.getOperand(2);
6646   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6647                                      DAG.getConstant(VTBits - 1, MVT::i8))
6648                        : DAG.getConstant(0, VT);
6649
6650   SDValue Tmp2, Tmp3;
6651   if (Op.getOpcode() == ISD::SHL_PARTS) {
6652     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6653     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6654   } else {
6655     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6656     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6657   }
6658
6659   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6660                                 DAG.getConstant(VTBits, MVT::i8));
6661   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6662                              AndNode, DAG.getConstant(0, MVT::i8));
6663
6664   SDValue Hi, Lo;
6665   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6666   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6667   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6668
6669   if (Op.getOpcode() == ISD::SHL_PARTS) {
6670     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6671     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6672   } else {
6673     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6674     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6675   }
6676
6677   SDValue Ops[2] = { Lo, Hi };
6678   return DAG.getMergeValues(Ops, 2, dl);
6679 }
6680
6681 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6682                                            SelectionDAG &DAG) const {
6683   EVT SrcVT = Op.getOperand(0).getValueType();
6684
6685   if (SrcVT.isVector())
6686     return SDValue();
6687
6688   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6689          "Unknown SINT_TO_FP to lower!");
6690
6691   // These are really Legal; return the operand so the caller accepts it as
6692   // Legal.
6693   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6694     return Op;
6695   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6696       Subtarget->is64Bit()) {
6697     return Op;
6698   }
6699
6700   DebugLoc dl = Op.getDebugLoc();
6701   unsigned Size = SrcVT.getSizeInBits()/8;
6702   MachineFunction &MF = DAG.getMachineFunction();
6703
6704   SDValue Addr = Op.getOperand(0);
6705   if (Addr.getOpcode() == ISD::LOAD)
6706     return BuildFILD(Op, SrcVT, DAG.getEntryNode(), Addr, DAG);
6707
6708   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6709   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6710   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6711                                StackSlot,
6712                                MachinePointerInfo::getFixedStack(SSFI),
6713                                false, false, 0);
6714   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6715 }
6716
6717 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6718                                      SDValue StackSlot,
6719                                      SelectionDAG &DAG) const {
6720   // Build the FILD
6721   DebugLoc DL = Op.getDebugLoc();
6722   SDVTList Tys;
6723   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6724   if (useSSE)
6725     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6726   else
6727     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6728
6729   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6730
6731   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6732   MachineMemOperand *MMO;
6733   if (FI) {
6734     int SSFI = FI->getIndex();
6735     MMO =
6736       DAG.getMachineFunction()
6737       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6738                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6739   } else {
6740     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6741     StackSlot = StackSlot.getOperand(1);
6742   }
6743   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6744   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6745                                            X86ISD::FILD, DL,
6746                                            Tys, Ops, array_lengthof(Ops),
6747                                            SrcVT, MMO);
6748
6749   if (useSSE) {
6750     Chain = Result.getValue(1);
6751     SDValue InFlag = Result.getValue(2);
6752
6753     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6754     // shouldn't be necessary except that RFP cannot be live across
6755     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6756     MachineFunction &MF = DAG.getMachineFunction();
6757     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6758     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6759     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6760     Tys = DAG.getVTList(MVT::Other);
6761     SDValue Ops[] = {
6762       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6763     };
6764     MachineMemOperand *MMO =
6765       DAG.getMachineFunction()
6766       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6767                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6768
6769     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6770                                     Ops, array_lengthof(Ops),
6771                                     Op.getValueType(), MMO);
6772     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6773                          MachinePointerInfo::getFixedStack(SSFI),
6774                          false, false, 0);
6775   }
6776
6777   return Result;
6778 }
6779
6780 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6781 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6782                                                SelectionDAG &DAG) const {
6783   // This algorithm is not obvious. Here it is in C code, more or less:
6784   /*
6785     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6786       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6787       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6788
6789       // Copy ints to xmm registers.
6790       __m128i xh = _mm_cvtsi32_si128( hi );
6791       __m128i xl = _mm_cvtsi32_si128( lo );
6792
6793       // Combine into low half of a single xmm register.
6794       __m128i x = _mm_unpacklo_epi32( xh, xl );
6795       __m128d d;
6796       double sd;
6797
6798       // Merge in appropriate exponents to give the integer bits the right
6799       // magnitude.
6800       x = _mm_unpacklo_epi32( x, exp );
6801
6802       // Subtract away the biases to deal with the IEEE-754 double precision
6803       // implicit 1.
6804       d = _mm_sub_pd( (__m128d) x, bias );
6805
6806       // All conversions up to here are exact. The correctly rounded result is
6807       // calculated using the current rounding mode using the following
6808       // horizontal add.
6809       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6810       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6811                                 // store doesn't really need to be here (except
6812                                 // maybe to zero the other double)
6813       return sd;
6814     }
6815   */
6816
6817   DebugLoc dl = Op.getDebugLoc();
6818   LLVMContext *Context = DAG.getContext();
6819
6820   // Build some magic constants.
6821   std::vector<Constant*> CV0;
6822   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6823   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6824   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6825   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6826   Constant *C0 = ConstantVector::get(CV0);
6827   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6828
6829   std::vector<Constant*> CV1;
6830   CV1.push_back(
6831     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6832   CV1.push_back(
6833     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6834   Constant *C1 = ConstantVector::get(CV1);
6835   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6836
6837   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6838                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6839                                         Op.getOperand(0),
6840                                         DAG.getIntPtrConstant(1)));
6841   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6842                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6843                                         Op.getOperand(0),
6844                                         DAG.getIntPtrConstant(0)));
6845   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6846   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6847                               MachinePointerInfo::getConstantPool(),
6848                               false, false, 16);
6849   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6850   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6851   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6852                               MachinePointerInfo::getConstantPool(),
6853                               false, false, 16);
6854   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6855
6856   // Add the halves; easiest way is to swap them into another reg first.
6857   int ShufMask[2] = { 1, -1 };
6858   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6859                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6860   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6861   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6862                      DAG.getIntPtrConstant(0));
6863 }
6864
6865 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6866 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6867                                                SelectionDAG &DAG) const {
6868   DebugLoc dl = Op.getDebugLoc();
6869   // FP constant to bias correct the final result.
6870   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6871                                    MVT::f64);
6872
6873   // Load the 32-bit value into an XMM register.
6874   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6875                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6876                                          Op.getOperand(0),
6877                                          DAG.getIntPtrConstant(0)));
6878
6879   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6880                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6881                      DAG.getIntPtrConstant(0));
6882
6883   // Or the load with the bias.
6884   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6885                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6886                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6887                                                    MVT::v2f64, Load)),
6888                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6889                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6890                                                    MVT::v2f64, Bias)));
6891   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6892                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6893                    DAG.getIntPtrConstant(0));
6894
6895   // Subtract the bias.
6896   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6897
6898   // Handle final rounding.
6899   EVT DestVT = Op.getValueType();
6900
6901   if (DestVT.bitsLT(MVT::f64)) {
6902     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6903                        DAG.getIntPtrConstant(0));
6904   } else if (DestVT.bitsGT(MVT::f64)) {
6905     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6906   }
6907
6908   // Handle final rounding.
6909   return Sub;
6910 }
6911
6912 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6913                                            SelectionDAG &DAG) const {
6914   SDValue N0 = Op.getOperand(0);
6915   DebugLoc dl = Op.getDebugLoc();
6916
6917   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6918   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6919   // the optimization here.
6920   if (DAG.SignBitIsZero(N0))
6921     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6922
6923   EVT SrcVT = N0.getValueType();
6924   EVT DstVT = Op.getValueType();
6925   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6926     return LowerUINT_TO_FP_i64(Op, DAG);
6927   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6928     return LowerUINT_TO_FP_i32(Op, DAG);
6929
6930   // Make a 64-bit buffer, and use it to build an FILD.
6931   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6932   if (SrcVT == MVT::i32) {
6933     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6934     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6935                                      getPointerTy(), StackSlot, WordOff);
6936     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6937                                   StackSlot, MachinePointerInfo(),
6938                                   false, false, 0);
6939     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6940                                   OffsetSlot, MachinePointerInfo(),
6941                                   false, false, 0);
6942     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6943     return Fild;
6944   }
6945
6946   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6947   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6948                                 StackSlot, MachinePointerInfo(),
6949                                false, false, 0);
6950   // For i64 source, we need to add the appropriate power of 2 if the input
6951   // was negative.  This is the same as the optimization in
6952   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6953   // we must be careful to do the computation in x87 extended precision, not
6954   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6955   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6956   MachineMemOperand *MMO =
6957     DAG.getMachineFunction()
6958     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6959                           MachineMemOperand::MOLoad, 8, 8);
6960
6961   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6962   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6963   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6964                                          MVT::i64, MMO);
6965
6966   APInt FF(32, 0x5F800000ULL);
6967
6968   // Check whether the sign bit is set.
6969   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6970                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6971                                  ISD::SETLT);
6972
6973   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6974   SDValue FudgePtr = DAG.getConstantPool(
6975                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6976                                          getPointerTy());
6977
6978   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6979   SDValue Zero = DAG.getIntPtrConstant(0);
6980   SDValue Four = DAG.getIntPtrConstant(4);
6981   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6982                                Zero, Four);
6983   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6984
6985   // Load the value out, extending it from f32 to f80.
6986   // FIXME: Avoid the extend by constructing the right constant pool?
6987   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6988                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6989                                  MVT::f32, false, false, 4);
6990   // Extend everything to 80 bits to force it to be done on x87.
6991   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6992   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6993 }
6994
6995 std::pair<SDValue,SDValue> X86TargetLowering::
6996 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6997   DebugLoc DL = Op.getDebugLoc();
6998
6999   EVT DstTy = Op.getValueType();
7000
7001   if (!IsSigned) {
7002     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7003     DstTy = MVT::i64;
7004   }
7005
7006   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7007          DstTy.getSimpleVT() >= MVT::i16 &&
7008          "Unknown FP_TO_SINT to lower!");
7009
7010   // These are really Legal.
7011   if (DstTy == MVT::i32 &&
7012       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7013     return std::make_pair(SDValue(), SDValue());
7014   if (Subtarget->is64Bit() &&
7015       DstTy == MVT::i64 &&
7016       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7017     return std::make_pair(SDValue(), SDValue());
7018
7019   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7020   // stack slot.
7021   MachineFunction &MF = DAG.getMachineFunction();
7022   unsigned MemSize = DstTy.getSizeInBits()/8;
7023   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7024   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7025
7026
7027
7028   unsigned Opc;
7029   switch (DstTy.getSimpleVT().SimpleTy) {
7030   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7031   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7032   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7033   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7034   }
7035
7036   SDValue Chain = DAG.getEntryNode();
7037   SDValue Value = Op.getOperand(0);
7038   EVT TheVT = Op.getOperand(0).getValueType();
7039   if (isScalarFPTypeInSSEReg(TheVT)) {
7040     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7041     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7042                          MachinePointerInfo::getFixedStack(SSFI),
7043                          false, false, 0);
7044     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7045     SDValue Ops[] = {
7046       Chain, StackSlot, DAG.getValueType(TheVT)
7047     };
7048
7049     MachineMemOperand *MMO =
7050       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7051                               MachineMemOperand::MOLoad, MemSize, MemSize);
7052     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7053                                     DstTy, MMO);
7054     Chain = Value.getValue(1);
7055     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7056     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7057   }
7058
7059   MachineMemOperand *MMO =
7060     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7061                             MachineMemOperand::MOStore, MemSize, MemSize);
7062
7063   // Build the FP_TO_INT*_IN_MEM
7064   SDValue Ops[] = { Chain, Value, StackSlot };
7065   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7066                                          Ops, 3, DstTy, MMO);
7067
7068   return std::make_pair(FIST, StackSlot);
7069 }
7070
7071 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7072                                            SelectionDAG &DAG) const {
7073   if (Op.getValueType().isVector())
7074     return SDValue();
7075
7076   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7077   SDValue FIST = Vals.first, StackSlot = Vals.second;
7078   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7079   if (FIST.getNode() == 0) return Op;
7080
7081   // Load the result.
7082   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7083                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7084 }
7085
7086 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7087                                            SelectionDAG &DAG) const {
7088   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7089   SDValue FIST = Vals.first, StackSlot = Vals.second;
7090   assert(FIST.getNode() && "Unexpected failure");
7091
7092   // Load the result.
7093   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7094                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7095 }
7096
7097 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7098                                      SelectionDAG &DAG) const {
7099   LLVMContext *Context = DAG.getContext();
7100   DebugLoc dl = Op.getDebugLoc();
7101   EVT VT = Op.getValueType();
7102   EVT EltVT = VT;
7103   if (VT.isVector())
7104     EltVT = VT.getVectorElementType();
7105   std::vector<Constant*> CV;
7106   if (EltVT == MVT::f64) {
7107     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7108     CV.push_back(C);
7109     CV.push_back(C);
7110   } else {
7111     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7112     CV.push_back(C);
7113     CV.push_back(C);
7114     CV.push_back(C);
7115     CV.push_back(C);
7116   }
7117   Constant *C = ConstantVector::get(CV);
7118   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7119   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7120                              MachinePointerInfo::getConstantPool(),
7121                              false, false, 16);
7122   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7123 }
7124
7125 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7126   LLVMContext *Context = DAG.getContext();
7127   DebugLoc dl = Op.getDebugLoc();
7128   EVT VT = Op.getValueType();
7129   EVT EltVT = VT;
7130   if (VT.isVector())
7131     EltVT = VT.getVectorElementType();
7132   std::vector<Constant*> CV;
7133   if (EltVT == MVT::f64) {
7134     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7135     CV.push_back(C);
7136     CV.push_back(C);
7137   } else {
7138     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7139     CV.push_back(C);
7140     CV.push_back(C);
7141     CV.push_back(C);
7142     CV.push_back(C);
7143   }
7144   Constant *C = ConstantVector::get(CV);
7145   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7146   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7147                              MachinePointerInfo::getConstantPool(),
7148                              false, false, 16);
7149   if (VT.isVector()) {
7150     return DAG.getNode(ISD::BITCAST, dl, VT,
7151                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7152                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7153                                 Op.getOperand(0)),
7154                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7155   } else {
7156     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7157   }
7158 }
7159
7160 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7161   LLVMContext *Context = DAG.getContext();
7162   SDValue Op0 = Op.getOperand(0);
7163   SDValue Op1 = Op.getOperand(1);
7164   DebugLoc dl = Op.getDebugLoc();
7165   EVT VT = Op.getValueType();
7166   EVT SrcVT = Op1.getValueType();
7167
7168   // If second operand is smaller, extend it first.
7169   if (SrcVT.bitsLT(VT)) {
7170     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7171     SrcVT = VT;
7172   }
7173   // And if it is bigger, shrink it first.
7174   if (SrcVT.bitsGT(VT)) {
7175     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7176     SrcVT = VT;
7177   }
7178
7179   // At this point the operands and the result should have the same
7180   // type, and that won't be f80 since that is not custom lowered.
7181
7182   // First get the sign bit of second operand.
7183   std::vector<Constant*> CV;
7184   if (SrcVT == 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   Constant *C = ConstantVector::get(CV);
7194   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7195   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7196                               MachinePointerInfo::getConstantPool(),
7197                               false, false, 16);
7198   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7199
7200   // Shift sign bit right or left if the two operands have different types.
7201   if (SrcVT.bitsGT(VT)) {
7202     // Op0 is MVT::f32, Op1 is MVT::f64.
7203     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7204     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7205                           DAG.getConstant(32, MVT::i32));
7206     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7207     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7208                           DAG.getIntPtrConstant(0));
7209   }
7210
7211   // Clear first operand sign bit.
7212   CV.clear();
7213   if (VT == MVT::f64) {
7214     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7215     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7216   } else {
7217     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7218     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7219     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7220     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7221   }
7222   C = ConstantVector::get(CV);
7223   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7224   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7225                               MachinePointerInfo::getConstantPool(),
7226                               false, false, 16);
7227   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7228
7229   // Or the value with the sign bit.
7230   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7231 }
7232
7233 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7234   SDValue N0 = Op.getOperand(0);
7235   DebugLoc dl = Op.getDebugLoc();
7236   EVT VT = Op.getValueType();
7237
7238   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7239   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7240                                   DAG.getConstant(1, VT));
7241   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7242 }
7243
7244 /// Emit nodes that will be selected as "test Op0,Op0", or something
7245 /// equivalent.
7246 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7247                                     SelectionDAG &DAG) const {
7248   DebugLoc dl = Op.getDebugLoc();
7249
7250   // CF and OF aren't always set the way we want. Determine which
7251   // of these we need.
7252   bool NeedCF = false;
7253   bool NeedOF = false;
7254   switch (X86CC) {
7255   default: break;
7256   case X86::COND_A: case X86::COND_AE:
7257   case X86::COND_B: case X86::COND_BE:
7258     NeedCF = true;
7259     break;
7260   case X86::COND_G: case X86::COND_GE:
7261   case X86::COND_L: case X86::COND_LE:
7262   case X86::COND_O: case X86::COND_NO:
7263     NeedOF = true;
7264     break;
7265   }
7266
7267   // See if we can use the EFLAGS value from the operand instead of
7268   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7269   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7270   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7271     // Emit a CMP with 0, which is the TEST pattern.
7272     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7273                        DAG.getConstant(0, Op.getValueType()));
7274
7275   unsigned Opcode = 0;
7276   unsigned NumOperands = 0;
7277   switch (Op.getNode()->getOpcode()) {
7278   case ISD::ADD:
7279     // Due to an isel shortcoming, be conservative if this add is likely to be
7280     // selected as part of a load-modify-store instruction. When the root node
7281     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7282     // uses of other nodes in the match, such as the ADD in this case. This
7283     // leads to the ADD being left around and reselected, with the result being
7284     // two adds in the output.  Alas, even if none our users are stores, that
7285     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7286     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7287     // climbing the DAG back to the root, and it doesn't seem to be worth the
7288     // effort.
7289     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7290            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7291       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7292         goto default_case;
7293
7294     if (ConstantSDNode *C =
7295         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7296       // An add of one will be selected as an INC.
7297       if (C->getAPIntValue() == 1) {
7298         Opcode = X86ISD::INC;
7299         NumOperands = 1;
7300         break;
7301       }
7302
7303       // An add of negative one (subtract of one) will be selected as a DEC.
7304       if (C->getAPIntValue().isAllOnesValue()) {
7305         Opcode = X86ISD::DEC;
7306         NumOperands = 1;
7307         break;
7308       }
7309     }
7310
7311     // Otherwise use a regular EFLAGS-setting add.
7312     Opcode = X86ISD::ADD;
7313     NumOperands = 2;
7314     break;
7315   case ISD::AND: {
7316     // If the primary and result isn't used, don't bother using X86ISD::AND,
7317     // because a TEST instruction will be better.
7318     bool NonFlagUse = false;
7319     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7320            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7321       SDNode *User = *UI;
7322       unsigned UOpNo = UI.getOperandNo();
7323       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7324         // Look pass truncate.
7325         UOpNo = User->use_begin().getOperandNo();
7326         User = *User->use_begin();
7327       }
7328
7329       if (User->getOpcode() != ISD::BRCOND &&
7330           User->getOpcode() != ISD::SETCC &&
7331           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7332         NonFlagUse = true;
7333         break;
7334       }
7335     }
7336
7337     if (!NonFlagUse)
7338       break;
7339   }
7340     // FALL THROUGH
7341   case ISD::SUB:
7342   case ISD::OR:
7343   case ISD::XOR:
7344     // Due to the ISEL shortcoming noted above, be conservative if this op is
7345     // likely to be selected as part of a load-modify-store instruction.
7346     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7347            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7348       if (UI->getOpcode() == ISD::STORE)
7349         goto default_case;
7350
7351     // Otherwise use a regular EFLAGS-setting instruction.
7352     switch (Op.getNode()->getOpcode()) {
7353     default: llvm_unreachable("unexpected operator!");
7354     case ISD::SUB: Opcode = X86ISD::SUB; break;
7355     case ISD::OR:  Opcode = X86ISD::OR;  break;
7356     case ISD::XOR: Opcode = X86ISD::XOR; break;
7357     case ISD::AND: Opcode = X86ISD::AND; break;
7358     }
7359
7360     NumOperands = 2;
7361     break;
7362   case X86ISD::ADD:
7363   case X86ISD::SUB:
7364   case X86ISD::INC:
7365   case X86ISD::DEC:
7366   case X86ISD::OR:
7367   case X86ISD::XOR:
7368   case X86ISD::AND:
7369     return SDValue(Op.getNode(), 1);
7370   default:
7371   default_case:
7372     break;
7373   }
7374
7375   if (Opcode == 0)
7376     // Emit a CMP with 0, which is the TEST pattern.
7377     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7378                        DAG.getConstant(0, Op.getValueType()));
7379
7380   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7381   SmallVector<SDValue, 4> Ops;
7382   for (unsigned i = 0; i != NumOperands; ++i)
7383     Ops.push_back(Op.getOperand(i));
7384
7385   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7386   DAG.ReplaceAllUsesWith(Op, New);
7387   return SDValue(New.getNode(), 1);
7388 }
7389
7390 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7391 /// equivalent.
7392 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7393                                    SelectionDAG &DAG) const {
7394   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7395     if (C->getAPIntValue() == 0)
7396       return EmitTest(Op0, X86CC, DAG);
7397
7398   DebugLoc dl = Op0.getDebugLoc();
7399   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7400 }
7401
7402 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7403 /// if it's possible.
7404 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7405                                      DebugLoc dl, SelectionDAG &DAG) const {
7406   SDValue Op0 = And.getOperand(0);
7407   SDValue Op1 = And.getOperand(1);
7408   if (Op0.getOpcode() == ISD::TRUNCATE)
7409     Op0 = Op0.getOperand(0);
7410   if (Op1.getOpcode() == ISD::TRUNCATE)
7411     Op1 = Op1.getOperand(0);
7412
7413   SDValue LHS, RHS;
7414   if (Op1.getOpcode() == ISD::SHL)
7415     std::swap(Op0, Op1);
7416   if (Op0.getOpcode() == ISD::SHL) {
7417     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7418       if (And00C->getZExtValue() == 1) {
7419         // If we looked past a truncate, check that it's only truncating away
7420         // known zeros.
7421         unsigned BitWidth = Op0.getValueSizeInBits();
7422         unsigned AndBitWidth = And.getValueSizeInBits();
7423         if (BitWidth > AndBitWidth) {
7424           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7425           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7426           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7427             return SDValue();
7428         }
7429         LHS = Op1;
7430         RHS = Op0.getOperand(1);
7431       }
7432   } else if (Op1.getOpcode() == ISD::Constant) {
7433     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7434     SDValue AndLHS = Op0;
7435     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7436       LHS = AndLHS.getOperand(0);
7437       RHS = AndLHS.getOperand(1);
7438     }
7439   }
7440
7441   if (LHS.getNode()) {
7442     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7443     // instruction.  Since the shift amount is in-range-or-undefined, we know
7444     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7445     // the encoding for the i16 version is larger than the i32 version.
7446     // Also promote i16 to i32 for performance / code size reason.
7447     if (LHS.getValueType() == MVT::i8 ||
7448         LHS.getValueType() == MVT::i16)
7449       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7450
7451     // If the operand types disagree, extend the shift amount to match.  Since
7452     // BT ignores high bits (like shifts) we can use anyextend.
7453     if (LHS.getValueType() != RHS.getValueType())
7454       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7455
7456     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7457     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7458     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7459                        DAG.getConstant(Cond, MVT::i8), BT);
7460   }
7461
7462   return SDValue();
7463 }
7464
7465 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7466   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7467   SDValue Op0 = Op.getOperand(0);
7468   SDValue Op1 = Op.getOperand(1);
7469   DebugLoc dl = Op.getDebugLoc();
7470   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7471
7472   // Optimize to BT if possible.
7473   // Lower (X & (1 << N)) == 0 to BT(X, N).
7474   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7475   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7476   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7477       Op1.getOpcode() == ISD::Constant &&
7478       cast<ConstantSDNode>(Op1)->isNullValue() &&
7479       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7480     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7481     if (NewSetCC.getNode())
7482       return NewSetCC;
7483   }
7484
7485   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7486   // these.
7487   if (Op1.getOpcode() == ISD::Constant &&
7488       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7489        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7490       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7491
7492     // If the input is a setcc, then reuse the input setcc or use a new one with
7493     // the inverted condition.
7494     if (Op0.getOpcode() == X86ISD::SETCC) {
7495       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7496       bool Invert = (CC == ISD::SETNE) ^
7497         cast<ConstantSDNode>(Op1)->isNullValue();
7498       if (!Invert) return Op0;
7499
7500       CCode = X86::GetOppositeBranchCondition(CCode);
7501       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7502                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7503     }
7504   }
7505
7506   bool isFP = Op1.getValueType().isFloatingPoint();
7507   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7508   if (X86CC == X86::COND_INVALID)
7509     return SDValue();
7510
7511   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7512   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7513                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7514 }
7515
7516 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7517   SDValue Cond;
7518   SDValue Op0 = Op.getOperand(0);
7519   SDValue Op1 = Op.getOperand(1);
7520   SDValue CC = Op.getOperand(2);
7521   EVT VT = Op.getValueType();
7522   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7523   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7524   DebugLoc dl = Op.getDebugLoc();
7525
7526   if (isFP) {
7527     unsigned SSECC = 8;
7528     EVT VT0 = Op0.getValueType();
7529     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7530     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7531     bool Swap = false;
7532
7533     switch (SetCCOpcode) {
7534     default: break;
7535     case ISD::SETOEQ:
7536     case ISD::SETEQ:  SSECC = 0; break;
7537     case ISD::SETOGT:
7538     case ISD::SETGT: Swap = true; // Fallthrough
7539     case ISD::SETLT:
7540     case ISD::SETOLT: SSECC = 1; break;
7541     case ISD::SETOGE:
7542     case ISD::SETGE: Swap = true; // Fallthrough
7543     case ISD::SETLE:
7544     case ISD::SETOLE: SSECC = 2; break;
7545     case ISD::SETUO:  SSECC = 3; break;
7546     case ISD::SETUNE:
7547     case ISD::SETNE:  SSECC = 4; break;
7548     case ISD::SETULE: Swap = true;
7549     case ISD::SETUGE: SSECC = 5; break;
7550     case ISD::SETULT: Swap = true;
7551     case ISD::SETUGT: SSECC = 6; break;
7552     case ISD::SETO:   SSECC = 7; break;
7553     }
7554     if (Swap)
7555       std::swap(Op0, Op1);
7556
7557     // In the two special cases we can't handle, emit two comparisons.
7558     if (SSECC == 8) {
7559       if (SetCCOpcode == ISD::SETUEQ) {
7560         SDValue UNORD, EQ;
7561         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7562         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7563         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7564       }
7565       else if (SetCCOpcode == ISD::SETONE) {
7566         SDValue ORD, NEQ;
7567         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7568         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7569         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7570       }
7571       llvm_unreachable("Illegal FP comparison");
7572     }
7573     // Handle all other FP comparisons here.
7574     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7575   }
7576
7577   // We are handling one of the integer comparisons here.  Since SSE only has
7578   // GT and EQ comparisons for integer, swapping operands and multiple
7579   // operations may be required for some comparisons.
7580   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7581   bool Swap = false, Invert = false, FlipSigns = false;
7582
7583   switch (VT.getSimpleVT().SimpleTy) {
7584   default: break;
7585   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7586   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7587   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7588   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7589   }
7590
7591   switch (SetCCOpcode) {
7592   default: break;
7593   case ISD::SETNE:  Invert = true;
7594   case ISD::SETEQ:  Opc = EQOpc; break;
7595   case ISD::SETLT:  Swap = true;
7596   case ISD::SETGT:  Opc = GTOpc; break;
7597   case ISD::SETGE:  Swap = true;
7598   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7599   case ISD::SETULT: Swap = true;
7600   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7601   case ISD::SETUGE: Swap = true;
7602   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7603   }
7604   if (Swap)
7605     std::swap(Op0, Op1);
7606
7607   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7608   // bits of the inputs before performing those operations.
7609   if (FlipSigns) {
7610     EVT EltVT = VT.getVectorElementType();
7611     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7612                                       EltVT);
7613     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7614     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7615                                     SignBits.size());
7616     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7617     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7618   }
7619
7620   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7621
7622   // If the logical-not of the result is required, perform that now.
7623   if (Invert)
7624     Result = DAG.getNOT(dl, Result, VT);
7625
7626   return Result;
7627 }
7628
7629 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7630 static bool isX86LogicalCmp(SDValue Op) {
7631   unsigned Opc = Op.getNode()->getOpcode();
7632   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7633     return true;
7634   if (Op.getResNo() == 1 &&
7635       (Opc == X86ISD::ADD ||
7636        Opc == X86ISD::SUB ||
7637        Opc == X86ISD::ADC ||
7638        Opc == X86ISD::SBB ||
7639        Opc == X86ISD::SMUL ||
7640        Opc == X86ISD::UMUL ||
7641        Opc == X86ISD::INC ||
7642        Opc == X86ISD::DEC ||
7643        Opc == X86ISD::OR ||
7644        Opc == X86ISD::XOR ||
7645        Opc == X86ISD::AND))
7646     return true;
7647
7648   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7649     return true;
7650
7651   return false;
7652 }
7653
7654 static bool isZero(SDValue V) {
7655   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7656   return C && C->isNullValue();
7657 }
7658
7659 static bool isAllOnes(SDValue V) {
7660   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7661   return C && C->isAllOnesValue();
7662 }
7663
7664 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7665   bool addTest = true;
7666   SDValue Cond  = Op.getOperand(0);
7667   SDValue Op1 = Op.getOperand(1);
7668   SDValue Op2 = Op.getOperand(2);
7669   DebugLoc DL = Op.getDebugLoc();
7670   SDValue CC;
7671
7672   if (Cond.getOpcode() == ISD::SETCC) {
7673     SDValue NewCond = LowerSETCC(Cond, DAG);
7674     if (NewCond.getNode())
7675       Cond = NewCond;
7676   }
7677
7678   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7679   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7680   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7681   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7682   if (Cond.getOpcode() == X86ISD::SETCC &&
7683       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7684       isZero(Cond.getOperand(1).getOperand(1))) {
7685     SDValue Cmp = Cond.getOperand(1);
7686
7687     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7688
7689     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7690         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7691       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7692
7693       SDValue CmpOp0 = Cmp.getOperand(0);
7694       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7695                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7696
7697       SDValue Res =   // Res = 0 or -1.
7698         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7699                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7700
7701       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7702         Res = DAG.getNOT(DL, Res, Res.getValueType());
7703
7704       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7705       if (N2C == 0 || !N2C->isNullValue())
7706         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7707       return Res;
7708     }
7709   }
7710
7711   // Look past (and (setcc_carry (cmp ...)), 1).
7712   if (Cond.getOpcode() == ISD::AND &&
7713       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7714     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7715     if (C && C->getAPIntValue() == 1)
7716       Cond = Cond.getOperand(0);
7717   }
7718
7719   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7720   // setting operand in place of the X86ISD::SETCC.
7721   if (Cond.getOpcode() == X86ISD::SETCC ||
7722       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7723     CC = Cond.getOperand(0);
7724
7725     SDValue Cmp = Cond.getOperand(1);
7726     unsigned Opc = Cmp.getOpcode();
7727     EVT VT = Op.getValueType();
7728
7729     bool IllegalFPCMov = false;
7730     if (VT.isFloatingPoint() && !VT.isVector() &&
7731         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7732       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7733
7734     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7735         Opc == X86ISD::BT) { // FIXME
7736       Cond = Cmp;
7737       addTest = false;
7738     }
7739   }
7740
7741   if (addTest) {
7742     // Look pass the truncate.
7743     if (Cond.getOpcode() == ISD::TRUNCATE)
7744       Cond = Cond.getOperand(0);
7745
7746     // We know the result of AND is compared against zero. Try to match
7747     // it to BT.
7748     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7749       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7750       if (NewSetCC.getNode()) {
7751         CC = NewSetCC.getOperand(0);
7752         Cond = NewSetCC.getOperand(1);
7753         addTest = false;
7754       }
7755     }
7756   }
7757
7758   if (addTest) {
7759     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7760     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7761   }
7762
7763   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7764   // a <  b ?  0 : -1 -> RES = setcc_carry
7765   // a >= b ? -1 :  0 -> RES = setcc_carry
7766   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7767   if (Cond.getOpcode() == X86ISD::CMP) {
7768     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7769
7770     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7771         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7772       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7773                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7774       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7775         return DAG.getNOT(DL, Res, Res.getValueType());
7776       return Res;
7777     }
7778   }
7779
7780   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7781   // condition is true.
7782   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7783   SDValue Ops[] = { Op2, Op1, CC, Cond };
7784   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7785 }
7786
7787 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7788 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7789 // from the AND / OR.
7790 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7791   Opc = Op.getOpcode();
7792   if (Opc != ISD::OR && Opc != ISD::AND)
7793     return false;
7794   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7795           Op.getOperand(0).hasOneUse() &&
7796           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7797           Op.getOperand(1).hasOneUse());
7798 }
7799
7800 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7801 // 1 and that the SETCC node has a single use.
7802 static bool isXor1OfSetCC(SDValue Op) {
7803   if (Op.getOpcode() != ISD::XOR)
7804     return false;
7805   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7806   if (N1C && N1C->getAPIntValue() == 1) {
7807     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7808       Op.getOperand(0).hasOneUse();
7809   }
7810   return false;
7811 }
7812
7813 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7814   bool addTest = true;
7815   SDValue Chain = Op.getOperand(0);
7816   SDValue Cond  = Op.getOperand(1);
7817   SDValue Dest  = Op.getOperand(2);
7818   DebugLoc dl = Op.getDebugLoc();
7819   SDValue CC;
7820
7821   if (Cond.getOpcode() == ISD::SETCC) {
7822     SDValue NewCond = LowerSETCC(Cond, DAG);
7823     if (NewCond.getNode())
7824       Cond = NewCond;
7825   }
7826 #if 0
7827   // FIXME: LowerXALUO doesn't handle these!!
7828   else if (Cond.getOpcode() == X86ISD::ADD  ||
7829            Cond.getOpcode() == X86ISD::SUB  ||
7830            Cond.getOpcode() == X86ISD::SMUL ||
7831            Cond.getOpcode() == X86ISD::UMUL)
7832     Cond = LowerXALUO(Cond, DAG);
7833 #endif
7834
7835   // Look pass (and (setcc_carry (cmp ...)), 1).
7836   if (Cond.getOpcode() == ISD::AND &&
7837       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7838     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7839     if (C && C->getAPIntValue() == 1)
7840       Cond = Cond.getOperand(0);
7841   }
7842
7843   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7844   // setting operand in place of the X86ISD::SETCC.
7845   if (Cond.getOpcode() == X86ISD::SETCC ||
7846       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7847     CC = Cond.getOperand(0);
7848
7849     SDValue Cmp = Cond.getOperand(1);
7850     unsigned Opc = Cmp.getOpcode();
7851     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7852     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7853       Cond = Cmp;
7854       addTest = false;
7855     } else {
7856       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7857       default: break;
7858       case X86::COND_O:
7859       case X86::COND_B:
7860         // These can only come from an arithmetic instruction with overflow,
7861         // e.g. SADDO, UADDO.
7862         Cond = Cond.getNode()->getOperand(1);
7863         addTest = false;
7864         break;
7865       }
7866     }
7867   } else {
7868     unsigned CondOpc;
7869     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7870       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7871       if (CondOpc == ISD::OR) {
7872         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7873         // two branches instead of an explicit OR instruction with a
7874         // separate test.
7875         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7876             isX86LogicalCmp(Cmp)) {
7877           CC = Cond.getOperand(0).getOperand(0);
7878           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7879                               Chain, Dest, CC, Cmp);
7880           CC = Cond.getOperand(1).getOperand(0);
7881           Cond = Cmp;
7882           addTest = false;
7883         }
7884       } else { // ISD::AND
7885         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7886         // two branches instead of an explicit AND instruction with a
7887         // separate test. However, we only do this if this block doesn't
7888         // have a fall-through edge, because this requires an explicit
7889         // jmp when the condition is false.
7890         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7891             isX86LogicalCmp(Cmp) &&
7892             Op.getNode()->hasOneUse()) {
7893           X86::CondCode CCode =
7894             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7895           CCode = X86::GetOppositeBranchCondition(CCode);
7896           CC = DAG.getConstant(CCode, MVT::i8);
7897           SDNode *User = *Op.getNode()->use_begin();
7898           // Look for an unconditional branch following this conditional branch.
7899           // We need this because we need to reverse the successors in order
7900           // to implement FCMP_OEQ.
7901           if (User->getOpcode() == ISD::BR) {
7902             SDValue FalseBB = User->getOperand(1);
7903             SDNode *NewBR =
7904               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7905             assert(NewBR == User);
7906             (void)NewBR;
7907             Dest = FalseBB;
7908
7909             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7910                                 Chain, Dest, CC, Cmp);
7911             X86::CondCode CCode =
7912               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7913             CCode = X86::GetOppositeBranchCondition(CCode);
7914             CC = DAG.getConstant(CCode, MVT::i8);
7915             Cond = Cmp;
7916             addTest = false;
7917           }
7918         }
7919       }
7920     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7921       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7922       // It should be transformed during dag combiner except when the condition
7923       // is set by a arithmetics with overflow node.
7924       X86::CondCode CCode =
7925         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7926       CCode = X86::GetOppositeBranchCondition(CCode);
7927       CC = DAG.getConstant(CCode, MVT::i8);
7928       Cond = Cond.getOperand(0).getOperand(1);
7929       addTest = false;
7930     }
7931   }
7932
7933   if (addTest) {
7934     // Look pass the truncate.
7935     if (Cond.getOpcode() == ISD::TRUNCATE)
7936       Cond = Cond.getOperand(0);
7937
7938     // We know the result of AND is compared against zero. Try to match
7939     // it to BT.
7940     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7941       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7942       if (NewSetCC.getNode()) {
7943         CC = NewSetCC.getOperand(0);
7944         Cond = NewSetCC.getOperand(1);
7945         addTest = false;
7946       }
7947     }
7948   }
7949
7950   if (addTest) {
7951     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7952     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7953   }
7954   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7955                      Chain, Dest, CC, Cond);
7956 }
7957
7958
7959 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7960 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7961 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7962 // that the guard pages used by the OS virtual memory manager are allocated in
7963 // correct sequence.
7964 SDValue
7965 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7966                                            SelectionDAG &DAG) const {
7967   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7968          "This should be used only on Windows targets");
7969   assert(!Subtarget->isTargetEnvMacho());
7970   DebugLoc dl = Op.getDebugLoc();
7971
7972   // Get the inputs.
7973   SDValue Chain = Op.getOperand(0);
7974   SDValue Size  = Op.getOperand(1);
7975   // FIXME: Ensure alignment here
7976
7977   SDValue Flag;
7978
7979   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7980   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7981
7982   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
7983   Flag = Chain.getValue(1);
7984
7985   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7986
7987   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7988   Flag = Chain.getValue(1);
7989
7990   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7991
7992   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7993   return DAG.getMergeValues(Ops1, 2, dl);
7994 }
7995
7996 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7997   MachineFunction &MF = DAG.getMachineFunction();
7998   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7999
8000   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8001   DebugLoc DL = Op.getDebugLoc();
8002
8003   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8004     // vastart just stores the address of the VarArgsFrameIndex slot into the
8005     // memory location argument.
8006     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8007                                    getPointerTy());
8008     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8009                         MachinePointerInfo(SV), false, false, 0);
8010   }
8011
8012   // __va_list_tag:
8013   //   gp_offset         (0 - 6 * 8)
8014   //   fp_offset         (48 - 48 + 8 * 16)
8015   //   overflow_arg_area (point to parameters coming in memory).
8016   //   reg_save_area
8017   SmallVector<SDValue, 8> MemOps;
8018   SDValue FIN = Op.getOperand(1);
8019   // Store gp_offset
8020   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8021                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8022                                                MVT::i32),
8023                                FIN, MachinePointerInfo(SV), false, false, 0);
8024   MemOps.push_back(Store);
8025
8026   // Store fp_offset
8027   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8028                     FIN, DAG.getIntPtrConstant(4));
8029   Store = DAG.getStore(Op.getOperand(0), DL,
8030                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8031                                        MVT::i32),
8032                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8033   MemOps.push_back(Store);
8034
8035   // Store ptr to overflow_arg_area
8036   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8037                     FIN, DAG.getIntPtrConstant(4));
8038   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8039                                     getPointerTy());
8040   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8041                        MachinePointerInfo(SV, 8),
8042                        false, false, 0);
8043   MemOps.push_back(Store);
8044
8045   // Store ptr to reg_save_area.
8046   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8047                     FIN, DAG.getIntPtrConstant(8));
8048   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8049                                     getPointerTy());
8050   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8051                        MachinePointerInfo(SV, 16), false, false, 0);
8052   MemOps.push_back(Store);
8053   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8054                      &MemOps[0], MemOps.size());
8055 }
8056
8057 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8058   assert(Subtarget->is64Bit() &&
8059          "LowerVAARG only handles 64-bit va_arg!");
8060   assert((Subtarget->isTargetLinux() ||
8061           Subtarget->isTargetDarwin()) &&
8062           "Unhandled target in LowerVAARG");
8063   assert(Op.getNode()->getNumOperands() == 4);
8064   SDValue Chain = Op.getOperand(0);
8065   SDValue SrcPtr = Op.getOperand(1);
8066   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8067   unsigned Align = Op.getConstantOperandVal(3);
8068   DebugLoc dl = Op.getDebugLoc();
8069
8070   EVT ArgVT = Op.getNode()->getValueType(0);
8071   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8072   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8073   uint8_t ArgMode;
8074
8075   // Decide which area this value should be read from.
8076   // TODO: Implement the AMD64 ABI in its entirety. This simple
8077   // selection mechanism works only for the basic types.
8078   if (ArgVT == MVT::f80) {
8079     llvm_unreachable("va_arg for f80 not yet implemented");
8080   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8081     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8082   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8083     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8084   } else {
8085     llvm_unreachable("Unhandled argument type in LowerVAARG");
8086   }
8087
8088   if (ArgMode == 2) {
8089     // Sanity Check: Make sure using fp_offset makes sense.
8090     assert(!UseSoftFloat &&
8091            !(DAG.getMachineFunction()
8092                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8093            Subtarget->hasXMM());
8094   }
8095
8096   // Insert VAARG_64 node into the DAG
8097   // VAARG_64 returns two values: Variable Argument Address, Chain
8098   SmallVector<SDValue, 11> InstOps;
8099   InstOps.push_back(Chain);
8100   InstOps.push_back(SrcPtr);
8101   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8102   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8103   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8104   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8105   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8106                                           VTs, &InstOps[0], InstOps.size(),
8107                                           MVT::i64,
8108                                           MachinePointerInfo(SV),
8109                                           /*Align=*/0,
8110                                           /*Volatile=*/false,
8111                                           /*ReadMem=*/true,
8112                                           /*WriteMem=*/true);
8113   Chain = VAARG.getValue(1);
8114
8115   // Load the next argument and return it
8116   return DAG.getLoad(ArgVT, dl,
8117                      Chain,
8118                      VAARG,
8119                      MachinePointerInfo(),
8120                      false, false, 0);
8121 }
8122
8123 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8124   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8125   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8126   SDValue Chain = Op.getOperand(0);
8127   SDValue DstPtr = Op.getOperand(1);
8128   SDValue SrcPtr = Op.getOperand(2);
8129   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8130   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8131   DebugLoc DL = Op.getDebugLoc();
8132
8133   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8134                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8135                        false,
8136                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8137 }
8138
8139 SDValue
8140 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8141   DebugLoc dl = Op.getDebugLoc();
8142   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8143   switch (IntNo) {
8144   default: return SDValue();    // Don't custom lower most intrinsics.
8145   // Comparison intrinsics.
8146   case Intrinsic::x86_sse_comieq_ss:
8147   case Intrinsic::x86_sse_comilt_ss:
8148   case Intrinsic::x86_sse_comile_ss:
8149   case Intrinsic::x86_sse_comigt_ss:
8150   case Intrinsic::x86_sse_comige_ss:
8151   case Intrinsic::x86_sse_comineq_ss:
8152   case Intrinsic::x86_sse_ucomieq_ss:
8153   case Intrinsic::x86_sse_ucomilt_ss:
8154   case Intrinsic::x86_sse_ucomile_ss:
8155   case Intrinsic::x86_sse_ucomigt_ss:
8156   case Intrinsic::x86_sse_ucomige_ss:
8157   case Intrinsic::x86_sse_ucomineq_ss:
8158   case Intrinsic::x86_sse2_comieq_sd:
8159   case Intrinsic::x86_sse2_comilt_sd:
8160   case Intrinsic::x86_sse2_comile_sd:
8161   case Intrinsic::x86_sse2_comigt_sd:
8162   case Intrinsic::x86_sse2_comige_sd:
8163   case Intrinsic::x86_sse2_comineq_sd:
8164   case Intrinsic::x86_sse2_ucomieq_sd:
8165   case Intrinsic::x86_sse2_ucomilt_sd:
8166   case Intrinsic::x86_sse2_ucomile_sd:
8167   case Intrinsic::x86_sse2_ucomigt_sd:
8168   case Intrinsic::x86_sse2_ucomige_sd:
8169   case Intrinsic::x86_sse2_ucomineq_sd: {
8170     unsigned Opc = 0;
8171     ISD::CondCode CC = ISD::SETCC_INVALID;
8172     switch (IntNo) {
8173     default: break;
8174     case Intrinsic::x86_sse_comieq_ss:
8175     case Intrinsic::x86_sse2_comieq_sd:
8176       Opc = X86ISD::COMI;
8177       CC = ISD::SETEQ;
8178       break;
8179     case Intrinsic::x86_sse_comilt_ss:
8180     case Intrinsic::x86_sse2_comilt_sd:
8181       Opc = X86ISD::COMI;
8182       CC = ISD::SETLT;
8183       break;
8184     case Intrinsic::x86_sse_comile_ss:
8185     case Intrinsic::x86_sse2_comile_sd:
8186       Opc = X86ISD::COMI;
8187       CC = ISD::SETLE;
8188       break;
8189     case Intrinsic::x86_sse_comigt_ss:
8190     case Intrinsic::x86_sse2_comigt_sd:
8191       Opc = X86ISD::COMI;
8192       CC = ISD::SETGT;
8193       break;
8194     case Intrinsic::x86_sse_comige_ss:
8195     case Intrinsic::x86_sse2_comige_sd:
8196       Opc = X86ISD::COMI;
8197       CC = ISD::SETGE;
8198       break;
8199     case Intrinsic::x86_sse_comineq_ss:
8200     case Intrinsic::x86_sse2_comineq_sd:
8201       Opc = X86ISD::COMI;
8202       CC = ISD::SETNE;
8203       break;
8204     case Intrinsic::x86_sse_ucomieq_ss:
8205     case Intrinsic::x86_sse2_ucomieq_sd:
8206       Opc = X86ISD::UCOMI;
8207       CC = ISD::SETEQ;
8208       break;
8209     case Intrinsic::x86_sse_ucomilt_ss:
8210     case Intrinsic::x86_sse2_ucomilt_sd:
8211       Opc = X86ISD::UCOMI;
8212       CC = ISD::SETLT;
8213       break;
8214     case Intrinsic::x86_sse_ucomile_ss:
8215     case Intrinsic::x86_sse2_ucomile_sd:
8216       Opc = X86ISD::UCOMI;
8217       CC = ISD::SETLE;
8218       break;
8219     case Intrinsic::x86_sse_ucomigt_ss:
8220     case Intrinsic::x86_sse2_ucomigt_sd:
8221       Opc = X86ISD::UCOMI;
8222       CC = ISD::SETGT;
8223       break;
8224     case Intrinsic::x86_sse_ucomige_ss:
8225     case Intrinsic::x86_sse2_ucomige_sd:
8226       Opc = X86ISD::UCOMI;
8227       CC = ISD::SETGE;
8228       break;
8229     case Intrinsic::x86_sse_ucomineq_ss:
8230     case Intrinsic::x86_sse2_ucomineq_sd:
8231       Opc = X86ISD::UCOMI;
8232       CC = ISD::SETNE;
8233       break;
8234     }
8235
8236     SDValue LHS = Op.getOperand(1);
8237     SDValue RHS = Op.getOperand(2);
8238     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8239     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8240     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8241     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8242                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8243     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8244   }
8245   // ptest and testp intrinsics. The intrinsic these come from are designed to
8246   // return an integer value, not just an instruction so lower it to the ptest
8247   // or testp pattern and a setcc for the result.
8248   case Intrinsic::x86_sse41_ptestz:
8249   case Intrinsic::x86_sse41_ptestc:
8250   case Intrinsic::x86_sse41_ptestnzc:
8251   case Intrinsic::x86_avx_ptestz_256:
8252   case Intrinsic::x86_avx_ptestc_256:
8253   case Intrinsic::x86_avx_ptestnzc_256:
8254   case Intrinsic::x86_avx_vtestz_ps:
8255   case Intrinsic::x86_avx_vtestc_ps:
8256   case Intrinsic::x86_avx_vtestnzc_ps:
8257   case Intrinsic::x86_avx_vtestz_pd:
8258   case Intrinsic::x86_avx_vtestc_pd:
8259   case Intrinsic::x86_avx_vtestnzc_pd:
8260   case Intrinsic::x86_avx_vtestz_ps_256:
8261   case Intrinsic::x86_avx_vtestc_ps_256:
8262   case Intrinsic::x86_avx_vtestnzc_ps_256:
8263   case Intrinsic::x86_avx_vtestz_pd_256:
8264   case Intrinsic::x86_avx_vtestc_pd_256:
8265   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8266     bool IsTestPacked = false;
8267     unsigned X86CC = 0;
8268     switch (IntNo) {
8269     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8270     case Intrinsic::x86_avx_vtestz_ps:
8271     case Intrinsic::x86_avx_vtestz_pd:
8272     case Intrinsic::x86_avx_vtestz_ps_256:
8273     case Intrinsic::x86_avx_vtestz_pd_256:
8274       IsTestPacked = true; // Fallthrough
8275     case Intrinsic::x86_sse41_ptestz:
8276     case Intrinsic::x86_avx_ptestz_256:
8277       // ZF = 1
8278       X86CC = X86::COND_E;
8279       break;
8280     case Intrinsic::x86_avx_vtestc_ps:
8281     case Intrinsic::x86_avx_vtestc_pd:
8282     case Intrinsic::x86_avx_vtestc_ps_256:
8283     case Intrinsic::x86_avx_vtestc_pd_256:
8284       IsTestPacked = true; // Fallthrough
8285     case Intrinsic::x86_sse41_ptestc:
8286     case Intrinsic::x86_avx_ptestc_256:
8287       // CF = 1
8288       X86CC = X86::COND_B;
8289       break;
8290     case Intrinsic::x86_avx_vtestnzc_ps:
8291     case Intrinsic::x86_avx_vtestnzc_pd:
8292     case Intrinsic::x86_avx_vtestnzc_ps_256:
8293     case Intrinsic::x86_avx_vtestnzc_pd_256:
8294       IsTestPacked = true; // Fallthrough
8295     case Intrinsic::x86_sse41_ptestnzc:
8296     case Intrinsic::x86_avx_ptestnzc_256:
8297       // ZF and CF = 0
8298       X86CC = X86::COND_A;
8299       break;
8300     }
8301
8302     SDValue LHS = Op.getOperand(1);
8303     SDValue RHS = Op.getOperand(2);
8304     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8305     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8306     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8307     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8308     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8309   }
8310
8311   // Fix vector shift instructions where the last operand is a non-immediate
8312   // i32 value.
8313   case Intrinsic::x86_sse2_pslli_w:
8314   case Intrinsic::x86_sse2_pslli_d:
8315   case Intrinsic::x86_sse2_pslli_q:
8316   case Intrinsic::x86_sse2_psrli_w:
8317   case Intrinsic::x86_sse2_psrli_d:
8318   case Intrinsic::x86_sse2_psrli_q:
8319   case Intrinsic::x86_sse2_psrai_w:
8320   case Intrinsic::x86_sse2_psrai_d:
8321   case Intrinsic::x86_mmx_pslli_w:
8322   case Intrinsic::x86_mmx_pslli_d:
8323   case Intrinsic::x86_mmx_pslli_q:
8324   case Intrinsic::x86_mmx_psrli_w:
8325   case Intrinsic::x86_mmx_psrli_d:
8326   case Intrinsic::x86_mmx_psrli_q:
8327   case Intrinsic::x86_mmx_psrai_w:
8328   case Intrinsic::x86_mmx_psrai_d: {
8329     SDValue ShAmt = Op.getOperand(2);
8330     if (isa<ConstantSDNode>(ShAmt))
8331       return SDValue();
8332
8333     unsigned NewIntNo = 0;
8334     EVT ShAmtVT = MVT::v4i32;
8335     switch (IntNo) {
8336     case Intrinsic::x86_sse2_pslli_w:
8337       NewIntNo = Intrinsic::x86_sse2_psll_w;
8338       break;
8339     case Intrinsic::x86_sse2_pslli_d:
8340       NewIntNo = Intrinsic::x86_sse2_psll_d;
8341       break;
8342     case Intrinsic::x86_sse2_pslli_q:
8343       NewIntNo = Intrinsic::x86_sse2_psll_q;
8344       break;
8345     case Intrinsic::x86_sse2_psrli_w:
8346       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8347       break;
8348     case Intrinsic::x86_sse2_psrli_d:
8349       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8350       break;
8351     case Intrinsic::x86_sse2_psrli_q:
8352       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8353       break;
8354     case Intrinsic::x86_sse2_psrai_w:
8355       NewIntNo = Intrinsic::x86_sse2_psra_w;
8356       break;
8357     case Intrinsic::x86_sse2_psrai_d:
8358       NewIntNo = Intrinsic::x86_sse2_psra_d;
8359       break;
8360     default: {
8361       ShAmtVT = MVT::v2i32;
8362       switch (IntNo) {
8363       case Intrinsic::x86_mmx_pslli_w:
8364         NewIntNo = Intrinsic::x86_mmx_psll_w;
8365         break;
8366       case Intrinsic::x86_mmx_pslli_d:
8367         NewIntNo = Intrinsic::x86_mmx_psll_d;
8368         break;
8369       case Intrinsic::x86_mmx_pslli_q:
8370         NewIntNo = Intrinsic::x86_mmx_psll_q;
8371         break;
8372       case Intrinsic::x86_mmx_psrli_w:
8373         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8374         break;
8375       case Intrinsic::x86_mmx_psrli_d:
8376         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8377         break;
8378       case Intrinsic::x86_mmx_psrli_q:
8379         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8380         break;
8381       case Intrinsic::x86_mmx_psrai_w:
8382         NewIntNo = Intrinsic::x86_mmx_psra_w;
8383         break;
8384       case Intrinsic::x86_mmx_psrai_d:
8385         NewIntNo = Intrinsic::x86_mmx_psra_d;
8386         break;
8387       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8388       }
8389       break;
8390     }
8391     }
8392
8393     // The vector shift intrinsics with scalars uses 32b shift amounts but
8394     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8395     // to be zero.
8396     SDValue ShOps[4];
8397     ShOps[0] = ShAmt;
8398     ShOps[1] = DAG.getConstant(0, MVT::i32);
8399     if (ShAmtVT == MVT::v4i32) {
8400       ShOps[2] = DAG.getUNDEF(MVT::i32);
8401       ShOps[3] = DAG.getUNDEF(MVT::i32);
8402       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8403     } else {
8404       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8405 // FIXME this must be lowered to get rid of the invalid type.
8406     }
8407
8408     EVT VT = Op.getValueType();
8409     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8410     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8411                        DAG.getConstant(NewIntNo, MVT::i32),
8412                        Op.getOperand(1), ShAmt);
8413   }
8414   }
8415 }
8416
8417 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8418                                            SelectionDAG &DAG) const {
8419   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8420   MFI->setReturnAddressIsTaken(true);
8421
8422   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8423   DebugLoc dl = Op.getDebugLoc();
8424
8425   if (Depth > 0) {
8426     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8427     SDValue Offset =
8428       DAG.getConstant(TD->getPointerSize(),
8429                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8430     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8431                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8432                                    FrameAddr, Offset),
8433                        MachinePointerInfo(), false, false, 0);
8434   }
8435
8436   // Just load the return address.
8437   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8438   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8439                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8440 }
8441
8442 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8443   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8444   MFI->setFrameAddressIsTaken(true);
8445
8446   EVT VT = Op.getValueType();
8447   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8448   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8449   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8450   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8451   while (Depth--)
8452     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8453                             MachinePointerInfo(),
8454                             false, false, 0);
8455   return FrameAddr;
8456 }
8457
8458 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8459                                                      SelectionDAG &DAG) const {
8460   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8461 }
8462
8463 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8464   MachineFunction &MF = DAG.getMachineFunction();
8465   SDValue Chain     = Op.getOperand(0);
8466   SDValue Offset    = Op.getOperand(1);
8467   SDValue Handler   = Op.getOperand(2);
8468   DebugLoc dl       = Op.getDebugLoc();
8469
8470   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8471                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8472                                      getPointerTy());
8473   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8474
8475   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8476                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8477   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8478   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8479                        false, false, 0);
8480   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8481   MF.getRegInfo().addLiveOut(StoreAddrReg);
8482
8483   return DAG.getNode(X86ISD::EH_RETURN, dl,
8484                      MVT::Other,
8485                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8486 }
8487
8488 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8489                                              SelectionDAG &DAG) const {
8490   SDValue Root = Op.getOperand(0);
8491   SDValue Trmp = Op.getOperand(1); // trampoline
8492   SDValue FPtr = Op.getOperand(2); // nested function
8493   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8494   DebugLoc dl  = Op.getDebugLoc();
8495
8496   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8497
8498   if (Subtarget->is64Bit()) {
8499     SDValue OutChains[6];
8500
8501     // Large code-model.
8502     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8503     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8504
8505     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8506     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8507
8508     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8509
8510     // Load the pointer to the nested function into R11.
8511     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8512     SDValue Addr = Trmp;
8513     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8514                                 Addr, MachinePointerInfo(TrmpAddr),
8515                                 false, false, 0);
8516
8517     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8518                        DAG.getConstant(2, MVT::i64));
8519     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8520                                 MachinePointerInfo(TrmpAddr, 2),
8521                                 false, false, 2);
8522
8523     // Load the 'nest' parameter value into R10.
8524     // R10 is specified in X86CallingConv.td
8525     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8526     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8527                        DAG.getConstant(10, MVT::i64));
8528     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8529                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8530                                 false, false, 0);
8531
8532     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8533                        DAG.getConstant(12, MVT::i64));
8534     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8535                                 MachinePointerInfo(TrmpAddr, 12),
8536                                 false, false, 2);
8537
8538     // Jump to the nested function.
8539     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8540     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8541                        DAG.getConstant(20, MVT::i64));
8542     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8543                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8544                                 false, false, 0);
8545
8546     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8547     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8548                        DAG.getConstant(22, MVT::i64));
8549     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8550                                 MachinePointerInfo(TrmpAddr, 22),
8551                                 false, false, 0);
8552
8553     SDValue Ops[] =
8554       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8555     return DAG.getMergeValues(Ops, 2, dl);
8556   } else {
8557     const Function *Func =
8558       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8559     CallingConv::ID CC = Func->getCallingConv();
8560     unsigned NestReg;
8561
8562     switch (CC) {
8563     default:
8564       llvm_unreachable("Unsupported calling convention");
8565     case CallingConv::C:
8566     case CallingConv::X86_StdCall: {
8567       // Pass 'nest' parameter in ECX.
8568       // Must be kept in sync with X86CallingConv.td
8569       NestReg = X86::ECX;
8570
8571       // Check that ECX wasn't needed by an 'inreg' parameter.
8572       const FunctionType *FTy = Func->getFunctionType();
8573       const AttrListPtr &Attrs = Func->getAttributes();
8574
8575       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8576         unsigned InRegCount = 0;
8577         unsigned Idx = 1;
8578
8579         for (FunctionType::param_iterator I = FTy->param_begin(),
8580              E = FTy->param_end(); I != E; ++I, ++Idx)
8581           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8582             // FIXME: should only count parameters that are lowered to integers.
8583             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8584
8585         if (InRegCount > 2) {
8586           report_fatal_error("Nest register in use - reduce number of inreg"
8587                              " parameters!");
8588         }
8589       }
8590       break;
8591     }
8592     case CallingConv::X86_FastCall:
8593     case CallingConv::X86_ThisCall:
8594     case CallingConv::Fast:
8595       // Pass 'nest' parameter in EAX.
8596       // Must be kept in sync with X86CallingConv.td
8597       NestReg = X86::EAX;
8598       break;
8599     }
8600
8601     SDValue OutChains[4];
8602     SDValue Addr, Disp;
8603
8604     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8605                        DAG.getConstant(10, MVT::i32));
8606     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8607
8608     // This is storing the opcode for MOV32ri.
8609     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8610     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8611     OutChains[0] = DAG.getStore(Root, dl,
8612                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8613                                 Trmp, MachinePointerInfo(TrmpAddr),
8614                                 false, false, 0);
8615
8616     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8617                        DAG.getConstant(1, MVT::i32));
8618     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8619                                 MachinePointerInfo(TrmpAddr, 1),
8620                                 false, false, 1);
8621
8622     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8623     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8624                        DAG.getConstant(5, MVT::i32));
8625     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8626                                 MachinePointerInfo(TrmpAddr, 5),
8627                                 false, false, 1);
8628
8629     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8630                        DAG.getConstant(6, MVT::i32));
8631     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8632                                 MachinePointerInfo(TrmpAddr, 6),
8633                                 false, false, 1);
8634
8635     SDValue Ops[] =
8636       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8637     return DAG.getMergeValues(Ops, 2, dl);
8638   }
8639 }
8640
8641 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8642                                             SelectionDAG &DAG) const {
8643   /*
8644    The rounding mode is in bits 11:10 of FPSR, and has the following
8645    settings:
8646      00 Round to nearest
8647      01 Round to -inf
8648      10 Round to +inf
8649      11 Round to 0
8650
8651   FLT_ROUNDS, on the other hand, expects the following:
8652     -1 Undefined
8653      0 Round to 0
8654      1 Round to nearest
8655      2 Round to +inf
8656      3 Round to -inf
8657
8658   To perform the conversion, we do:
8659     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8660   */
8661
8662   MachineFunction &MF = DAG.getMachineFunction();
8663   const TargetMachine &TM = MF.getTarget();
8664   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8665   unsigned StackAlignment = TFI.getStackAlignment();
8666   EVT VT = Op.getValueType();
8667   DebugLoc DL = Op.getDebugLoc();
8668
8669   // Save FP Control Word to stack slot
8670   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8671   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8672
8673
8674   MachineMemOperand *MMO =
8675    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8676                            MachineMemOperand::MOStore, 2, 2);
8677
8678   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8679   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8680                                           DAG.getVTList(MVT::Other),
8681                                           Ops, 2, MVT::i16, MMO);
8682
8683   // Load FP Control Word from stack slot
8684   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8685                             MachinePointerInfo(), false, false, 0);
8686
8687   // Transform as necessary
8688   SDValue CWD1 =
8689     DAG.getNode(ISD::SRL, DL, MVT::i16,
8690                 DAG.getNode(ISD::AND, DL, MVT::i16,
8691                             CWD, DAG.getConstant(0x800, MVT::i16)),
8692                 DAG.getConstant(11, MVT::i8));
8693   SDValue CWD2 =
8694     DAG.getNode(ISD::SRL, DL, MVT::i16,
8695                 DAG.getNode(ISD::AND, DL, MVT::i16,
8696                             CWD, DAG.getConstant(0x400, MVT::i16)),
8697                 DAG.getConstant(9, MVT::i8));
8698
8699   SDValue RetVal =
8700     DAG.getNode(ISD::AND, DL, MVT::i16,
8701                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8702                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8703                             DAG.getConstant(1, MVT::i16)),
8704                 DAG.getConstant(3, MVT::i16));
8705
8706
8707   return DAG.getNode((VT.getSizeInBits() < 16 ?
8708                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8709 }
8710
8711 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8712   EVT VT = Op.getValueType();
8713   EVT OpVT = VT;
8714   unsigned NumBits = VT.getSizeInBits();
8715   DebugLoc dl = Op.getDebugLoc();
8716
8717   Op = Op.getOperand(0);
8718   if (VT == MVT::i8) {
8719     // Zero extend to i32 since there is not an i8 bsr.
8720     OpVT = MVT::i32;
8721     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8722   }
8723
8724   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8725   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8726   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8727
8728   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8729   SDValue Ops[] = {
8730     Op,
8731     DAG.getConstant(NumBits+NumBits-1, OpVT),
8732     DAG.getConstant(X86::COND_E, MVT::i8),
8733     Op.getValue(1)
8734   };
8735   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8736
8737   // Finally xor with NumBits-1.
8738   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8739
8740   if (VT == MVT::i8)
8741     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8742   return Op;
8743 }
8744
8745 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8746   EVT VT = Op.getValueType();
8747   EVT OpVT = VT;
8748   unsigned NumBits = VT.getSizeInBits();
8749   DebugLoc dl = Op.getDebugLoc();
8750
8751   Op = Op.getOperand(0);
8752   if (VT == MVT::i8) {
8753     OpVT = MVT::i32;
8754     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8755   }
8756
8757   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8758   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8759   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8760
8761   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8762   SDValue Ops[] = {
8763     Op,
8764     DAG.getConstant(NumBits, OpVT),
8765     DAG.getConstant(X86::COND_E, MVT::i8),
8766     Op.getValue(1)
8767   };
8768   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8769
8770   if (VT == MVT::i8)
8771     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8772   return Op;
8773 }
8774
8775 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8776   EVT VT = Op.getValueType();
8777   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8778   DebugLoc dl = Op.getDebugLoc();
8779
8780   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8781   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8782   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8783   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8784   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8785   //
8786   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8787   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8788   //  return AloBlo + AloBhi + AhiBlo;
8789
8790   SDValue A = Op.getOperand(0);
8791   SDValue B = Op.getOperand(1);
8792
8793   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8794                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8795                        A, DAG.getConstant(32, MVT::i32));
8796   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8797                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8798                        B, DAG.getConstant(32, MVT::i32));
8799   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8800                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8801                        A, B);
8802   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8803                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8804                        A, Bhi);
8805   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8806                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8807                        Ahi, B);
8808   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8809                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8810                        AloBhi, DAG.getConstant(32, MVT::i32));
8811   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8812                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8813                        AhiBlo, DAG.getConstant(32, MVT::i32));
8814   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8815   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8816   return Res;
8817 }
8818
8819 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8820
8821   EVT VT = Op.getValueType();
8822   DebugLoc dl = Op.getDebugLoc();
8823   SDValue R = Op.getOperand(0);
8824   SDValue Amt = Op.getOperand(1);
8825
8826   LLVMContext *Context = DAG.getContext();
8827
8828   // Must have SSE2.
8829   if (!Subtarget->hasSSE2()) return SDValue();
8830
8831   // Optimize shl/srl/sra with constant shift amount.
8832   if (isSplatVector(Amt.getNode())) {
8833     SDValue SclrAmt = Amt->getOperand(0);
8834     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8835       uint64_t ShiftAmt = C->getZExtValue();
8836
8837       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8838        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8839                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8840                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8841
8842       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8843        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8844                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8845                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8846
8847       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8848        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8849                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8850                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8851
8852       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8853        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8854                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8855                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8856
8857       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8858        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8859                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8860                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8861
8862       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8863        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8864                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8865                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8866
8867       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8868        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8869                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8870                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8871
8872       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8873        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8874                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8875                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8876     }
8877   }
8878
8879   // Lower SHL with variable shift amount.
8880   // Cannot lower SHL without SSE4.1 or later.
8881   if (!Subtarget->hasSSE41()) return SDValue();
8882
8883   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8884     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8885                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8886                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8887
8888     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8889
8890     std::vector<Constant*> CV(4, CI);
8891     Constant *C = ConstantVector::get(CV);
8892     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8893     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8894                                  MachinePointerInfo::getConstantPool(),
8895                                  false, false, 16);
8896
8897     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8898     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8899     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8900     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8901   }
8902   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8903     // a = a << 5;
8904     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8905                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8906                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8907
8908     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8909     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8910
8911     std::vector<Constant*> CVM1(16, CM1);
8912     std::vector<Constant*> CVM2(16, CM2);
8913     Constant *C = ConstantVector::get(CVM1);
8914     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8915     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8916                             MachinePointerInfo::getConstantPool(),
8917                             false, false, 16);
8918
8919     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8920     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8921     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8922                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8923                     DAG.getConstant(4, MVT::i32));
8924     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8925     // a += a
8926     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8927
8928     C = ConstantVector::get(CVM2);
8929     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8930     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8931                     MachinePointerInfo::getConstantPool(),
8932                     false, false, 16);
8933
8934     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8935     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8936     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8937                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8938                     DAG.getConstant(2, MVT::i32));
8939     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8940     // a += a
8941     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8942
8943     // return pblendv(r, r+r, a);
8944     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8945                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8946     return R;
8947   }
8948   return SDValue();
8949 }
8950
8951 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8952   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8953   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8954   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8955   // has only one use.
8956   SDNode *N = Op.getNode();
8957   SDValue LHS = N->getOperand(0);
8958   SDValue RHS = N->getOperand(1);
8959   unsigned BaseOp = 0;
8960   unsigned Cond = 0;
8961   DebugLoc DL = Op.getDebugLoc();
8962   switch (Op.getOpcode()) {
8963   default: llvm_unreachable("Unknown ovf instruction!");
8964   case ISD::SADDO:
8965     // A subtract of one will be selected as a INC. Note that INC doesn't
8966     // set CF, so we can't do this for UADDO.
8967     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8968       if (C->isOne()) {
8969         BaseOp = X86ISD::INC;
8970         Cond = X86::COND_O;
8971         break;
8972       }
8973     BaseOp = X86ISD::ADD;
8974     Cond = X86::COND_O;
8975     break;
8976   case ISD::UADDO:
8977     BaseOp = X86ISD::ADD;
8978     Cond = X86::COND_B;
8979     break;
8980   case ISD::SSUBO:
8981     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8982     // set CF, so we can't do this for USUBO.
8983     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8984       if (C->isOne()) {
8985         BaseOp = X86ISD::DEC;
8986         Cond = X86::COND_O;
8987         break;
8988       }
8989     BaseOp = X86ISD::SUB;
8990     Cond = X86::COND_O;
8991     break;
8992   case ISD::USUBO:
8993     BaseOp = X86ISD::SUB;
8994     Cond = X86::COND_B;
8995     break;
8996   case ISD::SMULO:
8997     BaseOp = X86ISD::SMUL;
8998     Cond = X86::COND_O;
8999     break;
9000   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9001     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9002                                  MVT::i32);
9003     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9004
9005     SDValue SetCC =
9006       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9007                   DAG.getConstant(X86::COND_O, MVT::i32),
9008                   SDValue(Sum.getNode(), 2));
9009
9010     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9011     return Sum;
9012   }
9013   }
9014
9015   // Also sets EFLAGS.
9016   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9017   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9018
9019   SDValue SetCC =
9020     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9021                 DAG.getConstant(Cond, MVT::i32),
9022                 SDValue(Sum.getNode(), 1));
9023
9024   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9025   return Sum;
9026 }
9027
9028 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9029   DebugLoc dl = Op.getDebugLoc();
9030
9031   if (!Subtarget->hasSSE2()) {
9032     SDValue Chain = Op.getOperand(0);
9033     SDValue Zero = DAG.getConstant(0,
9034                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9035     SDValue Ops[] = {
9036       DAG.getRegister(X86::ESP, MVT::i32), // Base
9037       DAG.getTargetConstant(1, MVT::i8),   // Scale
9038       DAG.getRegister(0, MVT::i32),        // Index
9039       DAG.getTargetConstant(0, MVT::i32),  // Disp
9040       DAG.getRegister(0, MVT::i32),        // Segment.
9041       Zero,
9042       Chain
9043     };
9044     SDNode *Res =
9045       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9046                           array_lengthof(Ops));
9047     return SDValue(Res, 0);
9048   }
9049
9050   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9051   if (!isDev)
9052     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9053
9054   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9055   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9056   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9057   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9058
9059   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9060   if (!Op1 && !Op2 && !Op3 && Op4)
9061     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9062
9063   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9064   if (Op1 && !Op2 && !Op3 && !Op4)
9065     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9066
9067   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9068   //           (MFENCE)>;
9069   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9070 }
9071
9072 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9073   EVT T = Op.getValueType();
9074   DebugLoc DL = Op.getDebugLoc();
9075   unsigned Reg = 0;
9076   unsigned size = 0;
9077   switch(T.getSimpleVT().SimpleTy) {
9078   default:
9079     assert(false && "Invalid value type!");
9080   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9081   case MVT::i16: Reg = X86::AX;  size = 2; break;
9082   case MVT::i32: Reg = X86::EAX; size = 4; break;
9083   case MVT::i64:
9084     assert(Subtarget->is64Bit() && "Node not type legal!");
9085     Reg = X86::RAX; size = 8;
9086     break;
9087   }
9088   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9089                                     Op.getOperand(2), SDValue());
9090   SDValue Ops[] = { cpIn.getValue(0),
9091                     Op.getOperand(1),
9092                     Op.getOperand(3),
9093                     DAG.getTargetConstant(size, MVT::i8),
9094                     cpIn.getValue(1) };
9095   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9096   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9097   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9098                                            Ops, 5, T, MMO);
9099   SDValue cpOut =
9100     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9101   return cpOut;
9102 }
9103
9104 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9105                                                  SelectionDAG &DAG) const {
9106   assert(Subtarget->is64Bit() && "Result not type legalized?");
9107   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9108   SDValue TheChain = Op.getOperand(0);
9109   DebugLoc dl = Op.getDebugLoc();
9110   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9111   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9112   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9113                                    rax.getValue(2));
9114   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9115                             DAG.getConstant(32, MVT::i8));
9116   SDValue Ops[] = {
9117     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9118     rdx.getValue(1)
9119   };
9120   return DAG.getMergeValues(Ops, 2, dl);
9121 }
9122
9123 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9124                                             SelectionDAG &DAG) const {
9125   EVT SrcVT = Op.getOperand(0).getValueType();
9126   EVT DstVT = Op.getValueType();
9127   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9128          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9129   assert((DstVT == MVT::i64 ||
9130           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9131          "Unexpected custom BITCAST");
9132   // i64 <=> MMX conversions are Legal.
9133   if (SrcVT==MVT::i64 && DstVT.isVector())
9134     return Op;
9135   if (DstVT==MVT::i64 && SrcVT.isVector())
9136     return Op;
9137   // MMX <=> MMX conversions are Legal.
9138   if (SrcVT.isVector() && DstVT.isVector())
9139     return Op;
9140   // All other conversions need to be expanded.
9141   return SDValue();
9142 }
9143
9144 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9145   SDNode *Node = Op.getNode();
9146   DebugLoc dl = Node->getDebugLoc();
9147   EVT T = Node->getValueType(0);
9148   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9149                               DAG.getConstant(0, T), Node->getOperand(2));
9150   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9151                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9152                        Node->getOperand(0),
9153                        Node->getOperand(1), negOp,
9154                        cast<AtomicSDNode>(Node)->getSrcValue(),
9155                        cast<AtomicSDNode>(Node)->getAlignment());
9156 }
9157
9158 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9159   EVT VT = Op.getNode()->getValueType(0);
9160
9161   // Let legalize expand this if it isn't a legal type yet.
9162   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9163     return SDValue();
9164
9165   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9166
9167   unsigned Opc;
9168   bool ExtraOp = false;
9169   switch (Op.getOpcode()) {
9170   default: assert(0 && "Invalid code");
9171   case ISD::ADDC: Opc = X86ISD::ADD; break;
9172   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9173   case ISD::SUBC: Opc = X86ISD::SUB; break;
9174   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9175   }
9176
9177   if (!ExtraOp)
9178     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9179                        Op.getOperand(1));
9180   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9181                      Op.getOperand(1), Op.getOperand(2));
9182 }
9183
9184 /// LowerOperation - Provide custom lowering hooks for some operations.
9185 ///
9186 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9187   switch (Op.getOpcode()) {
9188   default: llvm_unreachable("Should not custom lower this!");
9189   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9190   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9191   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9192   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9193   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9194   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9195   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9196   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9197   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9198   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9199   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9200   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9201   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9202   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9203   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9204   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9205   case ISD::SHL_PARTS:
9206   case ISD::SRA_PARTS:
9207   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9208   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9209   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9210   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9211   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9212   case ISD::FABS:               return LowerFABS(Op, DAG);
9213   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9214   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9215   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9216   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9217   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9218   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9219   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9220   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9221   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9222   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9223   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9224   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9225   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9226   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9227   case ISD::FRAME_TO_ARGS_OFFSET:
9228                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9229   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9230   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9231   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9232   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9233   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9234   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9235   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9236   case ISD::SRA:
9237   case ISD::SRL:
9238   case ISD::SHL:                return LowerShift(Op, DAG);
9239   case ISD::SADDO:
9240   case ISD::UADDO:
9241   case ISD::SSUBO:
9242   case ISD::USUBO:
9243   case ISD::SMULO:
9244   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9245   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9246   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9247   case ISD::ADDC:
9248   case ISD::ADDE:
9249   case ISD::SUBC:
9250   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9251   }
9252 }
9253
9254 void X86TargetLowering::
9255 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9256                         SelectionDAG &DAG, unsigned NewOp) const {
9257   EVT T = Node->getValueType(0);
9258   DebugLoc dl = Node->getDebugLoc();
9259   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9260
9261   SDValue Chain = Node->getOperand(0);
9262   SDValue In1 = Node->getOperand(1);
9263   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9264                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9265   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9266                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9267   SDValue Ops[] = { Chain, In1, In2L, In2H };
9268   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9269   SDValue Result =
9270     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9271                             cast<MemSDNode>(Node)->getMemOperand());
9272   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9273   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9274   Results.push_back(Result.getValue(2));
9275 }
9276
9277 /// ReplaceNodeResults - Replace a node with an illegal result type
9278 /// with a new node built out of custom code.
9279 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9280                                            SmallVectorImpl<SDValue>&Results,
9281                                            SelectionDAG &DAG) const {
9282   DebugLoc dl = N->getDebugLoc();
9283   switch (N->getOpcode()) {
9284   default:
9285     assert(false && "Do not know how to custom type legalize this operation!");
9286     return;
9287   case ISD::ADDC:
9288   case ISD::ADDE:
9289   case ISD::SUBC:
9290   case ISD::SUBE:
9291     // We don't want to expand or promote these.
9292     return;
9293   case ISD::FP_TO_SINT: {
9294     std::pair<SDValue,SDValue> Vals =
9295         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9296     SDValue FIST = Vals.first, StackSlot = Vals.second;
9297     if (FIST.getNode() != 0) {
9298       EVT VT = N->getValueType(0);
9299       // Return a load from the stack slot.
9300       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9301                                     MachinePointerInfo(), false, false, 0));
9302     }
9303     return;
9304   }
9305   case ISD::READCYCLECOUNTER: {
9306     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9307     SDValue TheChain = N->getOperand(0);
9308     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9309     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9310                                      rd.getValue(1));
9311     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9312                                      eax.getValue(2));
9313     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9314     SDValue Ops[] = { eax, edx };
9315     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9316     Results.push_back(edx.getValue(1));
9317     return;
9318   }
9319   case ISD::ATOMIC_CMP_SWAP: {
9320     EVT T = N->getValueType(0);
9321     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9322     SDValue cpInL, cpInH;
9323     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9324                         DAG.getConstant(0, MVT::i32));
9325     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9326                         DAG.getConstant(1, MVT::i32));
9327     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9328     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9329                              cpInL.getValue(1));
9330     SDValue swapInL, swapInH;
9331     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9332                           DAG.getConstant(0, MVT::i32));
9333     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9334                           DAG.getConstant(1, MVT::i32));
9335     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9336                                cpInH.getValue(1));
9337     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9338                                swapInL.getValue(1));
9339     SDValue Ops[] = { swapInH.getValue(0),
9340                       N->getOperand(1),
9341                       swapInH.getValue(1) };
9342     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9343     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9344     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9345                                              Ops, 3, T, MMO);
9346     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9347                                         MVT::i32, Result.getValue(1));
9348     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9349                                         MVT::i32, cpOutL.getValue(2));
9350     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9351     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9352     Results.push_back(cpOutH.getValue(1));
9353     return;
9354   }
9355   case ISD::ATOMIC_LOAD_ADD:
9356     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9357     return;
9358   case ISD::ATOMIC_LOAD_AND:
9359     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9360     return;
9361   case ISD::ATOMIC_LOAD_NAND:
9362     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9363     return;
9364   case ISD::ATOMIC_LOAD_OR:
9365     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9366     return;
9367   case ISD::ATOMIC_LOAD_SUB:
9368     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9369     return;
9370   case ISD::ATOMIC_LOAD_XOR:
9371     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9372     return;
9373   case ISD::ATOMIC_SWAP:
9374     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9375     return;
9376   }
9377 }
9378
9379 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9380   switch (Opcode) {
9381   default: return NULL;
9382   case X86ISD::BSF:                return "X86ISD::BSF";
9383   case X86ISD::BSR:                return "X86ISD::BSR";
9384   case X86ISD::SHLD:               return "X86ISD::SHLD";
9385   case X86ISD::SHRD:               return "X86ISD::SHRD";
9386   case X86ISD::FAND:               return "X86ISD::FAND";
9387   case X86ISD::FOR:                return "X86ISD::FOR";
9388   case X86ISD::FXOR:               return "X86ISD::FXOR";
9389   case X86ISD::FSRL:               return "X86ISD::FSRL";
9390   case X86ISD::FILD:               return "X86ISD::FILD";
9391   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9392   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9393   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9394   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9395   case X86ISD::FLD:                return "X86ISD::FLD";
9396   case X86ISD::FST:                return "X86ISD::FST";
9397   case X86ISD::CALL:               return "X86ISD::CALL";
9398   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9399   case X86ISD::BT:                 return "X86ISD::BT";
9400   case X86ISD::CMP:                return "X86ISD::CMP";
9401   case X86ISD::COMI:               return "X86ISD::COMI";
9402   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9403   case X86ISD::SETCC:              return "X86ISD::SETCC";
9404   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9405   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9406   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9407   case X86ISD::CMOV:               return "X86ISD::CMOV";
9408   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9409   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9410   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9411   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9412   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9413   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9414   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9415   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9416   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9417   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9418   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9419   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9420   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9421   case X86ISD::PANDN:              return "X86ISD::PANDN";
9422   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9423   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9424   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9425   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9426   case X86ISD::FMAX:               return "X86ISD::FMAX";
9427   case X86ISD::FMIN:               return "X86ISD::FMIN";
9428   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9429   case X86ISD::FRCP:               return "X86ISD::FRCP";
9430   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9431   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9432   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9433   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9434   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9435   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9436   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9437   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9438   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9439   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9440   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9441   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9442   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9443   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9444   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9445   case X86ISD::VSHL:               return "X86ISD::VSHL";
9446   case X86ISD::VSRL:               return "X86ISD::VSRL";
9447   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9448   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9449   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9450   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9451   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9452   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9453   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9454   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9455   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9456   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9457   case X86ISD::ADD:                return "X86ISD::ADD";
9458   case X86ISD::SUB:                return "X86ISD::SUB";
9459   case X86ISD::ADC:                return "X86ISD::ADC";
9460   case X86ISD::SBB:                return "X86ISD::SBB";
9461   case X86ISD::SMUL:               return "X86ISD::SMUL";
9462   case X86ISD::UMUL:               return "X86ISD::UMUL";
9463   case X86ISD::INC:                return "X86ISD::INC";
9464   case X86ISD::DEC:                return "X86ISD::DEC";
9465   case X86ISD::OR:                 return "X86ISD::OR";
9466   case X86ISD::XOR:                return "X86ISD::XOR";
9467   case X86ISD::AND:                return "X86ISD::AND";
9468   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9469   case X86ISD::PTEST:              return "X86ISD::PTEST";
9470   case X86ISD::TESTP:              return "X86ISD::TESTP";
9471   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9472   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9473   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9474   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9475   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9476   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9477   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9478   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9479   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9480   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9481   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9482   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9483   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9484   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9485   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9486   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9487   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9488   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9489   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9490   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9491   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9492   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9493   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9494   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9495   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9496   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9497   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9498   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9499   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9500   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9501   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9502   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9503   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9504   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9505   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9506   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9507   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9508   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9509   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9510   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9511   }
9512 }
9513
9514 // isLegalAddressingMode - Return true if the addressing mode represented
9515 // by AM is legal for this target, for a load/store of the specified type.
9516 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9517                                               const Type *Ty) const {
9518   // X86 supports extremely general addressing modes.
9519   CodeModel::Model M = getTargetMachine().getCodeModel();
9520   Reloc::Model R = getTargetMachine().getRelocationModel();
9521
9522   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9523   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9524     return false;
9525
9526   if (AM.BaseGV) {
9527     unsigned GVFlags =
9528       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9529
9530     // If a reference to this global requires an extra load, we can't fold it.
9531     if (isGlobalStubReference(GVFlags))
9532       return false;
9533
9534     // If BaseGV requires a register for the PIC base, we cannot also have a
9535     // BaseReg specified.
9536     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9537       return false;
9538
9539     // If lower 4G is not available, then we must use rip-relative addressing.
9540     if ((M != CodeModel::Small || R != Reloc::Static) &&
9541         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9542       return false;
9543   }
9544
9545   switch (AM.Scale) {
9546   case 0:
9547   case 1:
9548   case 2:
9549   case 4:
9550   case 8:
9551     // These scales always work.
9552     break;
9553   case 3:
9554   case 5:
9555   case 9:
9556     // These scales are formed with basereg+scalereg.  Only accept if there is
9557     // no basereg yet.
9558     if (AM.HasBaseReg)
9559       return false;
9560     break;
9561   default:  // Other stuff never works.
9562     return false;
9563   }
9564
9565   return true;
9566 }
9567
9568
9569 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9570   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9571     return false;
9572   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9573   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9574   if (NumBits1 <= NumBits2)
9575     return false;
9576   return true;
9577 }
9578
9579 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9580   if (!VT1.isInteger() || !VT2.isInteger())
9581     return false;
9582   unsigned NumBits1 = VT1.getSizeInBits();
9583   unsigned NumBits2 = VT2.getSizeInBits();
9584   if (NumBits1 <= NumBits2)
9585     return false;
9586   return true;
9587 }
9588
9589 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9590   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9591   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9592 }
9593
9594 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9595   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9596   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9597 }
9598
9599 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9600   // i16 instructions are longer (0x66 prefix) and potentially slower.
9601   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9602 }
9603
9604 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9605 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9606 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9607 /// are assumed to be legal.
9608 bool
9609 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9610                                       EVT VT) const {
9611   // Very little shuffling can be done for 64-bit vectors right now.
9612   if (VT.getSizeInBits() == 64)
9613     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9614
9615   // FIXME: pshufb, blends, shifts.
9616   return (VT.getVectorNumElements() == 2 ||
9617           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9618           isMOVLMask(M, VT) ||
9619           isSHUFPMask(M, VT) ||
9620           isPSHUFDMask(M, VT) ||
9621           isPSHUFHWMask(M, VT) ||
9622           isPSHUFLWMask(M, VT) ||
9623           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9624           isUNPCKLMask(M, VT) ||
9625           isUNPCKHMask(M, VT) ||
9626           isUNPCKL_v_undef_Mask(M, VT) ||
9627           isUNPCKH_v_undef_Mask(M, VT));
9628 }
9629
9630 bool
9631 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9632                                           EVT VT) const {
9633   unsigned NumElts = VT.getVectorNumElements();
9634   // FIXME: This collection of masks seems suspect.
9635   if (NumElts == 2)
9636     return true;
9637   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9638     return (isMOVLMask(Mask, VT)  ||
9639             isCommutedMOVLMask(Mask, VT, true) ||
9640             isSHUFPMask(Mask, VT) ||
9641             isCommutedSHUFPMask(Mask, VT));
9642   }
9643   return false;
9644 }
9645
9646 //===----------------------------------------------------------------------===//
9647 //                           X86 Scheduler Hooks
9648 //===----------------------------------------------------------------------===//
9649
9650 // private utility function
9651 MachineBasicBlock *
9652 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9653                                                        MachineBasicBlock *MBB,
9654                                                        unsigned regOpc,
9655                                                        unsigned immOpc,
9656                                                        unsigned LoadOpc,
9657                                                        unsigned CXchgOpc,
9658                                                        unsigned notOpc,
9659                                                        unsigned EAXreg,
9660                                                        TargetRegisterClass *RC,
9661                                                        bool invSrc) const {
9662   // For the atomic bitwise operator, we generate
9663   //   thisMBB:
9664   //   newMBB:
9665   //     ld  t1 = [bitinstr.addr]
9666   //     op  t2 = t1, [bitinstr.val]
9667   //     mov EAX = t1
9668   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9669   //     bz  newMBB
9670   //     fallthrough -->nextMBB
9671   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9672   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9673   MachineFunction::iterator MBBIter = MBB;
9674   ++MBBIter;
9675
9676   /// First build the CFG
9677   MachineFunction *F = MBB->getParent();
9678   MachineBasicBlock *thisMBB = MBB;
9679   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9680   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9681   F->insert(MBBIter, newMBB);
9682   F->insert(MBBIter, nextMBB);
9683
9684   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9685   nextMBB->splice(nextMBB->begin(), thisMBB,
9686                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9687                   thisMBB->end());
9688   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9689
9690   // Update thisMBB to fall through to newMBB
9691   thisMBB->addSuccessor(newMBB);
9692
9693   // newMBB jumps to itself and fall through to nextMBB
9694   newMBB->addSuccessor(nextMBB);
9695   newMBB->addSuccessor(newMBB);
9696
9697   // Insert instructions into newMBB based on incoming instruction
9698   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9699          "unexpected number of operands");
9700   DebugLoc dl = bInstr->getDebugLoc();
9701   MachineOperand& destOper = bInstr->getOperand(0);
9702   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9703   int numArgs = bInstr->getNumOperands() - 1;
9704   for (int i=0; i < numArgs; ++i)
9705     argOpers[i] = &bInstr->getOperand(i+1);
9706
9707   // x86 address has 4 operands: base, index, scale, and displacement
9708   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9709   int valArgIndx = lastAddrIndx + 1;
9710
9711   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9712   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9713   for (int i=0; i <= lastAddrIndx; ++i)
9714     (*MIB).addOperand(*argOpers[i]);
9715
9716   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9717   if (invSrc) {
9718     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9719   }
9720   else
9721     tt = t1;
9722
9723   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9724   assert((argOpers[valArgIndx]->isReg() ||
9725           argOpers[valArgIndx]->isImm()) &&
9726          "invalid operand");
9727   if (argOpers[valArgIndx]->isReg())
9728     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9729   else
9730     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9731   MIB.addReg(tt);
9732   (*MIB).addOperand(*argOpers[valArgIndx]);
9733
9734   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9735   MIB.addReg(t1);
9736
9737   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9738   for (int i=0; i <= lastAddrIndx; ++i)
9739     (*MIB).addOperand(*argOpers[i]);
9740   MIB.addReg(t2);
9741   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9742   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9743                     bInstr->memoperands_end());
9744
9745   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9746   MIB.addReg(EAXreg);
9747
9748   // insert branch
9749   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9750
9751   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9752   return nextMBB;
9753 }
9754
9755 // private utility function:  64 bit atomics on 32 bit host.
9756 MachineBasicBlock *
9757 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9758                                                        MachineBasicBlock *MBB,
9759                                                        unsigned regOpcL,
9760                                                        unsigned regOpcH,
9761                                                        unsigned immOpcL,
9762                                                        unsigned immOpcH,
9763                                                        bool invSrc) const {
9764   // For the atomic bitwise operator, we generate
9765   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9766   //     ld t1,t2 = [bitinstr.addr]
9767   //   newMBB:
9768   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9769   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9770   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9771   //     mov ECX, EBX <- t5, t6
9772   //     mov EAX, EDX <- t1, t2
9773   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9774   //     mov t3, t4 <- EAX, EDX
9775   //     bz  newMBB
9776   //     result in out1, out2
9777   //     fallthrough -->nextMBB
9778
9779   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9780   const unsigned LoadOpc = X86::MOV32rm;
9781   const unsigned NotOpc = X86::NOT32r;
9782   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9783   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9784   MachineFunction::iterator MBBIter = MBB;
9785   ++MBBIter;
9786
9787   /// First build the CFG
9788   MachineFunction *F = MBB->getParent();
9789   MachineBasicBlock *thisMBB = MBB;
9790   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9791   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9792   F->insert(MBBIter, newMBB);
9793   F->insert(MBBIter, nextMBB);
9794
9795   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9796   nextMBB->splice(nextMBB->begin(), thisMBB,
9797                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9798                   thisMBB->end());
9799   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9800
9801   // Update thisMBB to fall through to newMBB
9802   thisMBB->addSuccessor(newMBB);
9803
9804   // newMBB jumps to itself and fall through to nextMBB
9805   newMBB->addSuccessor(nextMBB);
9806   newMBB->addSuccessor(newMBB);
9807
9808   DebugLoc dl = bInstr->getDebugLoc();
9809   // Insert instructions into newMBB based on incoming instruction
9810   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9811   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9812          "unexpected number of operands");
9813   MachineOperand& dest1Oper = bInstr->getOperand(0);
9814   MachineOperand& dest2Oper = bInstr->getOperand(1);
9815   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9816   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9817     argOpers[i] = &bInstr->getOperand(i+2);
9818
9819     // We use some of the operands multiple times, so conservatively just
9820     // clear any kill flags that might be present.
9821     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9822       argOpers[i]->setIsKill(false);
9823   }
9824
9825   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9826   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9827
9828   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9829   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9830   for (int i=0; i <= lastAddrIndx; ++i)
9831     (*MIB).addOperand(*argOpers[i]);
9832   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9833   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9834   // add 4 to displacement.
9835   for (int i=0; i <= lastAddrIndx-2; ++i)
9836     (*MIB).addOperand(*argOpers[i]);
9837   MachineOperand newOp3 = *(argOpers[3]);
9838   if (newOp3.isImm())
9839     newOp3.setImm(newOp3.getImm()+4);
9840   else
9841     newOp3.setOffset(newOp3.getOffset()+4);
9842   (*MIB).addOperand(newOp3);
9843   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9844
9845   // t3/4 are defined later, at the bottom of the loop
9846   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9847   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9848   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9849     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9850   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9851     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9852
9853   // The subsequent operations should be using the destination registers of
9854   //the PHI instructions.
9855   if (invSrc) {
9856     t1 = F->getRegInfo().createVirtualRegister(RC);
9857     t2 = F->getRegInfo().createVirtualRegister(RC);
9858     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9859     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9860   } else {
9861     t1 = dest1Oper.getReg();
9862     t2 = dest2Oper.getReg();
9863   }
9864
9865   int valArgIndx = lastAddrIndx + 1;
9866   assert((argOpers[valArgIndx]->isReg() ||
9867           argOpers[valArgIndx]->isImm()) &&
9868          "invalid operand");
9869   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9870   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9871   if (argOpers[valArgIndx]->isReg())
9872     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9873   else
9874     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9875   if (regOpcL != X86::MOV32rr)
9876     MIB.addReg(t1);
9877   (*MIB).addOperand(*argOpers[valArgIndx]);
9878   assert(argOpers[valArgIndx + 1]->isReg() ==
9879          argOpers[valArgIndx]->isReg());
9880   assert(argOpers[valArgIndx + 1]->isImm() ==
9881          argOpers[valArgIndx]->isImm());
9882   if (argOpers[valArgIndx + 1]->isReg())
9883     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9884   else
9885     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9886   if (regOpcH != X86::MOV32rr)
9887     MIB.addReg(t2);
9888   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9889
9890   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9891   MIB.addReg(t1);
9892   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9893   MIB.addReg(t2);
9894
9895   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9896   MIB.addReg(t5);
9897   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9898   MIB.addReg(t6);
9899
9900   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9901   for (int i=0; i <= lastAddrIndx; ++i)
9902     (*MIB).addOperand(*argOpers[i]);
9903
9904   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9905   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9906                     bInstr->memoperands_end());
9907
9908   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9909   MIB.addReg(X86::EAX);
9910   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9911   MIB.addReg(X86::EDX);
9912
9913   // insert branch
9914   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9915
9916   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9917   return nextMBB;
9918 }
9919
9920 // private utility function
9921 MachineBasicBlock *
9922 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9923                                                       MachineBasicBlock *MBB,
9924                                                       unsigned cmovOpc) const {
9925   // For the atomic min/max operator, we generate
9926   //   thisMBB:
9927   //   newMBB:
9928   //     ld t1 = [min/max.addr]
9929   //     mov t2 = [min/max.val]
9930   //     cmp  t1, t2
9931   //     cmov[cond] t2 = t1
9932   //     mov EAX = t1
9933   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9934   //     bz   newMBB
9935   //     fallthrough -->nextMBB
9936   //
9937   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9938   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9939   MachineFunction::iterator MBBIter = MBB;
9940   ++MBBIter;
9941
9942   /// First build the CFG
9943   MachineFunction *F = MBB->getParent();
9944   MachineBasicBlock *thisMBB = MBB;
9945   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9946   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9947   F->insert(MBBIter, newMBB);
9948   F->insert(MBBIter, nextMBB);
9949
9950   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9951   nextMBB->splice(nextMBB->begin(), thisMBB,
9952                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9953                   thisMBB->end());
9954   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9955
9956   // Update thisMBB to fall through to newMBB
9957   thisMBB->addSuccessor(newMBB);
9958
9959   // newMBB jumps to newMBB and fall through to nextMBB
9960   newMBB->addSuccessor(nextMBB);
9961   newMBB->addSuccessor(newMBB);
9962
9963   DebugLoc dl = mInstr->getDebugLoc();
9964   // Insert instructions into newMBB based on incoming instruction
9965   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9966          "unexpected number of operands");
9967   MachineOperand& destOper = mInstr->getOperand(0);
9968   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9969   int numArgs = mInstr->getNumOperands() - 1;
9970   for (int i=0; i < numArgs; ++i)
9971     argOpers[i] = &mInstr->getOperand(i+1);
9972
9973   // x86 address has 4 operands: base, index, scale, and displacement
9974   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9975   int valArgIndx = lastAddrIndx + 1;
9976
9977   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9978   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9979   for (int i=0; i <= lastAddrIndx; ++i)
9980     (*MIB).addOperand(*argOpers[i]);
9981
9982   // We only support register and immediate values
9983   assert((argOpers[valArgIndx]->isReg() ||
9984           argOpers[valArgIndx]->isImm()) &&
9985          "invalid operand");
9986
9987   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9988   if (argOpers[valArgIndx]->isReg())
9989     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9990   else
9991     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9992   (*MIB).addOperand(*argOpers[valArgIndx]);
9993
9994   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9995   MIB.addReg(t1);
9996
9997   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9998   MIB.addReg(t1);
9999   MIB.addReg(t2);
10000
10001   // Generate movc
10002   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10003   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10004   MIB.addReg(t2);
10005   MIB.addReg(t1);
10006
10007   // Cmp and exchange if none has modified the memory location
10008   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10009   for (int i=0; i <= lastAddrIndx; ++i)
10010     (*MIB).addOperand(*argOpers[i]);
10011   MIB.addReg(t3);
10012   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10013   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10014                     mInstr->memoperands_end());
10015
10016   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10017   MIB.addReg(X86::EAX);
10018
10019   // insert branch
10020   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10021
10022   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10023   return nextMBB;
10024 }
10025
10026 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10027 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10028 // in the .td file.
10029 MachineBasicBlock *
10030 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10031                             unsigned numArgs, bool memArg) const {
10032   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10033          "Target must have SSE4.2 or AVX features enabled");
10034
10035   DebugLoc dl = MI->getDebugLoc();
10036   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10037   unsigned Opc;
10038   if (!Subtarget->hasAVX()) {
10039     if (memArg)
10040       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10041     else
10042       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10043   } else {
10044     if (memArg)
10045       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10046     else
10047       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10048   }
10049
10050   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10051   for (unsigned i = 0; i < numArgs; ++i) {
10052     MachineOperand &Op = MI->getOperand(i+1);
10053     if (!(Op.isReg() && Op.isImplicit()))
10054       MIB.addOperand(Op);
10055   }
10056   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10057     .addReg(X86::XMM0);
10058
10059   MI->eraseFromParent();
10060   return BB;
10061 }
10062
10063 MachineBasicBlock *
10064 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10065   DebugLoc dl = MI->getDebugLoc();
10066   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10067
10068   // Address into RAX/EAX, other two args into ECX, EDX.
10069   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10070   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10071   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10072   for (int i = 0; i < X86::AddrNumOperands; ++i)
10073     MIB.addOperand(MI->getOperand(i));
10074
10075   unsigned ValOps = X86::AddrNumOperands;
10076   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10077     .addReg(MI->getOperand(ValOps).getReg());
10078   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10079     .addReg(MI->getOperand(ValOps+1).getReg());
10080
10081   // The instruction doesn't actually take any operands though.
10082   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10083
10084   MI->eraseFromParent(); // The pseudo is gone now.
10085   return BB;
10086 }
10087
10088 MachineBasicBlock *
10089 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10090   DebugLoc dl = MI->getDebugLoc();
10091   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10092
10093   // First arg in ECX, the second in EAX.
10094   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10095     .addReg(MI->getOperand(0).getReg());
10096   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10097     .addReg(MI->getOperand(1).getReg());
10098
10099   // The instruction doesn't actually take any operands though.
10100   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10101
10102   MI->eraseFromParent(); // The pseudo is gone now.
10103   return BB;
10104 }
10105
10106 MachineBasicBlock *
10107 X86TargetLowering::EmitVAARG64WithCustomInserter(
10108                    MachineInstr *MI,
10109                    MachineBasicBlock *MBB) const {
10110   // Emit va_arg instruction on X86-64.
10111
10112   // Operands to this pseudo-instruction:
10113   // 0  ) Output        : destination address (reg)
10114   // 1-5) Input         : va_list address (addr, i64mem)
10115   // 6  ) ArgSize       : Size (in bytes) of vararg type
10116   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10117   // 8  ) Align         : Alignment of type
10118   // 9  ) EFLAGS (implicit-def)
10119
10120   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10121   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10122
10123   unsigned DestReg = MI->getOperand(0).getReg();
10124   MachineOperand &Base = MI->getOperand(1);
10125   MachineOperand &Scale = MI->getOperand(2);
10126   MachineOperand &Index = MI->getOperand(3);
10127   MachineOperand &Disp = MI->getOperand(4);
10128   MachineOperand &Segment = MI->getOperand(5);
10129   unsigned ArgSize = MI->getOperand(6).getImm();
10130   unsigned ArgMode = MI->getOperand(7).getImm();
10131   unsigned Align = MI->getOperand(8).getImm();
10132
10133   // Memory Reference
10134   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10135   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10136   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10137
10138   // Machine Information
10139   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10140   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10141   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10142   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10143   DebugLoc DL = MI->getDebugLoc();
10144
10145   // struct va_list {
10146   //   i32   gp_offset
10147   //   i32   fp_offset
10148   //   i64   overflow_area (address)
10149   //   i64   reg_save_area (address)
10150   // }
10151   // sizeof(va_list) = 24
10152   // alignment(va_list) = 8
10153
10154   unsigned TotalNumIntRegs = 6;
10155   unsigned TotalNumXMMRegs = 8;
10156   bool UseGPOffset = (ArgMode == 1);
10157   bool UseFPOffset = (ArgMode == 2);
10158   unsigned MaxOffset = TotalNumIntRegs * 8 +
10159                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10160
10161   /* Align ArgSize to a multiple of 8 */
10162   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10163   bool NeedsAlign = (Align > 8);
10164
10165   MachineBasicBlock *thisMBB = MBB;
10166   MachineBasicBlock *overflowMBB;
10167   MachineBasicBlock *offsetMBB;
10168   MachineBasicBlock *endMBB;
10169
10170   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10171   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10172   unsigned OffsetReg = 0;
10173
10174   if (!UseGPOffset && !UseFPOffset) {
10175     // If we only pull from the overflow region, we don't create a branch.
10176     // We don't need to alter control flow.
10177     OffsetDestReg = 0; // unused
10178     OverflowDestReg = DestReg;
10179
10180     offsetMBB = NULL;
10181     overflowMBB = thisMBB;
10182     endMBB = thisMBB;
10183   } else {
10184     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10185     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10186     // If not, pull from overflow_area. (branch to overflowMBB)
10187     //
10188     //       thisMBB
10189     //         |     .
10190     //         |        .
10191     //     offsetMBB   overflowMBB
10192     //         |        .
10193     //         |     .
10194     //        endMBB
10195
10196     // Registers for the PHI in endMBB
10197     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10198     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10199
10200     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10201     MachineFunction *MF = MBB->getParent();
10202     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10203     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10204     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10205
10206     MachineFunction::iterator MBBIter = MBB;
10207     ++MBBIter;
10208
10209     // Insert the new basic blocks
10210     MF->insert(MBBIter, offsetMBB);
10211     MF->insert(MBBIter, overflowMBB);
10212     MF->insert(MBBIter, endMBB);
10213
10214     // Transfer the remainder of MBB and its successor edges to endMBB.
10215     endMBB->splice(endMBB->begin(), thisMBB,
10216                     llvm::next(MachineBasicBlock::iterator(MI)),
10217                     thisMBB->end());
10218     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10219
10220     // Make offsetMBB and overflowMBB successors of thisMBB
10221     thisMBB->addSuccessor(offsetMBB);
10222     thisMBB->addSuccessor(overflowMBB);
10223
10224     // endMBB is a successor of both offsetMBB and overflowMBB
10225     offsetMBB->addSuccessor(endMBB);
10226     overflowMBB->addSuccessor(endMBB);
10227
10228     // Load the offset value into a register
10229     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10230     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10231       .addOperand(Base)
10232       .addOperand(Scale)
10233       .addOperand(Index)
10234       .addDisp(Disp, UseFPOffset ? 4 : 0)
10235       .addOperand(Segment)
10236       .setMemRefs(MMOBegin, MMOEnd);
10237
10238     // Check if there is enough room left to pull this argument.
10239     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10240       .addReg(OffsetReg)
10241       .addImm(MaxOffset + 8 - ArgSizeA8);
10242
10243     // Branch to "overflowMBB" if offset >= max
10244     // Fall through to "offsetMBB" otherwise
10245     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10246       .addMBB(overflowMBB);
10247   }
10248
10249   // In offsetMBB, emit code to use the reg_save_area.
10250   if (offsetMBB) {
10251     assert(OffsetReg != 0);
10252
10253     // Read the reg_save_area address.
10254     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10255     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10256       .addOperand(Base)
10257       .addOperand(Scale)
10258       .addOperand(Index)
10259       .addDisp(Disp, 16)
10260       .addOperand(Segment)
10261       .setMemRefs(MMOBegin, MMOEnd);
10262
10263     // Zero-extend the offset
10264     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10265       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10266         .addImm(0)
10267         .addReg(OffsetReg)
10268         .addImm(X86::sub_32bit);
10269
10270     // Add the offset to the reg_save_area to get the final address.
10271     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10272       .addReg(OffsetReg64)
10273       .addReg(RegSaveReg);
10274
10275     // Compute the offset for the next argument
10276     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10277     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10278       .addReg(OffsetReg)
10279       .addImm(UseFPOffset ? 16 : 8);
10280
10281     // Store it back into the va_list.
10282     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10283       .addOperand(Base)
10284       .addOperand(Scale)
10285       .addOperand(Index)
10286       .addDisp(Disp, UseFPOffset ? 4 : 0)
10287       .addOperand(Segment)
10288       .addReg(NextOffsetReg)
10289       .setMemRefs(MMOBegin, MMOEnd);
10290
10291     // Jump to endMBB
10292     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10293       .addMBB(endMBB);
10294   }
10295
10296   //
10297   // Emit code to use overflow area
10298   //
10299
10300   // Load the overflow_area address into a register.
10301   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10302   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10303     .addOperand(Base)
10304     .addOperand(Scale)
10305     .addOperand(Index)
10306     .addDisp(Disp, 8)
10307     .addOperand(Segment)
10308     .setMemRefs(MMOBegin, MMOEnd);
10309
10310   // If we need to align it, do so. Otherwise, just copy the address
10311   // to OverflowDestReg.
10312   if (NeedsAlign) {
10313     // Align the overflow address
10314     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10315     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10316
10317     // aligned_addr = (addr + (align-1)) & ~(align-1)
10318     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10319       .addReg(OverflowAddrReg)
10320       .addImm(Align-1);
10321
10322     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10323       .addReg(TmpReg)
10324       .addImm(~(uint64_t)(Align-1));
10325   } else {
10326     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10327       .addReg(OverflowAddrReg);
10328   }
10329
10330   // Compute the next overflow address after this argument.
10331   // (the overflow address should be kept 8-byte aligned)
10332   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10333   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10334     .addReg(OverflowDestReg)
10335     .addImm(ArgSizeA8);
10336
10337   // Store the new overflow address.
10338   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10339     .addOperand(Base)
10340     .addOperand(Scale)
10341     .addOperand(Index)
10342     .addDisp(Disp, 8)
10343     .addOperand(Segment)
10344     .addReg(NextAddrReg)
10345     .setMemRefs(MMOBegin, MMOEnd);
10346
10347   // If we branched, emit the PHI to the front of endMBB.
10348   if (offsetMBB) {
10349     BuildMI(*endMBB, endMBB->begin(), DL,
10350             TII->get(X86::PHI), DestReg)
10351       .addReg(OffsetDestReg).addMBB(offsetMBB)
10352       .addReg(OverflowDestReg).addMBB(overflowMBB);
10353   }
10354
10355   // Erase the pseudo instruction
10356   MI->eraseFromParent();
10357
10358   return endMBB;
10359 }
10360
10361 MachineBasicBlock *
10362 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10363                                                  MachineInstr *MI,
10364                                                  MachineBasicBlock *MBB) const {
10365   // Emit code to save XMM registers to the stack. The ABI says that the
10366   // number of registers to save is given in %al, so it's theoretically
10367   // possible to do an indirect jump trick to avoid saving all of them,
10368   // however this code takes a simpler approach and just executes all
10369   // of the stores if %al is non-zero. It's less code, and it's probably
10370   // easier on the hardware branch predictor, and stores aren't all that
10371   // expensive anyway.
10372
10373   // Create the new basic blocks. One block contains all the XMM stores,
10374   // and one block is the final destination regardless of whether any
10375   // stores were performed.
10376   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10377   MachineFunction *F = MBB->getParent();
10378   MachineFunction::iterator MBBIter = MBB;
10379   ++MBBIter;
10380   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10381   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10382   F->insert(MBBIter, XMMSaveMBB);
10383   F->insert(MBBIter, EndMBB);
10384
10385   // Transfer the remainder of MBB and its successor edges to EndMBB.
10386   EndMBB->splice(EndMBB->begin(), MBB,
10387                  llvm::next(MachineBasicBlock::iterator(MI)),
10388                  MBB->end());
10389   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10390
10391   // The original block will now fall through to the XMM save block.
10392   MBB->addSuccessor(XMMSaveMBB);
10393   // The XMMSaveMBB will fall through to the end block.
10394   XMMSaveMBB->addSuccessor(EndMBB);
10395
10396   // Now add the instructions.
10397   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10398   DebugLoc DL = MI->getDebugLoc();
10399
10400   unsigned CountReg = MI->getOperand(0).getReg();
10401   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10402   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10403
10404   if (!Subtarget->isTargetWin64()) {
10405     // If %al is 0, branch around the XMM save block.
10406     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10407     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10408     MBB->addSuccessor(EndMBB);
10409   }
10410
10411   // In the XMM save block, save all the XMM argument registers.
10412   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10413     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10414     MachineMemOperand *MMO =
10415       F->getMachineMemOperand(
10416           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10417         MachineMemOperand::MOStore,
10418         /*Size=*/16, /*Align=*/16);
10419     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10420       .addFrameIndex(RegSaveFrameIndex)
10421       .addImm(/*Scale=*/1)
10422       .addReg(/*IndexReg=*/0)
10423       .addImm(/*Disp=*/Offset)
10424       .addReg(/*Segment=*/0)
10425       .addReg(MI->getOperand(i).getReg())
10426       .addMemOperand(MMO);
10427   }
10428
10429   MI->eraseFromParent();   // The pseudo instruction is gone now.
10430
10431   return EndMBB;
10432 }
10433
10434 MachineBasicBlock *
10435 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10436                                      MachineBasicBlock *BB) const {
10437   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10438   DebugLoc DL = MI->getDebugLoc();
10439
10440   // To "insert" a SELECT_CC instruction, we actually have to insert the
10441   // diamond control-flow pattern.  The incoming instruction knows the
10442   // destination vreg to set, the condition code register to branch on, the
10443   // true/false values to select between, and a branch opcode to use.
10444   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10445   MachineFunction::iterator It = BB;
10446   ++It;
10447
10448   //  thisMBB:
10449   //  ...
10450   //   TrueVal = ...
10451   //   cmpTY ccX, r1, r2
10452   //   bCC copy1MBB
10453   //   fallthrough --> copy0MBB
10454   MachineBasicBlock *thisMBB = BB;
10455   MachineFunction *F = BB->getParent();
10456   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10457   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10458   F->insert(It, copy0MBB);
10459   F->insert(It, sinkMBB);
10460
10461   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10462   // live into the sink and copy blocks.
10463   const MachineFunction *MF = BB->getParent();
10464   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10465   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10466
10467   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10468     const MachineOperand &MO = MI->getOperand(I);
10469     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10470     unsigned Reg = MO.getReg();
10471     if (Reg != X86::EFLAGS) continue;
10472     copy0MBB->addLiveIn(Reg);
10473     sinkMBB->addLiveIn(Reg);
10474   }
10475
10476   // Transfer the remainder of BB and its successor edges to sinkMBB.
10477   sinkMBB->splice(sinkMBB->begin(), BB,
10478                   llvm::next(MachineBasicBlock::iterator(MI)),
10479                   BB->end());
10480   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10481
10482   // Add the true and fallthrough blocks as its successors.
10483   BB->addSuccessor(copy0MBB);
10484   BB->addSuccessor(sinkMBB);
10485
10486   // Create the conditional branch instruction.
10487   unsigned Opc =
10488     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10489   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10490
10491   //  copy0MBB:
10492   //   %FalseValue = ...
10493   //   # fallthrough to sinkMBB
10494   copy0MBB->addSuccessor(sinkMBB);
10495
10496   //  sinkMBB:
10497   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10498   //  ...
10499   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10500           TII->get(X86::PHI), MI->getOperand(0).getReg())
10501     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10502     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10503
10504   MI->eraseFromParent();   // The pseudo instruction is gone now.
10505   return sinkMBB;
10506 }
10507
10508 MachineBasicBlock *
10509 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10510                                           MachineBasicBlock *BB) const {
10511   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10512   DebugLoc DL = MI->getDebugLoc();
10513
10514   assert(!Subtarget->isTargetEnvMacho());
10515
10516   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10517   // non-trivial part is impdef of ESP.
10518
10519   if (Subtarget->isTargetWin64()) {
10520     if (Subtarget->isTargetCygMing()) {
10521       // ___chkstk(Mingw64):
10522       // Clobbers R10, R11, RAX and EFLAGS.
10523       // Updates RSP.
10524       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10525         .addExternalSymbol("___chkstk")
10526         .addReg(X86::RAX, RegState::Implicit)
10527         .addReg(X86::RSP, RegState::Implicit)
10528         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10529         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10530         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10531     } else {
10532       // __chkstk(MSVCRT): does not update stack pointer.
10533       // Clobbers R10, R11 and EFLAGS.
10534       // FIXME: RAX(allocated size) might be reused and not killed.
10535       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10536         .addExternalSymbol("__chkstk")
10537         .addReg(X86::RAX, RegState::Implicit)
10538         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10539       // RAX has the offset to subtracted from RSP.
10540       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10541         .addReg(X86::RSP)
10542         .addReg(X86::RAX);
10543     }
10544   } else {
10545     const char *StackProbeSymbol =
10546       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10547
10548     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10549       .addExternalSymbol(StackProbeSymbol)
10550       .addReg(X86::EAX, RegState::Implicit)
10551       .addReg(X86::ESP, RegState::Implicit)
10552       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10553       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10554       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10555   }
10556
10557   MI->eraseFromParent();   // The pseudo instruction is gone now.
10558   return BB;
10559 }
10560
10561 MachineBasicBlock *
10562 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10563                                       MachineBasicBlock *BB) const {
10564   // This is pretty easy.  We're taking the value that we received from
10565   // our load from the relocation, sticking it in either RDI (x86-64)
10566   // or EAX and doing an indirect call.  The return value will then
10567   // be in the normal return register.
10568   const X86InstrInfo *TII
10569     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10570   DebugLoc DL = MI->getDebugLoc();
10571   MachineFunction *F = BB->getParent();
10572
10573   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10574   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10575
10576   if (Subtarget->is64Bit()) {
10577     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10578                                       TII->get(X86::MOV64rm), X86::RDI)
10579     .addReg(X86::RIP)
10580     .addImm(0).addReg(0)
10581     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10582                       MI->getOperand(3).getTargetFlags())
10583     .addReg(0);
10584     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10585     addDirectMem(MIB, X86::RDI);
10586   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10587     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10588                                       TII->get(X86::MOV32rm), X86::EAX)
10589     .addReg(0)
10590     .addImm(0).addReg(0)
10591     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10592                       MI->getOperand(3).getTargetFlags())
10593     .addReg(0);
10594     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10595     addDirectMem(MIB, X86::EAX);
10596   } else {
10597     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10598                                       TII->get(X86::MOV32rm), X86::EAX)
10599     .addReg(TII->getGlobalBaseReg(F))
10600     .addImm(0).addReg(0)
10601     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10602                       MI->getOperand(3).getTargetFlags())
10603     .addReg(0);
10604     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10605     addDirectMem(MIB, X86::EAX);
10606   }
10607
10608   MI->eraseFromParent(); // The pseudo instruction is gone now.
10609   return BB;
10610 }
10611
10612 MachineBasicBlock *
10613 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10614                                                MachineBasicBlock *BB) const {
10615   switch (MI->getOpcode()) {
10616   default: assert(false && "Unexpected instr type to insert");
10617   case X86::TAILJMPd64:
10618   case X86::TAILJMPr64:
10619   case X86::TAILJMPm64:
10620     assert(!"TAILJMP64 would not be touched here.");
10621   case X86::TCRETURNdi64:
10622   case X86::TCRETURNri64:
10623   case X86::TCRETURNmi64:
10624     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10625     // On AMD64, additional defs should be added before register allocation.
10626     if (!Subtarget->isTargetWin64()) {
10627       MI->addRegisterDefined(X86::RSI);
10628       MI->addRegisterDefined(X86::RDI);
10629       MI->addRegisterDefined(X86::XMM6);
10630       MI->addRegisterDefined(X86::XMM7);
10631       MI->addRegisterDefined(X86::XMM8);
10632       MI->addRegisterDefined(X86::XMM9);
10633       MI->addRegisterDefined(X86::XMM10);
10634       MI->addRegisterDefined(X86::XMM11);
10635       MI->addRegisterDefined(X86::XMM12);
10636       MI->addRegisterDefined(X86::XMM13);
10637       MI->addRegisterDefined(X86::XMM14);
10638       MI->addRegisterDefined(X86::XMM15);
10639     }
10640     return BB;
10641   case X86::WIN_ALLOCA:
10642     return EmitLoweredWinAlloca(MI, BB);
10643   case X86::TLSCall_32:
10644   case X86::TLSCall_64:
10645     return EmitLoweredTLSCall(MI, BB);
10646   case X86::CMOV_GR8:
10647   case X86::CMOV_FR32:
10648   case X86::CMOV_FR64:
10649   case X86::CMOV_V4F32:
10650   case X86::CMOV_V2F64:
10651   case X86::CMOV_V2I64:
10652   case X86::CMOV_GR16:
10653   case X86::CMOV_GR32:
10654   case X86::CMOV_RFP32:
10655   case X86::CMOV_RFP64:
10656   case X86::CMOV_RFP80:
10657     return EmitLoweredSelect(MI, BB);
10658
10659   case X86::FP32_TO_INT16_IN_MEM:
10660   case X86::FP32_TO_INT32_IN_MEM:
10661   case X86::FP32_TO_INT64_IN_MEM:
10662   case X86::FP64_TO_INT16_IN_MEM:
10663   case X86::FP64_TO_INT32_IN_MEM:
10664   case X86::FP64_TO_INT64_IN_MEM:
10665   case X86::FP80_TO_INT16_IN_MEM:
10666   case X86::FP80_TO_INT32_IN_MEM:
10667   case X86::FP80_TO_INT64_IN_MEM: {
10668     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10669     DebugLoc DL = MI->getDebugLoc();
10670
10671     // Change the floating point control register to use "round towards zero"
10672     // mode when truncating to an integer value.
10673     MachineFunction *F = BB->getParent();
10674     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10675     addFrameReference(BuildMI(*BB, MI, DL,
10676                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10677
10678     // Load the old value of the high byte of the control word...
10679     unsigned OldCW =
10680       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10681     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10682                       CWFrameIdx);
10683
10684     // Set the high part to be round to zero...
10685     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10686       .addImm(0xC7F);
10687
10688     // Reload the modified control word now...
10689     addFrameReference(BuildMI(*BB, MI, DL,
10690                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10691
10692     // Restore the memory image of control word to original value
10693     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10694       .addReg(OldCW);
10695
10696     // Get the X86 opcode to use.
10697     unsigned Opc;
10698     switch (MI->getOpcode()) {
10699     default: llvm_unreachable("illegal opcode!");
10700     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10701     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10702     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10703     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10704     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10705     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10706     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10707     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10708     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10709     }
10710
10711     X86AddressMode AM;
10712     MachineOperand &Op = MI->getOperand(0);
10713     if (Op.isReg()) {
10714       AM.BaseType = X86AddressMode::RegBase;
10715       AM.Base.Reg = Op.getReg();
10716     } else {
10717       AM.BaseType = X86AddressMode::FrameIndexBase;
10718       AM.Base.FrameIndex = Op.getIndex();
10719     }
10720     Op = MI->getOperand(1);
10721     if (Op.isImm())
10722       AM.Scale = Op.getImm();
10723     Op = MI->getOperand(2);
10724     if (Op.isImm())
10725       AM.IndexReg = Op.getImm();
10726     Op = MI->getOperand(3);
10727     if (Op.isGlobal()) {
10728       AM.GV = Op.getGlobal();
10729     } else {
10730       AM.Disp = Op.getImm();
10731     }
10732     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10733                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10734
10735     // Reload the original control word now.
10736     addFrameReference(BuildMI(*BB, MI, DL,
10737                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10738
10739     MI->eraseFromParent();   // The pseudo instruction is gone now.
10740     return BB;
10741   }
10742     // String/text processing lowering.
10743   case X86::PCMPISTRM128REG:
10744   case X86::VPCMPISTRM128REG:
10745     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10746   case X86::PCMPISTRM128MEM:
10747   case X86::VPCMPISTRM128MEM:
10748     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10749   case X86::PCMPESTRM128REG:
10750   case X86::VPCMPESTRM128REG:
10751     return EmitPCMP(MI, BB, 5, false /* in mem */);
10752   case X86::PCMPESTRM128MEM:
10753   case X86::VPCMPESTRM128MEM:
10754     return EmitPCMP(MI, BB, 5, true /* in mem */);
10755
10756     // Thread synchronization.
10757   case X86::MONITOR:
10758     return EmitMonitor(MI, BB);
10759   case X86::MWAIT:
10760     return EmitMwait(MI, BB);
10761
10762     // Atomic Lowering.
10763   case X86::ATOMAND32:
10764     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10765                                                X86::AND32ri, X86::MOV32rm,
10766                                                X86::LCMPXCHG32,
10767                                                X86::NOT32r, X86::EAX,
10768                                                X86::GR32RegisterClass);
10769   case X86::ATOMOR32:
10770     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10771                                                X86::OR32ri, X86::MOV32rm,
10772                                                X86::LCMPXCHG32,
10773                                                X86::NOT32r, X86::EAX,
10774                                                X86::GR32RegisterClass);
10775   case X86::ATOMXOR32:
10776     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10777                                                X86::XOR32ri, X86::MOV32rm,
10778                                                X86::LCMPXCHG32,
10779                                                X86::NOT32r, X86::EAX,
10780                                                X86::GR32RegisterClass);
10781   case X86::ATOMNAND32:
10782     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10783                                                X86::AND32ri, X86::MOV32rm,
10784                                                X86::LCMPXCHG32,
10785                                                X86::NOT32r, X86::EAX,
10786                                                X86::GR32RegisterClass, true);
10787   case X86::ATOMMIN32:
10788     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10789   case X86::ATOMMAX32:
10790     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10791   case X86::ATOMUMIN32:
10792     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10793   case X86::ATOMUMAX32:
10794     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10795
10796   case X86::ATOMAND16:
10797     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10798                                                X86::AND16ri, X86::MOV16rm,
10799                                                X86::LCMPXCHG16,
10800                                                X86::NOT16r, X86::AX,
10801                                                X86::GR16RegisterClass);
10802   case X86::ATOMOR16:
10803     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10804                                                X86::OR16ri, X86::MOV16rm,
10805                                                X86::LCMPXCHG16,
10806                                                X86::NOT16r, X86::AX,
10807                                                X86::GR16RegisterClass);
10808   case X86::ATOMXOR16:
10809     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10810                                                X86::XOR16ri, X86::MOV16rm,
10811                                                X86::LCMPXCHG16,
10812                                                X86::NOT16r, X86::AX,
10813                                                X86::GR16RegisterClass);
10814   case X86::ATOMNAND16:
10815     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10816                                                X86::AND16ri, X86::MOV16rm,
10817                                                X86::LCMPXCHG16,
10818                                                X86::NOT16r, X86::AX,
10819                                                X86::GR16RegisterClass, true);
10820   case X86::ATOMMIN16:
10821     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10822   case X86::ATOMMAX16:
10823     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10824   case X86::ATOMUMIN16:
10825     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10826   case X86::ATOMUMAX16:
10827     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10828
10829   case X86::ATOMAND8:
10830     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10831                                                X86::AND8ri, X86::MOV8rm,
10832                                                X86::LCMPXCHG8,
10833                                                X86::NOT8r, X86::AL,
10834                                                X86::GR8RegisterClass);
10835   case X86::ATOMOR8:
10836     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10837                                                X86::OR8ri, X86::MOV8rm,
10838                                                X86::LCMPXCHG8,
10839                                                X86::NOT8r, X86::AL,
10840                                                X86::GR8RegisterClass);
10841   case X86::ATOMXOR8:
10842     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10843                                                X86::XOR8ri, X86::MOV8rm,
10844                                                X86::LCMPXCHG8,
10845                                                X86::NOT8r, X86::AL,
10846                                                X86::GR8RegisterClass);
10847   case X86::ATOMNAND8:
10848     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10849                                                X86::AND8ri, X86::MOV8rm,
10850                                                X86::LCMPXCHG8,
10851                                                X86::NOT8r, X86::AL,
10852                                                X86::GR8RegisterClass, true);
10853   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10854   // This group is for 64-bit host.
10855   case X86::ATOMAND64:
10856     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10857                                                X86::AND64ri32, X86::MOV64rm,
10858                                                X86::LCMPXCHG64,
10859                                                X86::NOT64r, X86::RAX,
10860                                                X86::GR64RegisterClass);
10861   case X86::ATOMOR64:
10862     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10863                                                X86::OR64ri32, X86::MOV64rm,
10864                                                X86::LCMPXCHG64,
10865                                                X86::NOT64r, X86::RAX,
10866                                                X86::GR64RegisterClass);
10867   case X86::ATOMXOR64:
10868     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10869                                                X86::XOR64ri32, X86::MOV64rm,
10870                                                X86::LCMPXCHG64,
10871                                                X86::NOT64r, X86::RAX,
10872                                                X86::GR64RegisterClass);
10873   case X86::ATOMNAND64:
10874     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10875                                                X86::AND64ri32, X86::MOV64rm,
10876                                                X86::LCMPXCHG64,
10877                                                X86::NOT64r, X86::RAX,
10878                                                X86::GR64RegisterClass, true);
10879   case X86::ATOMMIN64:
10880     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10881   case X86::ATOMMAX64:
10882     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10883   case X86::ATOMUMIN64:
10884     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10885   case X86::ATOMUMAX64:
10886     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10887
10888   // This group does 64-bit operations on a 32-bit host.
10889   case X86::ATOMAND6432:
10890     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10891                                                X86::AND32rr, X86::AND32rr,
10892                                                X86::AND32ri, X86::AND32ri,
10893                                                false);
10894   case X86::ATOMOR6432:
10895     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10896                                                X86::OR32rr, X86::OR32rr,
10897                                                X86::OR32ri, X86::OR32ri,
10898                                                false);
10899   case X86::ATOMXOR6432:
10900     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10901                                                X86::XOR32rr, X86::XOR32rr,
10902                                                X86::XOR32ri, X86::XOR32ri,
10903                                                false);
10904   case X86::ATOMNAND6432:
10905     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10906                                                X86::AND32rr, X86::AND32rr,
10907                                                X86::AND32ri, X86::AND32ri,
10908                                                true);
10909   case X86::ATOMADD6432:
10910     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10911                                                X86::ADD32rr, X86::ADC32rr,
10912                                                X86::ADD32ri, X86::ADC32ri,
10913                                                false);
10914   case X86::ATOMSUB6432:
10915     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10916                                                X86::SUB32rr, X86::SBB32rr,
10917                                                X86::SUB32ri, X86::SBB32ri,
10918                                                false);
10919   case X86::ATOMSWAP6432:
10920     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10921                                                X86::MOV32rr, X86::MOV32rr,
10922                                                X86::MOV32ri, X86::MOV32ri,
10923                                                false);
10924   case X86::VASTART_SAVE_XMM_REGS:
10925     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10926
10927   case X86::VAARG_64:
10928     return EmitVAARG64WithCustomInserter(MI, BB);
10929   }
10930 }
10931
10932 //===----------------------------------------------------------------------===//
10933 //                           X86 Optimization Hooks
10934 //===----------------------------------------------------------------------===//
10935
10936 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10937                                                        const APInt &Mask,
10938                                                        APInt &KnownZero,
10939                                                        APInt &KnownOne,
10940                                                        const SelectionDAG &DAG,
10941                                                        unsigned Depth) const {
10942   unsigned Opc = Op.getOpcode();
10943   assert((Opc >= ISD::BUILTIN_OP_END ||
10944           Opc == ISD::INTRINSIC_WO_CHAIN ||
10945           Opc == ISD::INTRINSIC_W_CHAIN ||
10946           Opc == ISD::INTRINSIC_VOID) &&
10947          "Should use MaskedValueIsZero if you don't know whether Op"
10948          " is a target node!");
10949
10950   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10951   switch (Opc) {
10952   default: break;
10953   case X86ISD::ADD:
10954   case X86ISD::SUB:
10955   case X86ISD::ADC:
10956   case X86ISD::SBB:
10957   case X86ISD::SMUL:
10958   case X86ISD::UMUL:
10959   case X86ISD::INC:
10960   case X86ISD::DEC:
10961   case X86ISD::OR:
10962   case X86ISD::XOR:
10963   case X86ISD::AND:
10964     // These nodes' second result is a boolean.
10965     if (Op.getResNo() == 0)
10966       break;
10967     // Fallthrough
10968   case X86ISD::SETCC:
10969     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10970                                        Mask.getBitWidth() - 1);
10971     break;
10972   }
10973 }
10974
10975 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10976                                                          unsigned Depth) const {
10977   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10978   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10979     return Op.getValueType().getScalarType().getSizeInBits();
10980
10981   // Fallback case.
10982   return 1;
10983 }
10984
10985 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10986 /// node is a GlobalAddress + offset.
10987 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10988                                        const GlobalValue* &GA,
10989                                        int64_t &Offset) const {
10990   if (N->getOpcode() == X86ISD::Wrapper) {
10991     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10992       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10993       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10994       return true;
10995     }
10996   }
10997   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10998 }
10999
11000 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11001 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11002 /// if the load addresses are consecutive, non-overlapping, and in the right
11003 /// order.
11004 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11005                                      TargetLowering::DAGCombinerInfo &DCI) {
11006   DebugLoc dl = N->getDebugLoc();
11007   EVT VT = N->getValueType(0);
11008
11009   if (VT.getSizeInBits() != 128)
11010     return SDValue();
11011
11012   // Don't create instructions with illegal types after legalize types has run.
11013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11014   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11015     return SDValue();
11016
11017   SmallVector<SDValue, 16> Elts;
11018   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11019     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11020
11021   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11022 }
11023
11024 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11025 /// generation and convert it from being a bunch of shuffles and extracts
11026 /// to a simple store and scalar loads to extract the elements.
11027 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11028                                                 const TargetLowering &TLI) {
11029   SDValue InputVector = N->getOperand(0);
11030
11031   // Only operate on vectors of 4 elements, where the alternative shuffling
11032   // gets to be more expensive.
11033   if (InputVector.getValueType() != MVT::v4i32)
11034     return SDValue();
11035
11036   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11037   // single use which is a sign-extend or zero-extend, and all elements are
11038   // used.
11039   SmallVector<SDNode *, 4> Uses;
11040   unsigned ExtractedElements = 0;
11041   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11042        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11043     if (UI.getUse().getResNo() != InputVector.getResNo())
11044       return SDValue();
11045
11046     SDNode *Extract = *UI;
11047     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11048       return SDValue();
11049
11050     if (Extract->getValueType(0) != MVT::i32)
11051       return SDValue();
11052     if (!Extract->hasOneUse())
11053       return SDValue();
11054     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11055         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11056       return SDValue();
11057     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11058       return SDValue();
11059
11060     // Record which element was extracted.
11061     ExtractedElements |=
11062       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11063
11064     Uses.push_back(Extract);
11065   }
11066
11067   // If not all the elements were used, this may not be worthwhile.
11068   if (ExtractedElements != 15)
11069     return SDValue();
11070
11071   // Ok, we've now decided to do the transformation.
11072   DebugLoc dl = InputVector.getDebugLoc();
11073
11074   // Store the value to a temporary stack slot.
11075   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11076   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11077                             MachinePointerInfo(), false, false, 0);
11078
11079   // Replace each use (extract) with a load of the appropriate element.
11080   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11081        UE = Uses.end(); UI != UE; ++UI) {
11082     SDNode *Extract = *UI;
11083
11084     // cOMpute the element's address.
11085     SDValue Idx = Extract->getOperand(1);
11086     unsigned EltSize =
11087         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11088     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11089     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11090
11091     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11092                                      StackPtr, OffsetVal);
11093
11094     // Load the scalar.
11095     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11096                                      ScalarAddr, MachinePointerInfo(),
11097                                      false, false, 0);
11098
11099     // Replace the exact with the load.
11100     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11101   }
11102
11103   // The replacement was made in place; don't return anything.
11104   return SDValue();
11105 }
11106
11107 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11108 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11109                                     const X86Subtarget *Subtarget) {
11110   DebugLoc DL = N->getDebugLoc();
11111   SDValue Cond = N->getOperand(0);
11112   // Get the LHS/RHS of the select.
11113   SDValue LHS = N->getOperand(1);
11114   SDValue RHS = N->getOperand(2);
11115
11116   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11117   // instructions match the semantics of the common C idiom x<y?x:y but not
11118   // x<=y?x:y, because of how they handle negative zero (which can be
11119   // ignored in unsafe-math mode).
11120   if (Subtarget->hasSSE2() &&
11121       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11122       Cond.getOpcode() == ISD::SETCC) {
11123     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11124
11125     unsigned Opcode = 0;
11126     // Check for x CC y ? x : y.
11127     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11128         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11129       switch (CC) {
11130       default: break;
11131       case ISD::SETULT:
11132         // Converting this to a min would handle NaNs incorrectly, and swapping
11133         // the operands would cause it to handle comparisons between positive
11134         // and negative zero incorrectly.
11135         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11136           if (!UnsafeFPMath &&
11137               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11138             break;
11139           std::swap(LHS, RHS);
11140         }
11141         Opcode = X86ISD::FMIN;
11142         break;
11143       case ISD::SETOLE:
11144         // Converting this to a min would handle comparisons between positive
11145         // and negative zero incorrectly.
11146         if (!UnsafeFPMath &&
11147             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11148           break;
11149         Opcode = X86ISD::FMIN;
11150         break;
11151       case ISD::SETULE:
11152         // Converting this to a min would handle both negative zeros and NaNs
11153         // incorrectly, but we can swap the operands to fix both.
11154         std::swap(LHS, RHS);
11155       case ISD::SETOLT:
11156       case ISD::SETLT:
11157       case ISD::SETLE:
11158         Opcode = X86ISD::FMIN;
11159         break;
11160
11161       case ISD::SETOGE:
11162         // Converting this to a max would handle comparisons between positive
11163         // and negative zero incorrectly.
11164         if (!UnsafeFPMath &&
11165             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11166           break;
11167         Opcode = X86ISD::FMAX;
11168         break;
11169       case ISD::SETUGT:
11170         // Converting this to a max would handle NaNs incorrectly, and swapping
11171         // the operands would cause it to handle comparisons between positive
11172         // and negative zero incorrectly.
11173         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11174           if (!UnsafeFPMath &&
11175               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11176             break;
11177           std::swap(LHS, RHS);
11178         }
11179         Opcode = X86ISD::FMAX;
11180         break;
11181       case ISD::SETUGE:
11182         // Converting this to a max would handle both negative zeros and NaNs
11183         // incorrectly, but we can swap the operands to fix both.
11184         std::swap(LHS, RHS);
11185       case ISD::SETOGT:
11186       case ISD::SETGT:
11187       case ISD::SETGE:
11188         Opcode = X86ISD::FMAX;
11189         break;
11190       }
11191     // Check for x CC y ? y : x -- a min/max with reversed arms.
11192     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11193                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11194       switch (CC) {
11195       default: break;
11196       case ISD::SETOGE:
11197         // Converting this to a min would handle comparisons between positive
11198         // and negative zero incorrectly, and swapping the operands would
11199         // cause it to handle NaNs incorrectly.
11200         if (!UnsafeFPMath &&
11201             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11202           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11203             break;
11204           std::swap(LHS, RHS);
11205         }
11206         Opcode = X86ISD::FMIN;
11207         break;
11208       case ISD::SETUGT:
11209         // Converting this to a min would handle NaNs incorrectly.
11210         if (!UnsafeFPMath &&
11211             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11212           break;
11213         Opcode = X86ISD::FMIN;
11214         break;
11215       case ISD::SETUGE:
11216         // Converting this to a min would handle both negative zeros and NaNs
11217         // incorrectly, but we can swap the operands to fix both.
11218         std::swap(LHS, RHS);
11219       case ISD::SETOGT:
11220       case ISD::SETGT:
11221       case ISD::SETGE:
11222         Opcode = X86ISD::FMIN;
11223         break;
11224
11225       case ISD::SETULT:
11226         // Converting this to a max would handle NaNs incorrectly.
11227         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11228           break;
11229         Opcode = X86ISD::FMAX;
11230         break;
11231       case ISD::SETOLE:
11232         // Converting this to a max would handle comparisons between positive
11233         // and negative zero incorrectly, and swapping the operands would
11234         // cause it to handle NaNs incorrectly.
11235         if (!UnsafeFPMath &&
11236             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11237           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11238             break;
11239           std::swap(LHS, RHS);
11240         }
11241         Opcode = X86ISD::FMAX;
11242         break;
11243       case ISD::SETULE:
11244         // Converting this to a max would handle both negative zeros and NaNs
11245         // incorrectly, but we can swap the operands to fix both.
11246         std::swap(LHS, RHS);
11247       case ISD::SETOLT:
11248       case ISD::SETLT:
11249       case ISD::SETLE:
11250         Opcode = X86ISD::FMAX;
11251         break;
11252       }
11253     }
11254
11255     if (Opcode)
11256       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11257   }
11258
11259   // If this is a select between two integer constants, try to do some
11260   // optimizations.
11261   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11262     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11263       // Don't do this for crazy integer types.
11264       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11265         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11266         // so that TrueC (the true value) is larger than FalseC.
11267         bool NeedsCondInvert = false;
11268
11269         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11270             // Efficiently invertible.
11271             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11272              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11273               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11274           NeedsCondInvert = true;
11275           std::swap(TrueC, FalseC);
11276         }
11277
11278         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11279         if (FalseC->getAPIntValue() == 0 &&
11280             TrueC->getAPIntValue().isPowerOf2()) {
11281           if (NeedsCondInvert) // Invert the condition if needed.
11282             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11283                                DAG.getConstant(1, Cond.getValueType()));
11284
11285           // Zero extend the condition if needed.
11286           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11287
11288           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11289           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11290                              DAG.getConstant(ShAmt, MVT::i8));
11291         }
11292
11293         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11294         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11295           if (NeedsCondInvert) // Invert the condition if needed.
11296             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11297                                DAG.getConstant(1, Cond.getValueType()));
11298
11299           // Zero extend the condition if needed.
11300           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11301                              FalseC->getValueType(0), Cond);
11302           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11303                              SDValue(FalseC, 0));
11304         }
11305
11306         // Optimize cases that will turn into an LEA instruction.  This requires
11307         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11308         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11309           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11310           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11311
11312           bool isFastMultiplier = false;
11313           if (Diff < 10) {
11314             switch ((unsigned char)Diff) {
11315               default: break;
11316               case 1:  // result = add base, cond
11317               case 2:  // result = lea base(    , cond*2)
11318               case 3:  // result = lea base(cond, cond*2)
11319               case 4:  // result = lea base(    , cond*4)
11320               case 5:  // result = lea base(cond, cond*4)
11321               case 8:  // result = lea base(    , cond*8)
11322               case 9:  // result = lea base(cond, cond*8)
11323                 isFastMultiplier = true;
11324                 break;
11325             }
11326           }
11327
11328           if (isFastMultiplier) {
11329             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11330             if (NeedsCondInvert) // Invert the condition if needed.
11331               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11332                                  DAG.getConstant(1, Cond.getValueType()));
11333
11334             // Zero extend the condition if needed.
11335             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11336                                Cond);
11337             // Scale the condition by the difference.
11338             if (Diff != 1)
11339               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11340                                  DAG.getConstant(Diff, Cond.getValueType()));
11341
11342             // Add the base if non-zero.
11343             if (FalseC->getAPIntValue() != 0)
11344               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11345                                  SDValue(FalseC, 0));
11346             return Cond;
11347           }
11348         }
11349       }
11350   }
11351
11352   return SDValue();
11353 }
11354
11355 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11356 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11357                                   TargetLowering::DAGCombinerInfo &DCI) {
11358   DebugLoc DL = N->getDebugLoc();
11359
11360   // If the flag operand isn't dead, don't touch this CMOV.
11361   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11362     return SDValue();
11363
11364   SDValue FalseOp = N->getOperand(0);
11365   SDValue TrueOp = N->getOperand(1);
11366   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11367   SDValue Cond = N->getOperand(3);
11368   if (CC == X86::COND_E || CC == X86::COND_NE) {
11369     switch (Cond.getOpcode()) {
11370     default: break;
11371     case X86ISD::BSR:
11372     case X86ISD::BSF:
11373       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11374       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11375         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11376     }
11377   }
11378
11379   // If this is a select between two integer constants, try to do some
11380   // optimizations.  Note that the operands are ordered the opposite of SELECT
11381   // operands.
11382   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11383     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11384       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11385       // larger than FalseC (the false value).
11386       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11387         CC = X86::GetOppositeBranchCondition(CC);
11388         std::swap(TrueC, FalseC);
11389       }
11390
11391       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11392       // This is efficient for any integer data type (including i8/i16) and
11393       // shift amount.
11394       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11395         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11396                            DAG.getConstant(CC, MVT::i8), Cond);
11397
11398         // Zero extend the condition if needed.
11399         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11400
11401         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11402         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11403                            DAG.getConstant(ShAmt, MVT::i8));
11404         if (N->getNumValues() == 2)  // Dead flag value?
11405           return DCI.CombineTo(N, Cond, SDValue());
11406         return Cond;
11407       }
11408
11409       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11410       // for any integer data type, including i8/i16.
11411       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11412         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11413                            DAG.getConstant(CC, MVT::i8), Cond);
11414
11415         // Zero extend the condition if needed.
11416         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11417                            FalseC->getValueType(0), Cond);
11418         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11419                            SDValue(FalseC, 0));
11420
11421         if (N->getNumValues() == 2)  // Dead flag value?
11422           return DCI.CombineTo(N, Cond, SDValue());
11423         return Cond;
11424       }
11425
11426       // Optimize cases that will turn into an LEA instruction.  This requires
11427       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11428       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11429         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11430         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11431
11432         bool isFastMultiplier = false;
11433         if (Diff < 10) {
11434           switch ((unsigned char)Diff) {
11435           default: break;
11436           case 1:  // result = add base, cond
11437           case 2:  // result = lea base(    , cond*2)
11438           case 3:  // result = lea base(cond, cond*2)
11439           case 4:  // result = lea base(    , cond*4)
11440           case 5:  // result = lea base(cond, cond*4)
11441           case 8:  // result = lea base(    , cond*8)
11442           case 9:  // result = lea base(cond, cond*8)
11443             isFastMultiplier = true;
11444             break;
11445           }
11446         }
11447
11448         if (isFastMultiplier) {
11449           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11450           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11451                              DAG.getConstant(CC, MVT::i8), Cond);
11452           // Zero extend the condition if needed.
11453           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11454                              Cond);
11455           // Scale the condition by the difference.
11456           if (Diff != 1)
11457             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11458                                DAG.getConstant(Diff, Cond.getValueType()));
11459
11460           // Add the base if non-zero.
11461           if (FalseC->getAPIntValue() != 0)
11462             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11463                                SDValue(FalseC, 0));
11464           if (N->getNumValues() == 2)  // Dead flag value?
11465             return DCI.CombineTo(N, Cond, SDValue());
11466           return Cond;
11467         }
11468       }
11469     }
11470   }
11471   return SDValue();
11472 }
11473
11474
11475 /// PerformMulCombine - Optimize a single multiply with constant into two
11476 /// in order to implement it with two cheaper instructions, e.g.
11477 /// LEA + SHL, LEA + LEA.
11478 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11479                                  TargetLowering::DAGCombinerInfo &DCI) {
11480   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11481     return SDValue();
11482
11483   EVT VT = N->getValueType(0);
11484   if (VT != MVT::i64)
11485     return SDValue();
11486
11487   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11488   if (!C)
11489     return SDValue();
11490   uint64_t MulAmt = C->getZExtValue();
11491   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11492     return SDValue();
11493
11494   uint64_t MulAmt1 = 0;
11495   uint64_t MulAmt2 = 0;
11496   if ((MulAmt % 9) == 0) {
11497     MulAmt1 = 9;
11498     MulAmt2 = MulAmt / 9;
11499   } else if ((MulAmt % 5) == 0) {
11500     MulAmt1 = 5;
11501     MulAmt2 = MulAmt / 5;
11502   } else if ((MulAmt % 3) == 0) {
11503     MulAmt1 = 3;
11504     MulAmt2 = MulAmt / 3;
11505   }
11506   if (MulAmt2 &&
11507       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11508     DebugLoc DL = N->getDebugLoc();
11509
11510     if (isPowerOf2_64(MulAmt2) &&
11511         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11512       // If second multiplifer is pow2, issue it first. We want the multiply by
11513       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11514       // is an add.
11515       std::swap(MulAmt1, MulAmt2);
11516
11517     SDValue NewMul;
11518     if (isPowerOf2_64(MulAmt1))
11519       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11520                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11521     else
11522       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11523                            DAG.getConstant(MulAmt1, VT));
11524
11525     if (isPowerOf2_64(MulAmt2))
11526       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11527                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11528     else
11529       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11530                            DAG.getConstant(MulAmt2, VT));
11531
11532     // Do not add new nodes to DAG combiner worklist.
11533     DCI.CombineTo(N, NewMul, false);
11534   }
11535   return SDValue();
11536 }
11537
11538 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11539   SDValue N0 = N->getOperand(0);
11540   SDValue N1 = N->getOperand(1);
11541   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11542   EVT VT = N0.getValueType();
11543
11544   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11545   // since the result of setcc_c is all zero's or all ones.
11546   if (N1C && N0.getOpcode() == ISD::AND &&
11547       N0.getOperand(1).getOpcode() == ISD::Constant) {
11548     SDValue N00 = N0.getOperand(0);
11549     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11550         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11551           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11552          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11553       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11554       APInt ShAmt = N1C->getAPIntValue();
11555       Mask = Mask.shl(ShAmt);
11556       if (Mask != 0)
11557         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11558                            N00, DAG.getConstant(Mask, VT));
11559     }
11560   }
11561
11562   return SDValue();
11563 }
11564
11565 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11566 ///                       when possible.
11567 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11568                                    const X86Subtarget *Subtarget) {
11569   EVT VT = N->getValueType(0);
11570   if (!VT.isVector() && VT.isInteger() &&
11571       N->getOpcode() == ISD::SHL)
11572     return PerformSHLCombine(N, DAG);
11573
11574   // On X86 with SSE2 support, we can transform this to a vector shift if
11575   // all elements are shifted by the same amount.  We can't do this in legalize
11576   // because the a constant vector is typically transformed to a constant pool
11577   // so we have no knowledge of the shift amount.
11578   if (!Subtarget->hasSSE2())
11579     return SDValue();
11580
11581   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11582     return SDValue();
11583
11584   SDValue ShAmtOp = N->getOperand(1);
11585   EVT EltVT = VT.getVectorElementType();
11586   DebugLoc DL = N->getDebugLoc();
11587   SDValue BaseShAmt = SDValue();
11588   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11589     unsigned NumElts = VT.getVectorNumElements();
11590     unsigned i = 0;
11591     for (; i != NumElts; ++i) {
11592       SDValue Arg = ShAmtOp.getOperand(i);
11593       if (Arg.getOpcode() == ISD::UNDEF) continue;
11594       BaseShAmt = Arg;
11595       break;
11596     }
11597     for (; i != NumElts; ++i) {
11598       SDValue Arg = ShAmtOp.getOperand(i);
11599       if (Arg.getOpcode() == ISD::UNDEF) continue;
11600       if (Arg != BaseShAmt) {
11601         return SDValue();
11602       }
11603     }
11604   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11605              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11606     SDValue InVec = ShAmtOp.getOperand(0);
11607     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11608       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11609       unsigned i = 0;
11610       for (; i != NumElts; ++i) {
11611         SDValue Arg = InVec.getOperand(i);
11612         if (Arg.getOpcode() == ISD::UNDEF) continue;
11613         BaseShAmt = Arg;
11614         break;
11615       }
11616     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11617        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11618          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11619          if (C->getZExtValue() == SplatIdx)
11620            BaseShAmt = InVec.getOperand(1);
11621        }
11622     }
11623     if (BaseShAmt.getNode() == 0)
11624       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11625                               DAG.getIntPtrConstant(0));
11626   } else
11627     return SDValue();
11628
11629   // The shift amount is an i32.
11630   if (EltVT.bitsGT(MVT::i32))
11631     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11632   else if (EltVT.bitsLT(MVT::i32))
11633     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11634
11635   // The shift amount is identical so we can do a vector shift.
11636   SDValue  ValOp = N->getOperand(0);
11637   switch (N->getOpcode()) {
11638   default:
11639     llvm_unreachable("Unknown shift opcode!");
11640     break;
11641   case ISD::SHL:
11642     if (VT == MVT::v2i64)
11643       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11644                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11645                          ValOp, BaseShAmt);
11646     if (VT == MVT::v4i32)
11647       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11648                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11649                          ValOp, BaseShAmt);
11650     if (VT == MVT::v8i16)
11651       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11652                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11653                          ValOp, BaseShAmt);
11654     break;
11655   case ISD::SRA:
11656     if (VT == MVT::v4i32)
11657       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11658                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11659                          ValOp, BaseShAmt);
11660     if (VT == MVT::v8i16)
11661       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11662                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11663                          ValOp, BaseShAmt);
11664     break;
11665   case ISD::SRL:
11666     if (VT == MVT::v2i64)
11667       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11668                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11669                          ValOp, BaseShAmt);
11670     if (VT == MVT::v4i32)
11671       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11672                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11673                          ValOp, BaseShAmt);
11674     if (VT ==  MVT::v8i16)
11675       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11676                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11677                          ValOp, BaseShAmt);
11678     break;
11679   }
11680   return SDValue();
11681 }
11682
11683
11684 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11685 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11686 // and friends.  Likewise for OR -> CMPNEQSS.
11687 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11688                             TargetLowering::DAGCombinerInfo &DCI,
11689                             const X86Subtarget *Subtarget) {
11690   unsigned opcode;
11691
11692   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11693   // we're requiring SSE2 for both.
11694   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11695     SDValue N0 = N->getOperand(0);
11696     SDValue N1 = N->getOperand(1);
11697     SDValue CMP    = N0->getOperand(1);
11698     SDValue CMP0   = CMP->getOperand(0);
11699     SDValue CMP1   = CMP->getOperand(1);
11700     EVT     VT     = CMP0.getValueType();
11701     DebugLoc DL    = N->getDebugLoc();
11702
11703     if (VT == MVT::f32 || VT == MVT::f64) {
11704       bool ExpectingFlags = false;
11705       // Check for any users that want flags:
11706       for (SDNode::use_iterator UI = N->use_begin(),
11707              UE = N->use_end();
11708            !ExpectingFlags && UI != UE; ++UI)
11709         switch (UI->getOpcode()) {
11710         default:
11711         case ISD::BR_CC:
11712         case ISD::BRCOND:
11713         case ISD::SELECT:
11714           ExpectingFlags = true;
11715           break;
11716         case ISD::CopyToReg:
11717         case ISD::SIGN_EXTEND:
11718         case ISD::ZERO_EXTEND:
11719         case ISD::ANY_EXTEND:
11720           break;
11721         }
11722
11723       if (!ExpectingFlags) {
11724         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11725         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11726
11727         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11728           X86::CondCode tmp = cc0;
11729           cc0 = cc1;
11730           cc1 = tmp;
11731         }
11732
11733         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11734             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11735           bool is64BitFP = (CMP0.getValueType() == MVT::f64);
11736           X86ISD::NodeType NTOperator = is64BitFP ?
11737             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11738           // FIXME: need symbolic constants for these magic numbers.
11739           // See X86ATTInstPrinter.cpp:printSSECC().
11740           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11741           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP0, CMP1,
11742                                               DAG.getConstant(x86cc, MVT::i8));
11743           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11744                                               OnesOrZeroesF);
11745           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11746                                       DAG.getConstant(1, MVT::i32));
11747           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11748           return OneBitOfTruth;
11749         }
11750       }
11751     }
11752   }
11753   return SDValue();
11754 }
11755
11756 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11757                                  TargetLowering::DAGCombinerInfo &DCI,
11758                                  const X86Subtarget *Subtarget) {
11759   if (DCI.isBeforeLegalizeOps())
11760     return SDValue();
11761
11762   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11763   if (R.getNode())
11764     return R;
11765
11766   // Want to form PANDN nodes, in the hopes of then easily combining them with
11767   // OR and AND nodes to form PBLEND/PSIGN.
11768   EVT VT = N->getValueType(0);
11769   if (VT != MVT::v2i64)
11770     return SDValue();
11771
11772   SDValue N0 = N->getOperand(0);
11773   SDValue N1 = N->getOperand(1);
11774   DebugLoc DL = N->getDebugLoc();
11775
11776   // Check LHS for vnot
11777   if (N0.getOpcode() == ISD::XOR &&
11778       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11779     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11780
11781   // Check RHS for vnot
11782   if (N1.getOpcode() == ISD::XOR &&
11783       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11784     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11785
11786   return SDValue();
11787 }
11788
11789 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11790                                 TargetLowering::DAGCombinerInfo &DCI,
11791                                 const X86Subtarget *Subtarget) {
11792   if (DCI.isBeforeLegalizeOps())
11793     return SDValue();
11794
11795   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11796   if (R.getNode())
11797     return R;
11798
11799   EVT VT = N->getValueType(0);
11800   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11801     return SDValue();
11802
11803   SDValue N0 = N->getOperand(0);
11804   SDValue N1 = N->getOperand(1);
11805
11806   // look for psign/blend
11807   if (Subtarget->hasSSSE3()) {
11808     if (VT == MVT::v2i64) {
11809       // Canonicalize pandn to RHS
11810       if (N0.getOpcode() == X86ISD::PANDN)
11811         std::swap(N0, N1);
11812       // or (and (m, x), (pandn m, y))
11813       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11814         SDValue Mask = N1.getOperand(0);
11815         SDValue X    = N1.getOperand(1);
11816         SDValue Y;
11817         if (N0.getOperand(0) == Mask)
11818           Y = N0.getOperand(1);
11819         if (N0.getOperand(1) == Mask)
11820           Y = N0.getOperand(0);
11821
11822         // Check to see if the mask appeared in both the AND and PANDN and
11823         if (!Y.getNode())
11824           return SDValue();
11825
11826         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11827         if (Mask.getOpcode() != ISD::BITCAST ||
11828             X.getOpcode() != ISD::BITCAST ||
11829             Y.getOpcode() != ISD::BITCAST)
11830           return SDValue();
11831
11832         // Look through mask bitcast.
11833         Mask = Mask.getOperand(0);
11834         EVT MaskVT = Mask.getValueType();
11835
11836         // Validate that the Mask operand is a vector sra node.  The sra node
11837         // will be an intrinsic.
11838         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11839           return SDValue();
11840
11841         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11842         // there is no psrai.b
11843         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11844         case Intrinsic::x86_sse2_psrai_w:
11845         case Intrinsic::x86_sse2_psrai_d:
11846           break;
11847         default: return SDValue();
11848         }
11849
11850         // Check that the SRA is all signbits.
11851         SDValue SraC = Mask.getOperand(2);
11852         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11853         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11854         if ((SraAmt + 1) != EltBits)
11855           return SDValue();
11856
11857         DebugLoc DL = N->getDebugLoc();
11858
11859         // Now we know we at least have a plendvb with the mask val.  See if
11860         // we can form a psignb/w/d.
11861         // psign = x.type == y.type == mask.type && y = sub(0, x);
11862         X = X.getOperand(0);
11863         Y = Y.getOperand(0);
11864         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11865             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11866             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11867           unsigned Opc = 0;
11868           switch (EltBits) {
11869           case 8: Opc = X86ISD::PSIGNB; break;
11870           case 16: Opc = X86ISD::PSIGNW; break;
11871           case 32: Opc = X86ISD::PSIGND; break;
11872           default: break;
11873           }
11874           if (Opc) {
11875             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11876             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11877           }
11878         }
11879         // PBLENDVB only available on SSE 4.1
11880         if (!Subtarget->hasSSE41())
11881           return SDValue();
11882
11883         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11884         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11885         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11886         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11887         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11888       }
11889     }
11890   }
11891
11892   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11893   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11894     std::swap(N0, N1);
11895   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11896     return SDValue();
11897   if (!N0.hasOneUse() || !N1.hasOneUse())
11898     return SDValue();
11899
11900   SDValue ShAmt0 = N0.getOperand(1);
11901   if (ShAmt0.getValueType() != MVT::i8)
11902     return SDValue();
11903   SDValue ShAmt1 = N1.getOperand(1);
11904   if (ShAmt1.getValueType() != MVT::i8)
11905     return SDValue();
11906   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11907     ShAmt0 = ShAmt0.getOperand(0);
11908   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11909     ShAmt1 = ShAmt1.getOperand(0);
11910
11911   DebugLoc DL = N->getDebugLoc();
11912   unsigned Opc = X86ISD::SHLD;
11913   SDValue Op0 = N0.getOperand(0);
11914   SDValue Op1 = N1.getOperand(0);
11915   if (ShAmt0.getOpcode() == ISD::SUB) {
11916     Opc = X86ISD::SHRD;
11917     std::swap(Op0, Op1);
11918     std::swap(ShAmt0, ShAmt1);
11919   }
11920
11921   unsigned Bits = VT.getSizeInBits();
11922   if (ShAmt1.getOpcode() == ISD::SUB) {
11923     SDValue Sum = ShAmt1.getOperand(0);
11924     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11925       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11926       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11927         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11928       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11929         return DAG.getNode(Opc, DL, VT,
11930                            Op0, Op1,
11931                            DAG.getNode(ISD::TRUNCATE, DL,
11932                                        MVT::i8, ShAmt0));
11933     }
11934   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11935     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11936     if (ShAmt0C &&
11937         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11938       return DAG.getNode(Opc, DL, VT,
11939                          N0.getOperand(0), N1.getOperand(0),
11940                          DAG.getNode(ISD::TRUNCATE, DL,
11941                                        MVT::i8, ShAmt0));
11942   }
11943
11944   return SDValue();
11945 }
11946
11947 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11948 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11949                                    const X86Subtarget *Subtarget) {
11950   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11951   // the FP state in cases where an emms may be missing.
11952   // A preferable solution to the general problem is to figure out the right
11953   // places to insert EMMS.  This qualifies as a quick hack.
11954
11955   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11956   StoreSDNode *St = cast<StoreSDNode>(N);
11957   EVT VT = St->getValue().getValueType();
11958   if (VT.getSizeInBits() != 64)
11959     return SDValue();
11960
11961   const Function *F = DAG.getMachineFunction().getFunction();
11962   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11963   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11964     && Subtarget->hasSSE2();
11965   if ((VT.isVector() ||
11966        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11967       isa<LoadSDNode>(St->getValue()) &&
11968       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11969       St->getChain().hasOneUse() && !St->isVolatile()) {
11970     SDNode* LdVal = St->getValue().getNode();
11971     LoadSDNode *Ld = 0;
11972     int TokenFactorIndex = -1;
11973     SmallVector<SDValue, 8> Ops;
11974     SDNode* ChainVal = St->getChain().getNode();
11975     // Must be a store of a load.  We currently handle two cases:  the load
11976     // is a direct child, and it's under an intervening TokenFactor.  It is
11977     // possible to dig deeper under nested TokenFactors.
11978     if (ChainVal == LdVal)
11979       Ld = cast<LoadSDNode>(St->getChain());
11980     else if (St->getValue().hasOneUse() &&
11981              ChainVal->getOpcode() == ISD::TokenFactor) {
11982       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11983         if (ChainVal->getOperand(i).getNode() == LdVal) {
11984           TokenFactorIndex = i;
11985           Ld = cast<LoadSDNode>(St->getValue());
11986         } else
11987           Ops.push_back(ChainVal->getOperand(i));
11988       }
11989     }
11990
11991     if (!Ld || !ISD::isNormalLoad(Ld))
11992       return SDValue();
11993
11994     // If this is not the MMX case, i.e. we are just turning i64 load/store
11995     // into f64 load/store, avoid the transformation if there are multiple
11996     // uses of the loaded value.
11997     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11998       return SDValue();
11999
12000     DebugLoc LdDL = Ld->getDebugLoc();
12001     DebugLoc StDL = N->getDebugLoc();
12002     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12003     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12004     // pair instead.
12005     if (Subtarget->is64Bit() || F64IsLegal) {
12006       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12007       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12008                                   Ld->getPointerInfo(), Ld->isVolatile(),
12009                                   Ld->isNonTemporal(), Ld->getAlignment());
12010       SDValue NewChain = NewLd.getValue(1);
12011       if (TokenFactorIndex != -1) {
12012         Ops.push_back(NewChain);
12013         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12014                                Ops.size());
12015       }
12016       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12017                           St->getPointerInfo(),
12018                           St->isVolatile(), St->isNonTemporal(),
12019                           St->getAlignment());
12020     }
12021
12022     // Otherwise, lower to two pairs of 32-bit loads / stores.
12023     SDValue LoAddr = Ld->getBasePtr();
12024     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12025                                  DAG.getConstant(4, MVT::i32));
12026
12027     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12028                                Ld->getPointerInfo(),
12029                                Ld->isVolatile(), Ld->isNonTemporal(),
12030                                Ld->getAlignment());
12031     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12032                                Ld->getPointerInfo().getWithOffset(4),
12033                                Ld->isVolatile(), Ld->isNonTemporal(),
12034                                MinAlign(Ld->getAlignment(), 4));
12035
12036     SDValue NewChain = LoLd.getValue(1);
12037     if (TokenFactorIndex != -1) {
12038       Ops.push_back(LoLd);
12039       Ops.push_back(HiLd);
12040       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12041                              Ops.size());
12042     }
12043
12044     LoAddr = St->getBasePtr();
12045     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12046                          DAG.getConstant(4, MVT::i32));
12047
12048     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12049                                 St->getPointerInfo(),
12050                                 St->isVolatile(), St->isNonTemporal(),
12051                                 St->getAlignment());
12052     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12053                                 St->getPointerInfo().getWithOffset(4),
12054                                 St->isVolatile(),
12055                                 St->isNonTemporal(),
12056                                 MinAlign(St->getAlignment(), 4));
12057     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12058   }
12059   return SDValue();
12060 }
12061
12062 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12063 /// X86ISD::FXOR nodes.
12064 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12065   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12066   // F[X]OR(0.0, x) -> x
12067   // F[X]OR(x, 0.0) -> x
12068   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12069     if (C->getValueAPF().isPosZero())
12070       return N->getOperand(1);
12071   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12072     if (C->getValueAPF().isPosZero())
12073       return N->getOperand(0);
12074   return SDValue();
12075 }
12076
12077 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12078 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12079   // FAND(0.0, x) -> 0.0
12080   // FAND(x, 0.0) -> 0.0
12081   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12082     if (C->getValueAPF().isPosZero())
12083       return N->getOperand(0);
12084   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12085     if (C->getValueAPF().isPosZero())
12086       return N->getOperand(1);
12087   return SDValue();
12088 }
12089
12090 static SDValue PerformBTCombine(SDNode *N,
12091                                 SelectionDAG &DAG,
12092                                 TargetLowering::DAGCombinerInfo &DCI) {
12093   // BT ignores high bits in the bit index operand.
12094   SDValue Op1 = N->getOperand(1);
12095   if (Op1.hasOneUse()) {
12096     unsigned BitWidth = Op1.getValueSizeInBits();
12097     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12098     APInt KnownZero, KnownOne;
12099     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12100                                           !DCI.isBeforeLegalizeOps());
12101     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12102     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12103         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12104       DCI.CommitTargetLoweringOpt(TLO);
12105   }
12106   return SDValue();
12107 }
12108
12109 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12110   SDValue Op = N->getOperand(0);
12111   if (Op.getOpcode() == ISD::BITCAST)
12112     Op = Op.getOperand(0);
12113   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12114   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12115       VT.getVectorElementType().getSizeInBits() ==
12116       OpVT.getVectorElementType().getSizeInBits()) {
12117     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12118   }
12119   return SDValue();
12120 }
12121
12122 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12123   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12124   //           (and (i32 x86isd::setcc_carry), 1)
12125   // This eliminates the zext. This transformation is necessary because
12126   // ISD::SETCC is always legalized to i8.
12127   DebugLoc dl = N->getDebugLoc();
12128   SDValue N0 = N->getOperand(0);
12129   EVT VT = N->getValueType(0);
12130   if (N0.getOpcode() == ISD::AND &&
12131       N0.hasOneUse() &&
12132       N0.getOperand(0).hasOneUse()) {
12133     SDValue N00 = N0.getOperand(0);
12134     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12135       return SDValue();
12136     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12137     if (!C || C->getZExtValue() != 1)
12138       return SDValue();
12139     return DAG.getNode(ISD::AND, dl, VT,
12140                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12141                                    N00.getOperand(0), N00.getOperand(1)),
12142                        DAG.getConstant(1, VT));
12143   }
12144
12145   return SDValue();
12146 }
12147
12148 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12149 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12150   unsigned X86CC = N->getConstantOperandVal(0);
12151   SDValue EFLAG = N->getOperand(1);
12152   DebugLoc DL = N->getDebugLoc();
12153
12154   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12155   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12156   // cases.
12157   if (X86CC == X86::COND_B)
12158     return DAG.getNode(ISD::AND, DL, MVT::i8,
12159                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12160                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12161                        DAG.getConstant(1, MVT::i8));
12162
12163   return SDValue();
12164 }
12165
12166 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12167 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12168                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12169   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12170   // the result is either zero or one (depending on the input carry bit).
12171   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12172   if (X86::isZeroNode(N->getOperand(0)) &&
12173       X86::isZeroNode(N->getOperand(1)) &&
12174       // We don't have a good way to replace an EFLAGS use, so only do this when
12175       // dead right now.
12176       SDValue(N, 1).use_empty()) {
12177     DebugLoc DL = N->getDebugLoc();
12178     EVT VT = N->getValueType(0);
12179     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12180     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12181                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12182                                            DAG.getConstant(X86::COND_B,MVT::i8),
12183                                            N->getOperand(2)),
12184                                DAG.getConstant(1, VT));
12185     return DCI.CombineTo(N, Res1, CarryOut);
12186   }
12187
12188   return SDValue();
12189 }
12190
12191 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12192 //      (add Y, (setne X, 0)) -> sbb -1, Y
12193 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12194 //      (sub (setne X, 0), Y) -> adc -1, Y
12195 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12196   DebugLoc DL = N->getDebugLoc();
12197
12198   // Look through ZExts.
12199   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12200   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12201     return SDValue();
12202
12203   SDValue SetCC = Ext.getOperand(0);
12204   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12205     return SDValue();
12206
12207   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12208   if (CC != X86::COND_E && CC != X86::COND_NE)
12209     return SDValue();
12210
12211   SDValue Cmp = SetCC.getOperand(1);
12212   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12213       !X86::isZeroNode(Cmp.getOperand(1)) ||
12214       !Cmp.getOperand(0).getValueType().isInteger())
12215     return SDValue();
12216
12217   SDValue CmpOp0 = Cmp.getOperand(0);
12218   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12219                                DAG.getConstant(1, CmpOp0.getValueType()));
12220
12221   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12222   if (CC == X86::COND_NE)
12223     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12224                        DL, OtherVal.getValueType(), OtherVal,
12225                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12226   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12227                      DL, OtherVal.getValueType(), OtherVal,
12228                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12229 }
12230
12231 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12232                                              DAGCombinerInfo &DCI) const {
12233   SelectionDAG &DAG = DCI.DAG;
12234   switch (N->getOpcode()) {
12235   default: break;
12236   case ISD::EXTRACT_VECTOR_ELT:
12237     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12238   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12239   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12240   case ISD::ADD:
12241   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12242   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12243   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12244   case ISD::SHL:
12245   case ISD::SRA:
12246   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12247   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12248   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12249   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12250   case X86ISD::FXOR:
12251   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12252   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12253   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12254   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12255   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12256   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12257   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12258   case X86ISD::SHUFPD:
12259   case X86ISD::PALIGN:
12260   case X86ISD::PUNPCKHBW:
12261   case X86ISD::PUNPCKHWD:
12262   case X86ISD::PUNPCKHDQ:
12263   case X86ISD::PUNPCKHQDQ:
12264   case X86ISD::UNPCKHPS:
12265   case X86ISD::UNPCKHPD:
12266   case X86ISD::PUNPCKLBW:
12267   case X86ISD::PUNPCKLWD:
12268   case X86ISD::PUNPCKLDQ:
12269   case X86ISD::PUNPCKLQDQ:
12270   case X86ISD::UNPCKLPS:
12271   case X86ISD::UNPCKLPD:
12272   case X86ISD::VUNPCKLPS:
12273   case X86ISD::VUNPCKLPD:
12274   case X86ISD::VUNPCKLPSY:
12275   case X86ISD::VUNPCKLPDY:
12276   case X86ISD::MOVHLPS:
12277   case X86ISD::MOVLHPS:
12278   case X86ISD::PSHUFD:
12279   case X86ISD::PSHUFHW:
12280   case X86ISD::PSHUFLW:
12281   case X86ISD::MOVSS:
12282   case X86ISD::MOVSD:
12283   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12284   }
12285
12286   return SDValue();
12287 }
12288
12289 /// isTypeDesirableForOp - Return true if the target has native support for
12290 /// the specified value type and it is 'desirable' to use the type for the
12291 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12292 /// instruction encodings are longer and some i16 instructions are slow.
12293 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12294   if (!isTypeLegal(VT))
12295     return false;
12296   if (VT != MVT::i16)
12297     return true;
12298
12299   switch (Opc) {
12300   default:
12301     return true;
12302   case ISD::LOAD:
12303   case ISD::SIGN_EXTEND:
12304   case ISD::ZERO_EXTEND:
12305   case ISD::ANY_EXTEND:
12306   case ISD::SHL:
12307   case ISD::SRL:
12308   case ISD::SUB:
12309   case ISD::ADD:
12310   case ISD::MUL:
12311   case ISD::AND:
12312   case ISD::OR:
12313   case ISD::XOR:
12314     return false;
12315   }
12316 }
12317
12318 /// IsDesirableToPromoteOp - This method query the target whether it is
12319 /// beneficial for dag combiner to promote the specified node. If true, it
12320 /// should return the desired promotion type by reference.
12321 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12322   EVT VT = Op.getValueType();
12323   if (VT != MVT::i16)
12324     return false;
12325
12326   bool Promote = false;
12327   bool Commute = false;
12328   switch (Op.getOpcode()) {
12329   default: break;
12330   case ISD::LOAD: {
12331     LoadSDNode *LD = cast<LoadSDNode>(Op);
12332     // If the non-extending load has a single use and it's not live out, then it
12333     // might be folded.
12334     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12335                                                      Op.hasOneUse()*/) {
12336       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12337              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12338         // The only case where we'd want to promote LOAD (rather then it being
12339         // promoted as an operand is when it's only use is liveout.
12340         if (UI->getOpcode() != ISD::CopyToReg)
12341           return false;
12342       }
12343     }
12344     Promote = true;
12345     break;
12346   }
12347   case ISD::SIGN_EXTEND:
12348   case ISD::ZERO_EXTEND:
12349   case ISD::ANY_EXTEND:
12350     Promote = true;
12351     break;
12352   case ISD::SHL:
12353   case ISD::SRL: {
12354     SDValue N0 = Op.getOperand(0);
12355     // Look out for (store (shl (load), x)).
12356     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12357       return false;
12358     Promote = true;
12359     break;
12360   }
12361   case ISD::ADD:
12362   case ISD::MUL:
12363   case ISD::AND:
12364   case ISD::OR:
12365   case ISD::XOR:
12366     Commute = true;
12367     // fallthrough
12368   case ISD::SUB: {
12369     SDValue N0 = Op.getOperand(0);
12370     SDValue N1 = Op.getOperand(1);
12371     if (!Commute && MayFoldLoad(N1))
12372       return false;
12373     // Avoid disabling potential load folding opportunities.
12374     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12375       return false;
12376     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12377       return false;
12378     Promote = true;
12379   }
12380   }
12381
12382   PVT = MVT::i32;
12383   return Promote;
12384 }
12385
12386 //===----------------------------------------------------------------------===//
12387 //                           X86 Inline Assembly Support
12388 //===----------------------------------------------------------------------===//
12389
12390 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12391   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12392
12393   std::string AsmStr = IA->getAsmString();
12394
12395   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12396   SmallVector<StringRef, 4> AsmPieces;
12397   SplitString(AsmStr, AsmPieces, ";\n");
12398
12399   switch (AsmPieces.size()) {
12400   default: return false;
12401   case 1:
12402     AsmStr = AsmPieces[0];
12403     AsmPieces.clear();
12404     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12405
12406     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12407     // we will turn this bswap into something that will be lowered to logical ops
12408     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12409     // so don't worry about this.
12410     // bswap $0
12411     if (AsmPieces.size() == 2 &&
12412         (AsmPieces[0] == "bswap" ||
12413          AsmPieces[0] == "bswapq" ||
12414          AsmPieces[0] == "bswapl") &&
12415         (AsmPieces[1] == "$0" ||
12416          AsmPieces[1] == "${0:q}")) {
12417       // No need to check constraints, nothing other than the equivalent of
12418       // "=r,0" would be valid here.
12419       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12420       if (!Ty || Ty->getBitWidth() % 16 != 0)
12421         return false;
12422       return IntrinsicLowering::LowerToByteSwap(CI);
12423     }
12424     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12425     if (CI->getType()->isIntegerTy(16) &&
12426         AsmPieces.size() == 3 &&
12427         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12428         AsmPieces[1] == "$$8," &&
12429         AsmPieces[2] == "${0:w}" &&
12430         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12431       AsmPieces.clear();
12432       const std::string &ConstraintsStr = IA->getConstraintString();
12433       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12434       std::sort(AsmPieces.begin(), AsmPieces.end());
12435       if (AsmPieces.size() == 4 &&
12436           AsmPieces[0] == "~{cc}" &&
12437           AsmPieces[1] == "~{dirflag}" &&
12438           AsmPieces[2] == "~{flags}" &&
12439           AsmPieces[3] == "~{fpsr}") {
12440         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12441         if (!Ty || Ty->getBitWidth() % 16 != 0)
12442           return false;
12443         return IntrinsicLowering::LowerToByteSwap(CI);
12444       }
12445     }
12446     break;
12447   case 3:
12448     if (CI->getType()->isIntegerTy(32) &&
12449         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12450       SmallVector<StringRef, 4> Words;
12451       SplitString(AsmPieces[0], Words, " \t,");
12452       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12453           Words[2] == "${0:w}") {
12454         Words.clear();
12455         SplitString(AsmPieces[1], Words, " \t,");
12456         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12457             Words[2] == "$0") {
12458           Words.clear();
12459           SplitString(AsmPieces[2], Words, " \t,");
12460           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12461               Words[2] == "${0:w}") {
12462             AsmPieces.clear();
12463             const std::string &ConstraintsStr = IA->getConstraintString();
12464             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12465             std::sort(AsmPieces.begin(), AsmPieces.end());
12466             if (AsmPieces.size() == 4 &&
12467                 AsmPieces[0] == "~{cc}" &&
12468                 AsmPieces[1] == "~{dirflag}" &&
12469                 AsmPieces[2] == "~{flags}" &&
12470                 AsmPieces[3] == "~{fpsr}") {
12471               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12472               if (!Ty || Ty->getBitWidth() % 16 != 0)
12473                 return false;
12474               return IntrinsicLowering::LowerToByteSwap(CI);
12475             }
12476           }
12477         }
12478       }
12479     }
12480
12481     if (CI->getType()->isIntegerTy(64)) {
12482       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12483       if (Constraints.size() >= 2 &&
12484           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12485           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12486         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12487         SmallVector<StringRef, 4> Words;
12488         SplitString(AsmPieces[0], Words, " \t");
12489         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12490           Words.clear();
12491           SplitString(AsmPieces[1], Words, " \t");
12492           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12493             Words.clear();
12494             SplitString(AsmPieces[2], Words, " \t,");
12495             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12496                 Words[2] == "%edx") {
12497               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12498               if (!Ty || Ty->getBitWidth() % 16 != 0)
12499                 return false;
12500               return IntrinsicLowering::LowerToByteSwap(CI);
12501             }
12502           }
12503         }
12504       }
12505     }
12506     break;
12507   }
12508   return false;
12509 }
12510
12511
12512
12513 /// getConstraintType - Given a constraint letter, return the type of
12514 /// constraint it is for this target.
12515 X86TargetLowering::ConstraintType
12516 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12517   if (Constraint.size() == 1) {
12518     switch (Constraint[0]) {
12519     case 'R':
12520     case 'q':
12521     case 'Q':
12522     case 'f':
12523     case 't':
12524     case 'u':
12525     case 'y':
12526     case 'x':
12527     case 'Y':
12528       return C_RegisterClass;
12529     case 'a':
12530     case 'b':
12531     case 'c':
12532     case 'd':
12533     case 'S':
12534     case 'D':
12535     case 'A':
12536       return C_Register;
12537     case 'I':
12538     case 'J':
12539     case 'K':
12540     case 'L':
12541     case 'M':
12542     case 'N':
12543     case 'G':
12544     case 'C':
12545     case 'e':
12546     case 'Z':
12547       return C_Other;
12548     default:
12549       break;
12550     }
12551   }
12552   return TargetLowering::getConstraintType(Constraint);
12553 }
12554
12555 /// Examine constraint type and operand type and determine a weight value.
12556 /// This object must already have been set up with the operand type
12557 /// and the current alternative constraint selected.
12558 TargetLowering::ConstraintWeight
12559   X86TargetLowering::getSingleConstraintMatchWeight(
12560     AsmOperandInfo &info, const char *constraint) const {
12561   ConstraintWeight weight = CW_Invalid;
12562   Value *CallOperandVal = info.CallOperandVal;
12563     // If we don't have a value, we can't do a match,
12564     // but allow it at the lowest weight.
12565   if (CallOperandVal == NULL)
12566     return CW_Default;
12567   const Type *type = CallOperandVal->getType();
12568   // Look at the constraint type.
12569   switch (*constraint) {
12570   default:
12571     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12572   case 'R':
12573   case 'q':
12574   case 'Q':
12575   case 'a':
12576   case 'b':
12577   case 'c':
12578   case 'd':
12579   case 'S':
12580   case 'D':
12581   case 'A':
12582     if (CallOperandVal->getType()->isIntegerTy())
12583       weight = CW_SpecificReg;
12584     break;
12585   case 'f':
12586   case 't':
12587   case 'u':
12588       if (type->isFloatingPointTy())
12589         weight = CW_SpecificReg;
12590       break;
12591   case 'y':
12592       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12593         weight = CW_SpecificReg;
12594       break;
12595   case 'x':
12596   case 'Y':
12597     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12598       weight = CW_Register;
12599     break;
12600   case 'I':
12601     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12602       if (C->getZExtValue() <= 31)
12603         weight = CW_Constant;
12604     }
12605     break;
12606   case 'J':
12607     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12608       if (C->getZExtValue() <= 63)
12609         weight = CW_Constant;
12610     }
12611     break;
12612   case 'K':
12613     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12614       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12615         weight = CW_Constant;
12616     }
12617     break;
12618   case 'L':
12619     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12620       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12621         weight = CW_Constant;
12622     }
12623     break;
12624   case 'M':
12625     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12626       if (C->getZExtValue() <= 3)
12627         weight = CW_Constant;
12628     }
12629     break;
12630   case 'N':
12631     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12632       if (C->getZExtValue() <= 0xff)
12633         weight = CW_Constant;
12634     }
12635     break;
12636   case 'G':
12637   case 'C':
12638     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12639       weight = CW_Constant;
12640     }
12641     break;
12642   case 'e':
12643     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12644       if ((C->getSExtValue() >= -0x80000000LL) &&
12645           (C->getSExtValue() <= 0x7fffffffLL))
12646         weight = CW_Constant;
12647     }
12648     break;
12649   case 'Z':
12650     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12651       if (C->getZExtValue() <= 0xffffffff)
12652         weight = CW_Constant;
12653     }
12654     break;
12655   }
12656   return weight;
12657 }
12658
12659 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12660 /// with another that has more specific requirements based on the type of the
12661 /// corresponding operand.
12662 const char *X86TargetLowering::
12663 LowerXConstraint(EVT ConstraintVT) const {
12664   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12665   // 'f' like normal targets.
12666   if (ConstraintVT.isFloatingPoint()) {
12667     if (Subtarget->hasXMMInt())
12668       return "Y";
12669     if (Subtarget->hasXMM())
12670       return "x";
12671   }
12672
12673   return TargetLowering::LowerXConstraint(ConstraintVT);
12674 }
12675
12676 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12677 /// vector.  If it is invalid, don't add anything to Ops.
12678 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12679                                                      char Constraint,
12680                                                      std::vector<SDValue>&Ops,
12681                                                      SelectionDAG &DAG) const {
12682   SDValue Result(0, 0);
12683
12684   switch (Constraint) {
12685   default: break;
12686   case 'I':
12687     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12688       if (C->getZExtValue() <= 31) {
12689         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12690         break;
12691       }
12692     }
12693     return;
12694   case 'J':
12695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12696       if (C->getZExtValue() <= 63) {
12697         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12698         break;
12699       }
12700     }
12701     return;
12702   case 'K':
12703     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12704       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12705         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12706         break;
12707       }
12708     }
12709     return;
12710   case 'N':
12711     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12712       if (C->getZExtValue() <= 255) {
12713         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12714         break;
12715       }
12716     }
12717     return;
12718   case 'e': {
12719     // 32-bit signed value
12720     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12721       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12722                                            C->getSExtValue())) {
12723         // Widen to 64 bits here to get it sign extended.
12724         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12725         break;
12726       }
12727     // FIXME gcc accepts some relocatable values here too, but only in certain
12728     // memory models; it's complicated.
12729     }
12730     return;
12731   }
12732   case 'Z': {
12733     // 32-bit unsigned value
12734     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12735       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12736                                            C->getZExtValue())) {
12737         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12738         break;
12739       }
12740     }
12741     // FIXME gcc accepts some relocatable values here too, but only in certain
12742     // memory models; it's complicated.
12743     return;
12744   }
12745   case 'i': {
12746     // Literal immediates are always ok.
12747     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12748       // Widen to 64 bits here to get it sign extended.
12749       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12750       break;
12751     }
12752
12753     // In any sort of PIC mode addresses need to be computed at runtime by
12754     // adding in a register or some sort of table lookup.  These can't
12755     // be used as immediates.
12756     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12757       return;
12758
12759     // If we are in non-pic codegen mode, we allow the address of a global (with
12760     // an optional displacement) to be used with 'i'.
12761     GlobalAddressSDNode *GA = 0;
12762     int64_t Offset = 0;
12763
12764     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12765     while (1) {
12766       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12767         Offset += GA->getOffset();
12768         break;
12769       } else if (Op.getOpcode() == ISD::ADD) {
12770         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12771           Offset += C->getZExtValue();
12772           Op = Op.getOperand(0);
12773           continue;
12774         }
12775       } else if (Op.getOpcode() == ISD::SUB) {
12776         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12777           Offset += -C->getZExtValue();
12778           Op = Op.getOperand(0);
12779           continue;
12780         }
12781       }
12782
12783       // Otherwise, this isn't something we can handle, reject it.
12784       return;
12785     }
12786
12787     const GlobalValue *GV = GA->getGlobal();
12788     // If we require an extra load to get this address, as in PIC mode, we
12789     // can't accept it.
12790     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12791                                                         getTargetMachine())))
12792       return;
12793
12794     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12795                                         GA->getValueType(0), Offset);
12796     break;
12797   }
12798   }
12799
12800   if (Result.getNode()) {
12801     Ops.push_back(Result);
12802     return;
12803   }
12804   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12805 }
12806
12807 std::vector<unsigned> X86TargetLowering::
12808 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12809                                   EVT VT) const {
12810   if (Constraint.size() == 1) {
12811     // FIXME: not handling fp-stack yet!
12812     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12813     default: break;  // Unknown constraint letter
12814     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12815       if (Subtarget->is64Bit()) {
12816         if (VT == MVT::i32)
12817           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12818                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12819                                        X86::R10D,X86::R11D,X86::R12D,
12820                                        X86::R13D,X86::R14D,X86::R15D,
12821                                        X86::EBP, X86::ESP, 0);
12822         else if (VT == MVT::i16)
12823           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12824                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12825                                        X86::R10W,X86::R11W,X86::R12W,
12826                                        X86::R13W,X86::R14W,X86::R15W,
12827                                        X86::BP,  X86::SP, 0);
12828         else if (VT == MVT::i8)
12829           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12830                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12831                                        X86::R10B,X86::R11B,X86::R12B,
12832                                        X86::R13B,X86::R14B,X86::R15B,
12833                                        X86::BPL, X86::SPL, 0);
12834
12835         else if (VT == MVT::i64)
12836           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12837                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12838                                        X86::R10, X86::R11, X86::R12,
12839                                        X86::R13, X86::R14, X86::R15,
12840                                        X86::RBP, X86::RSP, 0);
12841
12842         break;
12843       }
12844       // 32-bit fallthrough
12845     case 'Q':   // Q_REGS
12846       if (VT == MVT::i32)
12847         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12848       else if (VT == MVT::i16)
12849         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12850       else if (VT == MVT::i8)
12851         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12852       else if (VT == MVT::i64)
12853         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12854       break;
12855     }
12856   }
12857
12858   return std::vector<unsigned>();
12859 }
12860
12861 std::pair<unsigned, const TargetRegisterClass*>
12862 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12863                                                 EVT VT) const {
12864   // First, see if this is a constraint that directly corresponds to an LLVM
12865   // register class.
12866   if (Constraint.size() == 1) {
12867     // GCC Constraint Letters
12868     switch (Constraint[0]) {
12869     default: break;
12870     case 'r':   // GENERAL_REGS
12871     case 'l':   // INDEX_REGS
12872       if (VT == MVT::i8)
12873         return std::make_pair(0U, X86::GR8RegisterClass);
12874       if (VT == MVT::i16)
12875         return std::make_pair(0U, X86::GR16RegisterClass);
12876       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12877         return std::make_pair(0U, X86::GR32RegisterClass);
12878       return std::make_pair(0U, X86::GR64RegisterClass);
12879     case 'R':   // LEGACY_REGS
12880       if (VT == MVT::i8)
12881         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12882       if (VT == MVT::i16)
12883         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12884       if (VT == MVT::i32 || !Subtarget->is64Bit())
12885         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12886       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12887     case 'f':  // FP Stack registers.
12888       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12889       // value to the correct fpstack register class.
12890       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12891         return std::make_pair(0U, X86::RFP32RegisterClass);
12892       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12893         return std::make_pair(0U, X86::RFP64RegisterClass);
12894       return std::make_pair(0U, X86::RFP80RegisterClass);
12895     case 'y':   // MMX_REGS if MMX allowed.
12896       if (!Subtarget->hasMMX()) break;
12897       return std::make_pair(0U, X86::VR64RegisterClass);
12898     case 'Y':   // SSE_REGS if SSE2 allowed
12899       if (!Subtarget->hasXMMInt()) break;
12900       // FALL THROUGH.
12901     case 'x':   // SSE_REGS if SSE1 allowed
12902       if (!Subtarget->hasXMM()) break;
12903
12904       switch (VT.getSimpleVT().SimpleTy) {
12905       default: break;
12906       // Scalar SSE types.
12907       case MVT::f32:
12908       case MVT::i32:
12909         return std::make_pair(0U, X86::FR32RegisterClass);
12910       case MVT::f64:
12911       case MVT::i64:
12912         return std::make_pair(0U, X86::FR64RegisterClass);
12913       // Vector types.
12914       case MVT::v16i8:
12915       case MVT::v8i16:
12916       case MVT::v4i32:
12917       case MVT::v2i64:
12918       case MVT::v4f32:
12919       case MVT::v2f64:
12920         return std::make_pair(0U, X86::VR128RegisterClass);
12921       }
12922       break;
12923     }
12924   }
12925
12926   // Use the default implementation in TargetLowering to convert the register
12927   // constraint into a member of a register class.
12928   std::pair<unsigned, const TargetRegisterClass*> Res;
12929   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12930
12931   // Not found as a standard register?
12932   if (Res.second == 0) {
12933     // Map st(0) -> st(7) -> ST0
12934     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12935         tolower(Constraint[1]) == 's' &&
12936         tolower(Constraint[2]) == 't' &&
12937         Constraint[3] == '(' &&
12938         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12939         Constraint[5] == ')' &&
12940         Constraint[6] == '}') {
12941
12942       Res.first = X86::ST0+Constraint[4]-'0';
12943       Res.second = X86::RFP80RegisterClass;
12944       return Res;
12945     }
12946
12947     // GCC allows "st(0)" to be called just plain "st".
12948     if (StringRef("{st}").equals_lower(Constraint)) {
12949       Res.first = X86::ST0;
12950       Res.second = X86::RFP80RegisterClass;
12951       return Res;
12952     }
12953
12954     // flags -> EFLAGS
12955     if (StringRef("{flags}").equals_lower(Constraint)) {
12956       Res.first = X86::EFLAGS;
12957       Res.second = X86::CCRRegisterClass;
12958       return Res;
12959     }
12960
12961     // 'A' means EAX + EDX.
12962     if (Constraint == "A") {
12963       Res.first = X86::EAX;
12964       Res.second = X86::GR32_ADRegisterClass;
12965       return Res;
12966     }
12967     return Res;
12968   }
12969
12970   // Otherwise, check to see if this is a register class of the wrong value
12971   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12972   // turn into {ax},{dx}.
12973   if (Res.second->hasType(VT))
12974     return Res;   // Correct type already, nothing to do.
12975
12976   // All of the single-register GCC register classes map their values onto
12977   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12978   // really want an 8-bit or 32-bit register, map to the appropriate register
12979   // class and return the appropriate register.
12980   if (Res.second == X86::GR16RegisterClass) {
12981     if (VT == MVT::i8) {
12982       unsigned DestReg = 0;
12983       switch (Res.first) {
12984       default: break;
12985       case X86::AX: DestReg = X86::AL; break;
12986       case X86::DX: DestReg = X86::DL; break;
12987       case X86::CX: DestReg = X86::CL; break;
12988       case X86::BX: DestReg = X86::BL; break;
12989       }
12990       if (DestReg) {
12991         Res.first = DestReg;
12992         Res.second = X86::GR8RegisterClass;
12993       }
12994     } else if (VT == MVT::i32) {
12995       unsigned DestReg = 0;
12996       switch (Res.first) {
12997       default: break;
12998       case X86::AX: DestReg = X86::EAX; break;
12999       case X86::DX: DestReg = X86::EDX; break;
13000       case X86::CX: DestReg = X86::ECX; break;
13001       case X86::BX: DestReg = X86::EBX; break;
13002       case X86::SI: DestReg = X86::ESI; break;
13003       case X86::DI: DestReg = X86::EDI; break;
13004       case X86::BP: DestReg = X86::EBP; break;
13005       case X86::SP: DestReg = X86::ESP; break;
13006       }
13007       if (DestReg) {
13008         Res.first = DestReg;
13009         Res.second = X86::GR32RegisterClass;
13010       }
13011     } else if (VT == MVT::i64) {
13012       unsigned DestReg = 0;
13013       switch (Res.first) {
13014       default: break;
13015       case X86::AX: DestReg = X86::RAX; break;
13016       case X86::DX: DestReg = X86::RDX; break;
13017       case X86::CX: DestReg = X86::RCX; break;
13018       case X86::BX: DestReg = X86::RBX; break;
13019       case X86::SI: DestReg = X86::RSI; break;
13020       case X86::DI: DestReg = X86::RDI; break;
13021       case X86::BP: DestReg = X86::RBP; break;
13022       case X86::SP: DestReg = X86::RSP; break;
13023       }
13024       if (DestReg) {
13025         Res.first = DestReg;
13026         Res.second = X86::GR64RegisterClass;
13027       }
13028     }
13029   } else if (Res.second == X86::FR32RegisterClass ||
13030              Res.second == X86::FR64RegisterClass ||
13031              Res.second == X86::VR128RegisterClass) {
13032     // Handle references to XMM physical registers that got mapped into the
13033     // wrong class.  This can happen with constraints like {xmm0} where the
13034     // target independent register mapper will just pick the first match it can
13035     // find, ignoring the required type.
13036     if (VT == MVT::f32)
13037       Res.second = X86::FR32RegisterClass;
13038     else if (VT == MVT::f64)
13039       Res.second = X86::FR64RegisterClass;
13040     else if (X86::VR128RegisterClass->hasType(VT))
13041       Res.second = X86::VR128RegisterClass;
13042   }
13043
13044   return Res;
13045 }