[AVX] Add some utilities to insert and extract 128-bit subvectors.
[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 "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.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/CommandLine.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 static SDValue Extract128BitVector(SDValue Vec,
69                                    SDValue Idx,
70                                    SelectionDAG &DAG,
71                                    DebugLoc dl);
72
73 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.
78 static SDValue Extract128BitVector(SDValue Vec,
79                                    SDValue Idx,
80                                    SelectionDAG &DAG,
81                                    DebugLoc dl) {
82   EVT VT = Vec.getValueType();
83   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
84
85   EVT ElVT = VT.getVectorElementType();
86
87   int Factor = VT.getSizeInBits() / 128;
88
89   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
90                                   ElVT,
91                                   VT.getVectorNumElements() / Factor);
92
93   // Extract from UNDEF is UNDEF.
94   if (Vec.getOpcode() == ISD::UNDEF)
95     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
96
97   if (isa<ConstantSDNode>(Idx)) {
98     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
99
100     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
101     // we can match to VEXTRACTF128.
102     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
103
104     // This is the index of the first element of the 128-bit chunk
105     // we want.
106     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107                                  * ElemsPerChunk);
108
109     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
110
111     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
112                                  VecIdx);
113
114     return Result;
115   }
116
117   return SDValue();
118 }
119
120 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
121 /// sets things up to match to an AVX VINSERTF128 instruction or a
122 /// simple superregister reference.
123 static SDValue Insert128BitVector(SDValue Result,
124                                   SDValue Vec,
125                                   SDValue Idx,
126                                   SelectionDAG &DAG,
127                                   DebugLoc dl) {
128   if (isa<ConstantSDNode>(Idx)) {
129     EVT VT = Vec.getValueType();
130     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
131
132     EVT ElVT = VT.getVectorElementType();
133
134     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
135
136     EVT ResultVT = Result.getValueType();
137
138     // Insert the relevant 128 bits.
139     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
140
141     // This is the index of the first element of the 128-bit chunk
142     // we want.
143     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
144                                  * ElemsPerChunk);
145
146     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
147
148     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
149                          VecIdx);
150     return Result;
151   }
152
153   return SDValue();
154 }
155
156 /// Given two vectors, concat them.
157 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
158   DebugLoc dl = Lower.getDebugLoc();
159
160   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
161
162   EVT VT = EVT::getVectorVT(*DAG.getContext(),
163                             Lower.getValueType().getVectorElementType(),
164                             Lower.getValueType().getVectorNumElements() * 2);
165
166   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
167   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
168
169   // Insert the upper subvector.
170   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
171                                    DAG.getConstant(
172                                      // This is half the length of the result
173                                      // vector.  Start inserting the upper 128
174                                      // bits here.
175                                      Lower.getValueType().
176                                        getVectorNumElements(),
177                                      MVT::i32),
178                                    DAG, dl);
179
180   // Insert the lower subvector.
181   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
182   return Vec;
183 }
184
185 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
186   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
187   bool is64Bit = Subtarget->is64Bit();
188  
189   if (Subtarget->isTargetEnvMacho()) {
190     if (is64Bit)
191       return new X8664_MachoTargetObjectFile();
192     return new TargetLoweringObjectFileMachO();
193   }
194
195   if (Subtarget->isTargetELF()) {
196     if (is64Bit)
197       return new X8664_ELFTargetObjectFile(TM);
198     return new X8632_ELFTargetObjectFile(TM);
199   }
200   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
201     return new TargetLoweringObjectFileCOFF();
202   llvm_unreachable("unknown subtarget type");
203 }
204
205 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
206   : TargetLowering(TM, createTLOF(TM)) {
207   Subtarget = &TM.getSubtarget<X86Subtarget>();
208   X86ScalarSSEf64 = Subtarget->hasXMMInt();
209   X86ScalarSSEf32 = Subtarget->hasXMM();
210   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
211
212   RegInfo = TM.getRegisterInfo();
213   TD = getTargetData();
214
215   // Set up the TargetLowering object.
216   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
217
218   // X86 is weird, it always uses i8 for shift amounts and setcc results.
219   setShiftAmountType(MVT::i8);
220   setBooleanContents(ZeroOrOneBooleanContent);
221   setSchedulingPreference(Sched::RegPressure);
222   setStackPointerRegisterToSaveRestore(X86StackPtr);
223
224   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
225     // Setup Windows compiler runtime calls.
226     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
227     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
228     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
229     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
230     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
231     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
232     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
233     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
234   }
235
236   if (Subtarget->isTargetDarwin()) {
237     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
238     setUseUnderscoreSetJmp(false);
239     setUseUnderscoreLongJmp(false);
240   } else if (Subtarget->isTargetMingw()) {
241     // MS runtime is weird: it exports _setjmp, but longjmp!
242     setUseUnderscoreSetJmp(true);
243     setUseUnderscoreLongJmp(false);
244   } else {
245     setUseUnderscoreSetJmp(true);
246     setUseUnderscoreLongJmp(true);
247   }
248
249   // Set up the register classes.
250   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
251   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
252   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
253   if (Subtarget->is64Bit())
254     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
255
256   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
257
258   // We don't accept any truncstore of integer registers.
259   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
260   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
261   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
262   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
263   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
264   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
265
266   // SETOEQ and SETUNE require checking two conditions.
267   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
268   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
269   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
270   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
271   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
272   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
273
274   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
275   // operation.
276   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
277   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
278   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
279
280   if (Subtarget->is64Bit()) {
281     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
282     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
283   } else if (!UseSoftFloat) {
284     // We have an algorithm for SSE2->double, and we turn this into a
285     // 64-bit FILD followed by conditional FADD for other targets.
286     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
287     // We have an algorithm for SSE2, and we turn this into a 64-bit
288     // FILD for other targets.
289     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
290   }
291
292   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
293   // this operation.
294   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
295   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
296
297   if (!UseSoftFloat) {
298     // SSE has no i16 to fp conversion, only i32
299     if (X86ScalarSSEf32) {
300       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
301       // f32 and f64 cases are Legal, f80 case is not
302       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
303     } else {
304       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
305       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
306     }
307   } else {
308     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
309     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
310   }
311
312   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
313   // are Legal, f80 is custom lowered.
314   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
315   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
316
317   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
318   // this operation.
319   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
320   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
321
322   if (X86ScalarSSEf32) {
323     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
324     // f32 and f64 cases are Legal, f80 case is not
325     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
326   } else {
327     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
328     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
329   }
330
331   // Handle FP_TO_UINT by promoting the destination to a larger signed
332   // conversion.
333   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
334   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
335   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
336
337   if (Subtarget->is64Bit()) {
338     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
339     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
340   } else if (!UseSoftFloat) {
341     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
342       // Expand FP_TO_UINT into a select.
343       // FIXME: We would like to use a Custom expander here eventually to do
344       // the optimal thing for SSE vs. the default expansion in the legalizer.
345       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
346     else
347       // With SSE3 we can use fisttpll to convert to a signed i64; without
348       // SSE, we're stuck with a fistpll.
349       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
350   }
351
352   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
353   if (!X86ScalarSSEf64) {
354     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
355     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
358       // Without SSE, i64->f64 goes through memory.
359       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
360     }
361   }
362
363   // Scalar integer divide and remainder are lowered to use operations that
364   // produce two results, to match the available instructions. This exposes
365   // the two-result form to trivial CSE, which is able to combine x/y and x%y
366   // into a single instruction.
367   //
368   // Scalar integer multiply-high is also lowered to use two-result
369   // operations, to match the available instructions. However, plain multiply
370   // (low) operations are left as Legal, as there are single-result
371   // instructions for this in x86. Using the two-result multiply instructions
372   // when both high and low results are needed must be arranged by dagcombine.
373   for (unsigned i = 0, e = 4; i != e; ++i) {
374     MVT VT = IntVTs[i];
375     setOperationAction(ISD::MULHS, VT, Expand);
376     setOperationAction(ISD::MULHU, VT, Expand);
377     setOperationAction(ISD::SDIV, VT, Expand);
378     setOperationAction(ISD::UDIV, VT, Expand);
379     setOperationAction(ISD::SREM, VT, Expand);
380     setOperationAction(ISD::UREM, VT, Expand);
381
382     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
383     setOperationAction(ISD::ADDC, VT, Custom);
384     setOperationAction(ISD::ADDE, VT, Custom);
385     setOperationAction(ISD::SUBC, VT, Custom);
386     setOperationAction(ISD::SUBE, VT, Custom);
387   }
388
389   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
390   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
391   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
392   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
393   if (Subtarget->is64Bit())
394     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
395   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
396   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
397   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
398   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
399   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
400   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
401   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
402   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
403
404   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
405   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
406   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
407   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
408   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
409   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
410   if (Subtarget->is64Bit()) {
411     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
413   }
414
415   if (Subtarget->hasPOPCNT()) {
416     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
417   } else {
418     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
419     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
420     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
421     if (Subtarget->is64Bit())
422       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
423   }
424
425   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
426   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
427
428   // These should be promoted to a larger select which is supported.
429   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
430   // X86 wants to expand cmov itself.
431   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
432   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
433   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
434   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
435   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
436   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
437   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
438   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
439   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
440   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
441   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
443   if (Subtarget->is64Bit()) {
444     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
445     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
446   }
447   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
448
449   // Darwin ABI issue.
450   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
451   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
452   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
453   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
454   if (Subtarget->is64Bit())
455     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
456   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
457   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
458   if (Subtarget->is64Bit()) {
459     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
460     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
461     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
462     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
463     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
464   }
465   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
466   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
467   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
468   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
469   if (Subtarget->is64Bit()) {
470     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
471     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
472     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
473   }
474
475   if (Subtarget->hasXMM())
476     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
477
478   // We may not have a libcall for MEMBARRIER so we should lower this.
479   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
480
481   // On X86 and X86-64, atomic operations are lowered to locked instructions.
482   // Locked instructions, in turn, have implicit fence semantics (all memory
483   // operations are flushed before issuing the locked instruction, and they
484   // are not buffered), so we can fold away the common pattern of
485   // fence-atomic-fence.
486   setShouldFoldAtomicFences(true);
487
488   // Expand certain atomics
489   for (unsigned i = 0, e = 4; i != e; ++i) {
490     MVT VT = IntVTs[i];
491     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
492     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
493   }
494
495   if (!Subtarget->is64Bit()) {
496     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
497     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
498     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
499     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
503   }
504
505   // FIXME - use subtarget debug flags
506   if (!Subtarget->isTargetDarwin() &&
507       !Subtarget->isTargetELF() &&
508       !Subtarget->isTargetCygMing()) {
509     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
510   }
511
512   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
513   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
514   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
515   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
516   if (Subtarget->is64Bit()) {
517     setExceptionPointerRegister(X86::RAX);
518     setExceptionSelectorRegister(X86::RDX);
519   } else {
520     setExceptionPointerRegister(X86::EAX);
521     setExceptionSelectorRegister(X86::EDX);
522   }
523   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
524   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
525
526   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
527
528   setOperationAction(ISD::TRAP, MVT::Other, Legal);
529
530   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
531   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
532   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
533   if (Subtarget->is64Bit()) {
534     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
535     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
536   } else {
537     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
538     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
539   }
540
541   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
542   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
543   if (Subtarget->is64Bit())
544     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
545   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
546     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
547   else
548     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
549
550   if (!UseSoftFloat && X86ScalarSSEf64) {
551     // f32 and f64 use SSE.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
554     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
555
556     // Use ANDPD to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f64, Custom);
558     setOperationAction(ISD::FABS , MVT::f32, Custom);
559
560     // Use XORP to simulate FNEG.
561     setOperationAction(ISD::FNEG , MVT::f64, Custom);
562     setOperationAction(ISD::FNEG , MVT::f32, Custom);
563
564     // Use ANDPD and ORPD to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN , MVT::f64, Expand);
570     setOperationAction(ISD::FCOS , MVT::f64, Expand);
571     setOperationAction(ISD::FSIN , MVT::f32, Expand);
572     setOperationAction(ISD::FCOS , MVT::f32, Expand);
573
574     // Expand FP immediates into loads from the stack, except for the special
575     // cases we handle.
576     addLegalFPImmediate(APFloat(+0.0)); // xorpd
577     addLegalFPImmediate(APFloat(+0.0f)); // xorps
578   } else if (!UseSoftFloat && X86ScalarSSEf32) {
579     // Use SSE for f32, x87 for f64.
580     // Set up the FP register classes.
581     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
582     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
583
584     // Use ANDPS to simulate FABS.
585     setOperationAction(ISD::FABS , MVT::f32, Custom);
586
587     // Use XORP to simulate FNEG.
588     setOperationAction(ISD::FNEG , MVT::f32, Custom);
589
590     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
591
592     // Use ANDPS and ORPS to simulate FCOPYSIGN.
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
595
596     // We don't support sin/cos/fmod
597     setOperationAction(ISD::FSIN , MVT::f32, Expand);
598     setOperationAction(ISD::FCOS , MVT::f32, Expand);
599
600     // Special cases we handle for FP constants.
601     addLegalFPImmediate(APFloat(+0.0f)); // xorps
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606
607     if (!UnsafeFPMath) {
608       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
609       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
610     }
611   } else if (!UseSoftFloat) {
612     // f32 and f64 in x87.
613     // Set up the FP register classes.
614     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
615     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
616
617     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
618     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
619     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
621
622     if (!UnsafeFPMath) {
623       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
624       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
625     }
626     addLegalFPImmediate(APFloat(+0.0)); // FLD0
627     addLegalFPImmediate(APFloat(+1.0)); // FLD1
628     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
629     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
630     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
631     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
632     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
633     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
634   }
635
636   // Long double always uses X87.
637   if (!UseSoftFloat) {
638     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
639     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
640     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
641     {
642       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
643       addLegalFPImmediate(TmpFlt);  // FLD0
644       TmpFlt.changeSign();
645       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
646
647       bool ignored;
648       APFloat TmpFlt2(+1.0);
649       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
650                       &ignored);
651       addLegalFPImmediate(TmpFlt2);  // FLD1
652       TmpFlt2.changeSign();
653       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
654     }
655
656     if (!UnsafeFPMath) {
657       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
658       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
659     }
660   }
661
662   // Always use a library call for pow.
663   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
664   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
665   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
666
667   setOperationAction(ISD::FLOG, MVT::f80, Expand);
668   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
669   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
670   setOperationAction(ISD::FEXP, MVT::f80, Expand);
671   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
672
673   // First set operation action for all vector types to either promote
674   // (for widening) or expand (for scalarization). Then we will selectively
675   // turn on ones that can be effectively codegen'd.
676   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
677        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
678     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
679     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
680     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
681     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
693     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
695     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
696     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
728     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
732     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
733          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
734       setTruncStoreAction((MVT::SimpleValueType)VT,
735                           (MVT::SimpleValueType)InnerVT, Expand);
736     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
737     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
738     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
739   }
740
741   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
742   // with -msoft-float, disable use of MMX as well.
743   if (!UseSoftFloat && Subtarget->hasMMX()) {
744     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
745     // No operations on x86mmx supported, everything uses intrinsics.
746   }
747
748   // MMX-sized vectors (other than x86mmx) are expected to be expanded
749   // into smaller operations.
750   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
751   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
752   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
753   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
754   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
755   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
756   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
757   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
758   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
759   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
760   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
761   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
762   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
763   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
764   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
765   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
766   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
767   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
768   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
769   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
770   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
771   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
772   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
773   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
774   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
775   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
776   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
777   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
778   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
779
780   if (!UseSoftFloat && Subtarget->hasXMM()) {
781     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
782
783     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
788     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
789     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
790     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
791     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
792     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
794     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
795   }
796
797   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
798     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
799
800     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
801     // registers cannot be used even for integer operations.
802     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
803     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
804     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
805     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
806
807     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
808     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
809     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
810     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
811     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
812     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
813     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
814     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
815     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
816     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
817     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
822     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
825     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
826     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
827     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
828
829     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
830     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
831     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
834
835     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
836     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
837     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
838     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
839     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
840
841     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
842     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
843       EVT VT = (MVT::SimpleValueType)i;
844       // Do not attempt to custom lower non-power-of-2 vectors
845       if (!isPowerOf2_32(VT.getVectorNumElements()))
846         continue;
847       // Do not attempt to custom lower non-128-bit vectors
848       if (!VT.is128BitVector())
849         continue;
850       setOperationAction(ISD::BUILD_VECTOR,
851                          VT.getSimpleVT().SimpleTy, Custom);
852       setOperationAction(ISD::VECTOR_SHUFFLE,
853                          VT.getSimpleVT().SimpleTy, Custom);
854       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
855                          VT.getSimpleVT().SimpleTy, Custom);
856     }
857
858     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
859     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
860     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
861     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
863     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
864
865     if (Subtarget->is64Bit()) {
866       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
867       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
868     }
869
870     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
871     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
872       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
873       EVT VT = SVT;
874
875       // Do not attempt to promote non-128-bit vectors
876       if (!VT.is128BitVector())
877         continue;
878
879       setOperationAction(ISD::AND,    SVT, Promote);
880       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
881       setOperationAction(ISD::OR,     SVT, Promote);
882       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
883       setOperationAction(ISD::XOR,    SVT, Promote);
884       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
885       setOperationAction(ISD::LOAD,   SVT, Promote);
886       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
887       setOperationAction(ISD::SELECT, SVT, Promote);
888       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
889     }
890
891     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
892
893     // Custom lower v2i64 and v2f64 selects.
894     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
895     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
896     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
897     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
898
899     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
900     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
901   }
902
903   if (Subtarget->hasSSE41()) {
904     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
905     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
906     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
907     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
908     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
909     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
910     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
911     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
912     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
913     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
914
915     // FIXME: Do we need to handle scalar-to-vector here?
916     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
917
918     // Can turn SHL into an integer multiply.
919     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
920     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
921
922     // i8 and i16 vectors are custom , because the source register and source
923     // source memory operand types are not the same width.  f32 vectors are
924     // custom since the immediate controlling the insert encodes additional
925     // information.
926     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
927     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
928     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
929     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
930
931     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
932     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
933     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
934     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
935
936     if (Subtarget->is64Bit()) {
937       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
938       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
939     }
940   }
941
942   if (Subtarget->hasSSE42())
943     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
944
945   if (!UseSoftFloat && Subtarget->hasAVX()) {
946     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
947     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
948     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
949     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
950     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
951
952     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
953     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
954     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
955     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
956
957     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
958     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
959     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
960     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
961     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
962     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
963
964     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
965     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
966     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
967     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
968     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
969     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
970
971     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
972     // insert_vector_elt extract_subvector and extract_vector_elt for
973     // 256-bit types.
974     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
975          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
976          ++i) {
977       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
978       // Do not attempt to custom lower non-256-bit vectors
979       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
980           || (MVT(VT).getSizeInBits() < 256))
981         continue;
982       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
983       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
984       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
985       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
986       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
987     }
988     // Custom-lower insert_subvector and extract_subvector based on
989     // the result type.
990     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
991          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
992          ++i) {
993       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
994       // Do not attempt to custom lower non-256-bit vectors
995       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
996         continue;
997
998       if (MVT(VT).getSizeInBits() == 128) {
999         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1000       }
1001       else if (MVT(VT).getSizeInBits() == 256) {
1002         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1003       }
1004     }
1005
1006     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1007     // Don't promote loads because we need them for VPERM vector index versions.
1008
1009     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1010          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1011          VT++) {
1012       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1013           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1014         continue;
1015       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1016       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1017       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1018       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1019       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1020       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1021       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1022       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1023       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1024       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1025     }
1026   }
1027
1028   // We want to custom lower some of our intrinsics.
1029   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1030
1031
1032   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1033   // handle type legalization for these operations here.
1034   //
1035   // FIXME: We really should do custom legalization for addition and
1036   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1037   // than generic legalization for 64-bit multiplication-with-overflow, though.
1038   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1039     // Add/Sub/Mul with overflow operations are custom lowered.
1040     MVT VT = IntVTs[i];
1041     setOperationAction(ISD::SADDO, VT, Custom);
1042     setOperationAction(ISD::UADDO, VT, Custom);
1043     setOperationAction(ISD::SSUBO, VT, Custom);
1044     setOperationAction(ISD::USUBO, VT, Custom);
1045     setOperationAction(ISD::SMULO, VT, Custom);
1046     setOperationAction(ISD::UMULO, VT, Custom);
1047   }
1048
1049   // There are no 8-bit 3-address imul/mul instructions
1050   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1051   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1052
1053   if (!Subtarget->is64Bit()) {
1054     // These libcalls are not available in 32-bit.
1055     setLibcallName(RTLIB::SHL_I128, 0);
1056     setLibcallName(RTLIB::SRL_I128, 0);
1057     setLibcallName(RTLIB::SRA_I128, 0);
1058   }
1059
1060   // We have target-specific dag combine patterns for the following nodes:
1061   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1062   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1063   setTargetDAGCombine(ISD::BUILD_VECTOR);
1064   setTargetDAGCombine(ISD::SELECT);
1065   setTargetDAGCombine(ISD::SHL);
1066   setTargetDAGCombine(ISD::SRA);
1067   setTargetDAGCombine(ISD::SRL);
1068   setTargetDAGCombine(ISD::OR);
1069   setTargetDAGCombine(ISD::AND);
1070   setTargetDAGCombine(ISD::ADD);
1071   setTargetDAGCombine(ISD::SUB);
1072   setTargetDAGCombine(ISD::STORE);
1073   setTargetDAGCombine(ISD::ZERO_EXTEND);
1074   if (Subtarget->is64Bit())
1075     setTargetDAGCombine(ISD::MUL);
1076
1077   computeRegisterProperties();
1078
1079   // On Darwin, -Os means optimize for size without hurting performance,
1080   // do not reduce the limit.
1081   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1082   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1083   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1084   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1085   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1086   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1087   setPrefLoopAlignment(16);
1088   benefitFromCodePlacementOpt = true;
1089 }
1090
1091
1092 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1093   return MVT::i8;
1094 }
1095
1096
1097 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1098 /// the desired ByVal argument alignment.
1099 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1100   if (MaxAlign == 16)
1101     return;
1102   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1103     if (VTy->getBitWidth() == 128)
1104       MaxAlign = 16;
1105   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1106     unsigned EltAlign = 0;
1107     getMaxByValAlign(ATy->getElementType(), EltAlign);
1108     if (EltAlign > MaxAlign)
1109       MaxAlign = EltAlign;
1110   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1111     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1112       unsigned EltAlign = 0;
1113       getMaxByValAlign(STy->getElementType(i), EltAlign);
1114       if (EltAlign > MaxAlign)
1115         MaxAlign = EltAlign;
1116       if (MaxAlign == 16)
1117         break;
1118     }
1119   }
1120   return;
1121 }
1122
1123 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1124 /// function arguments in the caller parameter area. For X86, aggregates
1125 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1126 /// are at 4-byte boundaries.
1127 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1128   if (Subtarget->is64Bit()) {
1129     // Max of 8 and alignment of type.
1130     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1131     if (TyAlign > 8)
1132       return TyAlign;
1133     return 8;
1134   }
1135
1136   unsigned Align = 4;
1137   if (Subtarget->hasXMM())
1138     getMaxByValAlign(Ty, Align);
1139   return Align;
1140 }
1141
1142 /// getOptimalMemOpType - Returns the target specific optimal type for load
1143 /// and store operations as a result of memset, memcpy, and memmove
1144 /// lowering. If DstAlign is zero that means it's safe to destination
1145 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1146 /// means there isn't a need to check it against alignment requirement,
1147 /// probably because the source does not need to be loaded. If
1148 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1149 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1150 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1151 /// constant so it does not need to be loaded.
1152 /// It returns EVT::Other if the type should be determined using generic
1153 /// target-independent logic.
1154 EVT
1155 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1156                                        unsigned DstAlign, unsigned SrcAlign,
1157                                        bool NonScalarIntSafe,
1158                                        bool MemcpyStrSrc,
1159                                        MachineFunction &MF) const {
1160   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1161   // linux.  This is because the stack realignment code can't handle certain
1162   // cases like PR2962.  This should be removed when PR2962 is fixed.
1163   const Function *F = MF.getFunction();
1164   if (NonScalarIntSafe &&
1165       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1166     if (Size >= 16 &&
1167         (Subtarget->isUnalignedMemAccessFast() ||
1168          ((DstAlign == 0 || DstAlign >= 16) &&
1169           (SrcAlign == 0 || SrcAlign >= 16))) &&
1170         Subtarget->getStackAlignment() >= 16) {
1171       if (Subtarget->hasSSE2())
1172         return MVT::v4i32;
1173       if (Subtarget->hasSSE1())
1174         return MVT::v4f32;
1175     } else if (!MemcpyStrSrc && Size >= 8 &&
1176                !Subtarget->is64Bit() &&
1177                Subtarget->getStackAlignment() >= 8 &&
1178                Subtarget->hasXMMInt()) {
1179       // Do not use f64 to lower memcpy if source is string constant. It's
1180       // better to use i32 to avoid the loads.
1181       return MVT::f64;
1182     }
1183   }
1184   if (Subtarget->is64Bit() && Size >= 8)
1185     return MVT::i64;
1186   return MVT::i32;
1187 }
1188
1189 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1190 /// current function.  The returned value is a member of the
1191 /// MachineJumpTableInfo::JTEntryKind enum.
1192 unsigned X86TargetLowering::getJumpTableEncoding() const {
1193   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1194   // symbol.
1195   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1196       Subtarget->isPICStyleGOT())
1197     return MachineJumpTableInfo::EK_Custom32;
1198
1199   // Otherwise, use the normal jump table encoding heuristics.
1200   return TargetLowering::getJumpTableEncoding();
1201 }
1202
1203 const MCExpr *
1204 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1205                                              const MachineBasicBlock *MBB,
1206                                              unsigned uid,MCContext &Ctx) const{
1207   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1208          Subtarget->isPICStyleGOT());
1209   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1210   // entries.
1211   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1212                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1213 }
1214
1215 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1216 /// jumptable.
1217 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1218                                                     SelectionDAG &DAG) const {
1219   if (!Subtarget->is64Bit())
1220     // This doesn't have DebugLoc associated with it, but is not really the
1221     // same as a Register.
1222     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1223   return Table;
1224 }
1225
1226 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1227 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1228 /// MCExpr.
1229 const MCExpr *X86TargetLowering::
1230 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1231                              MCContext &Ctx) const {
1232   // X86-64 uses RIP relative addressing based on the jump table label.
1233   if (Subtarget->isPICStyleRIPRel())
1234     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1235
1236   // Otherwise, the reference is relative to the PIC base.
1237   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1238 }
1239
1240 /// getFunctionAlignment - Return the Log2 alignment of this function.
1241 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1242   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1243 }
1244
1245 // FIXME: Why this routine is here? Move to RegInfo!
1246 std::pair<const TargetRegisterClass*, uint8_t>
1247 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1248   const TargetRegisterClass *RRC = 0;
1249   uint8_t Cost = 1;
1250   switch (VT.getSimpleVT().SimpleTy) {
1251   default:
1252     return TargetLowering::findRepresentativeClass(VT);
1253   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1254     RRC = (Subtarget->is64Bit()
1255            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1256     break;
1257   case MVT::x86mmx:
1258     RRC = X86::VR64RegisterClass;
1259     break;
1260   case MVT::f32: case MVT::f64:
1261   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1262   case MVT::v4f32: case MVT::v2f64:
1263   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1264   case MVT::v4f64:
1265     RRC = X86::VR128RegisterClass;
1266     break;
1267   }
1268   return std::make_pair(RRC, Cost);
1269 }
1270
1271 // FIXME: Why this routine is here? Move to RegInfo!
1272 unsigned
1273 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1274                                        MachineFunction &MF) const {
1275   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1276
1277   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1278   switch (RC->getID()) {
1279   default:
1280     return 0;
1281   case X86::GR32RegClassID:
1282     return 4 - FPDiff;
1283   case X86::GR64RegClassID:
1284     return 8 - FPDiff;
1285   case X86::VR128RegClassID:
1286     return Subtarget->is64Bit() ? 10 : 4;
1287   case X86::VR64RegClassID:
1288     return 4;
1289   }
1290 }
1291
1292 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1293                                                unsigned &Offset) const {
1294   if (!Subtarget->isTargetLinux())
1295     return false;
1296
1297   if (Subtarget->is64Bit()) {
1298     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1299     Offset = 0x28;
1300     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1301       AddressSpace = 256;
1302     else
1303       AddressSpace = 257;
1304   } else {
1305     // %gs:0x14 on i386
1306     Offset = 0x14;
1307     AddressSpace = 256;
1308   }
1309   return true;
1310 }
1311
1312
1313 //===----------------------------------------------------------------------===//
1314 //               Return Value Calling Convention Implementation
1315 //===----------------------------------------------------------------------===//
1316
1317 #include "X86GenCallingConv.inc"
1318
1319 bool
1320 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1321                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1322                         LLVMContext &Context) const {
1323   SmallVector<CCValAssign, 16> RVLocs;
1324   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1325                  RVLocs, Context);
1326   return CCInfo.CheckReturn(Outs, RetCC_X86);
1327 }
1328
1329 SDValue
1330 X86TargetLowering::LowerReturn(SDValue Chain,
1331                                CallingConv::ID CallConv, bool isVarArg,
1332                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1333                                const SmallVectorImpl<SDValue> &OutVals,
1334                                DebugLoc dl, SelectionDAG &DAG) const {
1335   MachineFunction &MF = DAG.getMachineFunction();
1336   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1337
1338   SmallVector<CCValAssign, 16> RVLocs;
1339   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1340                  RVLocs, *DAG.getContext());
1341   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1342
1343   // Add the regs to the liveout set for the function.
1344   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1345   for (unsigned i = 0; i != RVLocs.size(); ++i)
1346     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1347       MRI.addLiveOut(RVLocs[i].getLocReg());
1348
1349   SDValue Flag;
1350
1351   SmallVector<SDValue, 6> RetOps;
1352   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1353   // Operand #1 = Bytes To Pop
1354   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1355                    MVT::i16));
1356
1357   // Copy the result values into the output registers.
1358   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1359     CCValAssign &VA = RVLocs[i];
1360     assert(VA.isRegLoc() && "Can only return in registers!");
1361     SDValue ValToCopy = OutVals[i];
1362     EVT ValVT = ValToCopy.getValueType();
1363
1364     // If this is x86-64, and we disabled SSE, we can't return FP values,
1365     // or SSE or MMX vectors.
1366     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1367          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1368           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1369       report_fatal_error("SSE register return with SSE disabled");
1370     }
1371     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1372     // llvm-gcc has never done it right and no one has noticed, so this
1373     // should be OK for now.
1374     if (ValVT == MVT::f64 &&
1375         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1376       report_fatal_error("SSE2 register return with SSE2 disabled");
1377
1378     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1379     // the RET instruction and handled by the FP Stackifier.
1380     if (VA.getLocReg() == X86::ST0 ||
1381         VA.getLocReg() == X86::ST1) {
1382       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1383       // change the value to the FP stack register class.
1384       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1385         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1386       RetOps.push_back(ValToCopy);
1387       // Don't emit a copytoreg.
1388       continue;
1389     }
1390
1391     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1392     // which is returned in RAX / RDX.
1393     if (Subtarget->is64Bit()) {
1394       if (ValVT == MVT::x86mmx) {
1395         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1396           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1397           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1398                                   ValToCopy);
1399           // If we don't have SSE2 available, convert to v4f32 so the generated
1400           // register is legal.
1401           if (!Subtarget->hasSSE2())
1402             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1403         }
1404       }
1405     }
1406
1407     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1408     Flag = Chain.getValue(1);
1409   }
1410
1411   // The x86-64 ABI for returning structs by value requires that we copy
1412   // the sret argument into %rax for the return. We saved the argument into
1413   // a virtual register in the entry block, so now we copy the value out
1414   // and into %rax.
1415   if (Subtarget->is64Bit() &&
1416       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1417     MachineFunction &MF = DAG.getMachineFunction();
1418     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1419     unsigned Reg = FuncInfo->getSRetReturnReg();
1420     assert(Reg &&
1421            "SRetReturnReg should have been set in LowerFormalArguments().");
1422     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1423
1424     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1425     Flag = Chain.getValue(1);
1426
1427     // RAX now acts like a return value.
1428     MRI.addLiveOut(X86::RAX);
1429   }
1430
1431   RetOps[0] = Chain;  // Update chain.
1432
1433   // Add the flag if we have it.
1434   if (Flag.getNode())
1435     RetOps.push_back(Flag);
1436
1437   return DAG.getNode(X86ISD::RET_FLAG, dl,
1438                      MVT::Other, &RetOps[0], RetOps.size());
1439 }
1440
1441 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1442   if (N->getNumValues() != 1)
1443     return false;
1444   if (!N->hasNUsesOfValue(1, 0))
1445     return false;
1446
1447   SDNode *Copy = *N->use_begin();
1448   if (Copy->getOpcode() != ISD::CopyToReg &&
1449       Copy->getOpcode() != ISD::FP_EXTEND)
1450     return false;
1451
1452   bool HasRet = false;
1453   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1454        UI != UE; ++UI) {
1455     if (UI->getOpcode() != X86ISD::RET_FLAG)
1456       return false;
1457     HasRet = true;
1458   }
1459
1460   return HasRet;
1461 }
1462
1463 /// LowerCallResult - Lower the result values of a call into the
1464 /// appropriate copies out of appropriate physical registers.
1465 ///
1466 SDValue
1467 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1468                                    CallingConv::ID CallConv, bool isVarArg,
1469                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1470                                    DebugLoc dl, SelectionDAG &DAG,
1471                                    SmallVectorImpl<SDValue> &InVals) const {
1472
1473   // Assign locations to each value returned by this call.
1474   SmallVector<CCValAssign, 16> RVLocs;
1475   bool Is64Bit = Subtarget->is64Bit();
1476   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1477                  RVLocs, *DAG.getContext());
1478   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1479
1480   // Copy all of the result registers out of their specified physreg.
1481   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1482     CCValAssign &VA = RVLocs[i];
1483     EVT CopyVT = VA.getValVT();
1484
1485     // If this is x86-64, and we disabled SSE, we can't return FP values
1486     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1487         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1488       report_fatal_error("SSE register return with SSE disabled");
1489     }
1490
1491     SDValue Val;
1492
1493     // If this is a call to a function that returns an fp value on the floating
1494     // point stack, we must guarantee the the value is popped from the stack, so
1495     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1496     // if the return value is not used. We use the FpGET_ST0 instructions
1497     // instead.
1498     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1499       // If we prefer to use the value in xmm registers, copy it out as f80 and
1500       // use a truncate to move it from fp stack reg to xmm reg.
1501       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1502       bool isST0 = VA.getLocReg() == X86::ST0;
1503       unsigned Opc = 0;
1504       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1505       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1506       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1507       SDValue Ops[] = { Chain, InFlag };
1508       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1509                                          Ops, 2), 1);
1510       Val = Chain.getValue(0);
1511
1512       // Round the f80 to the right size, which also moves it to the appropriate
1513       // xmm register.
1514       if (CopyVT != VA.getValVT())
1515         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1516                           // This truncation won't change the value.
1517                           DAG.getIntPtrConstant(1));
1518     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1519       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1520       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1521         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1522                                    MVT::v2i64, InFlag).getValue(1);
1523         Val = Chain.getValue(0);
1524         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1525                           Val, DAG.getConstant(0, MVT::i64));
1526       } else {
1527         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1528                                    MVT::i64, InFlag).getValue(1);
1529         Val = Chain.getValue(0);
1530       }
1531       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1532     } else {
1533       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1534                                  CopyVT, InFlag).getValue(1);
1535       Val = Chain.getValue(0);
1536     }
1537     InFlag = Chain.getValue(2);
1538     InVals.push_back(Val);
1539   }
1540
1541   return Chain;
1542 }
1543
1544
1545 //===----------------------------------------------------------------------===//
1546 //                C & StdCall & Fast Calling Convention implementation
1547 //===----------------------------------------------------------------------===//
1548 //  StdCall calling convention seems to be standard for many Windows' API
1549 //  routines and around. It differs from C calling convention just a little:
1550 //  callee should clean up the stack, not caller. Symbols should be also
1551 //  decorated in some fancy way :) It doesn't support any vector arguments.
1552 //  For info on fast calling convention see Fast Calling Convention (tail call)
1553 //  implementation LowerX86_32FastCCCallTo.
1554
1555 /// CallIsStructReturn - Determines whether a call uses struct return
1556 /// semantics.
1557 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1558   if (Outs.empty())
1559     return false;
1560
1561   return Outs[0].Flags.isSRet();
1562 }
1563
1564 /// ArgsAreStructReturn - Determines whether a function uses struct
1565 /// return semantics.
1566 static bool
1567 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1568   if (Ins.empty())
1569     return false;
1570
1571   return Ins[0].Flags.isSRet();
1572 }
1573
1574 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1575 /// by "Src" to address "Dst" with size and alignment information specified by
1576 /// the specific parameter attribute. The copy will be passed as a byval
1577 /// function parameter.
1578 static SDValue
1579 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1580                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1581                           DebugLoc dl) {
1582   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1583
1584   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1585                        /*isVolatile*/false, /*AlwaysInline=*/true,
1586                        MachinePointerInfo(), MachinePointerInfo());
1587 }
1588
1589 /// IsTailCallConvention - Return true if the calling convention is one that
1590 /// supports tail call optimization.
1591 static bool IsTailCallConvention(CallingConv::ID CC) {
1592   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1593 }
1594
1595 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1596 /// a tailcall target by changing its ABI.
1597 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1598   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1599 }
1600
1601 SDValue
1602 X86TargetLowering::LowerMemArgument(SDValue Chain,
1603                                     CallingConv::ID CallConv,
1604                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1605                                     DebugLoc dl, SelectionDAG &DAG,
1606                                     const CCValAssign &VA,
1607                                     MachineFrameInfo *MFI,
1608                                     unsigned i) const {
1609   // Create the nodes corresponding to a load from this parameter slot.
1610   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1611   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1612   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1613   EVT ValVT;
1614
1615   // If value is passed by pointer we have address passed instead of the value
1616   // itself.
1617   if (VA.getLocInfo() == CCValAssign::Indirect)
1618     ValVT = VA.getLocVT();
1619   else
1620     ValVT = VA.getValVT();
1621
1622   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1623   // changed with more analysis.
1624   // In case of tail call optimization mark all arguments mutable. Since they
1625   // could be overwritten by lowering of arguments in case of a tail call.
1626   if (Flags.isByVal()) {
1627     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1628                                     VA.getLocMemOffset(), isImmutable);
1629     return DAG.getFrameIndex(FI, getPointerTy());
1630   } else {
1631     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1632                                     VA.getLocMemOffset(), isImmutable);
1633     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1634     return DAG.getLoad(ValVT, dl, Chain, FIN,
1635                        MachinePointerInfo::getFixedStack(FI),
1636                        false, false, 0);
1637   }
1638 }
1639
1640 SDValue
1641 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1642                                         CallingConv::ID CallConv,
1643                                         bool isVarArg,
1644                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1645                                         DebugLoc dl,
1646                                         SelectionDAG &DAG,
1647                                         SmallVectorImpl<SDValue> &InVals)
1648                                           const {
1649   MachineFunction &MF = DAG.getMachineFunction();
1650   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1651
1652   const Function* Fn = MF.getFunction();
1653   if (Fn->hasExternalLinkage() &&
1654       Subtarget->isTargetCygMing() &&
1655       Fn->getName() == "main")
1656     FuncInfo->setForceFramePointer(true);
1657
1658   MachineFrameInfo *MFI = MF.getFrameInfo();
1659   bool Is64Bit = Subtarget->is64Bit();
1660   bool IsWin64 = Subtarget->isTargetWin64();
1661
1662   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1663          "Var args not supported with calling convention fastcc or ghc");
1664
1665   // Assign locations to all of the incoming arguments.
1666   SmallVector<CCValAssign, 16> ArgLocs;
1667   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1668                  ArgLocs, *DAG.getContext());
1669   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1670
1671   unsigned LastVal = ~0U;
1672   SDValue ArgValue;
1673   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1674     CCValAssign &VA = ArgLocs[i];
1675     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1676     // places.
1677     assert(VA.getValNo() != LastVal &&
1678            "Don't support value assigned to multiple locs yet");
1679     LastVal = VA.getValNo();
1680
1681     if (VA.isRegLoc()) {
1682       EVT RegVT = VA.getLocVT();
1683       TargetRegisterClass *RC = NULL;
1684       if (RegVT == MVT::i32)
1685         RC = X86::GR32RegisterClass;
1686       else if (Is64Bit && RegVT == MVT::i64)
1687         RC = X86::GR64RegisterClass;
1688       else if (RegVT == MVT::f32)
1689         RC = X86::FR32RegisterClass;
1690       else if (RegVT == MVT::f64)
1691         RC = X86::FR64RegisterClass;
1692       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1693         RC = X86::VR256RegisterClass;
1694       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1695         RC = X86::VR128RegisterClass;
1696       else if (RegVT == MVT::x86mmx)
1697         RC = X86::VR64RegisterClass;
1698       else
1699         llvm_unreachable("Unknown argument type!");
1700
1701       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC, dl);
1702       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1703
1704       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1705       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1706       // right size.
1707       if (VA.getLocInfo() == CCValAssign::SExt)
1708         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1709                                DAG.getValueType(VA.getValVT()));
1710       else if (VA.getLocInfo() == CCValAssign::ZExt)
1711         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1712                                DAG.getValueType(VA.getValVT()));
1713       else if (VA.getLocInfo() == CCValAssign::BCvt)
1714         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1715
1716       if (VA.isExtInLoc()) {
1717         // Handle MMX values passed in XMM regs.
1718         if (RegVT.isVector()) {
1719           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1720                                  ArgValue);
1721         } else
1722           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1723       }
1724     } else {
1725       assert(VA.isMemLoc());
1726       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1727     }
1728
1729     // If value is passed via pointer - do a load.
1730     if (VA.getLocInfo() == CCValAssign::Indirect)
1731       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1732                              MachinePointerInfo(), false, false, 0);
1733
1734     InVals.push_back(ArgValue);
1735   }
1736
1737   // The x86-64 ABI for returning structs by value requires that we copy
1738   // the sret argument into %rax for the return. Save the argument into
1739   // a virtual register so that we can access it from the return points.
1740   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1741     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1742     unsigned Reg = FuncInfo->getSRetReturnReg();
1743     if (!Reg) {
1744       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1745       FuncInfo->setSRetReturnReg(Reg);
1746     }
1747     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1748     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1749   }
1750
1751   unsigned StackSize = CCInfo.getNextStackOffset();
1752   // Align stack specially for tail calls.
1753   if (FuncIsMadeTailCallSafe(CallConv))
1754     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1755
1756   // If the function takes variable number of arguments, make a frame index for
1757   // the start of the first vararg value... for expansion of llvm.va_start.
1758   if (isVarArg) {
1759     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1760                     CallConv != CallingConv::X86_ThisCall))) {
1761       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1762     }
1763     if (Is64Bit) {
1764       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1765
1766       // FIXME: We should really autogenerate these arrays
1767       static const unsigned GPR64ArgRegsWin64[] = {
1768         X86::RCX, X86::RDX, X86::R8,  X86::R9
1769       };
1770       static const unsigned GPR64ArgRegs64Bit[] = {
1771         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1772       };
1773       static const unsigned XMMArgRegs64Bit[] = {
1774         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1775         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1776       };
1777       const unsigned *GPR64ArgRegs;
1778       unsigned NumXMMRegs = 0;
1779
1780       if (IsWin64) {
1781         // The XMM registers which might contain var arg parameters are shadowed
1782         // in their paired GPR.  So we only need to save the GPR to their home
1783         // slots.
1784         TotalNumIntRegs = 4;
1785         GPR64ArgRegs = GPR64ArgRegsWin64;
1786       } else {
1787         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1788         GPR64ArgRegs = GPR64ArgRegs64Bit;
1789
1790         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1791       }
1792       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1793                                                        TotalNumIntRegs);
1794
1795       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1796       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1797              "SSE register cannot be used when SSE is disabled!");
1798       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1799              "SSE register cannot be used when SSE is disabled!");
1800       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1801         // Kernel mode asks for SSE to be disabled, so don't push them
1802         // on the stack.
1803         TotalNumXMMRegs = 0;
1804
1805       if (IsWin64) {
1806         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1807         // Get to the caller-allocated home save location.  Add 8 to account
1808         // for the return address.
1809         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1810         FuncInfo->setRegSaveFrameIndex(
1811           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1812         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1813       } else {
1814         // For X86-64, if there are vararg parameters that are passed via
1815         // registers, then we must store them to their spots on the stack so they
1816         // may be loaded by deferencing the result of va_next.
1817         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1818         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1819         FuncInfo->setRegSaveFrameIndex(
1820           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1821                                false));
1822       }
1823
1824       // Store the integer parameter registers.
1825       SmallVector<SDValue, 8> MemOps;
1826       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1827                                         getPointerTy());
1828       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1829       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1830         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1831                                   DAG.getIntPtrConstant(Offset));
1832         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1833                                      X86::GR64RegisterClass, dl);
1834         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1835         SDValue Store =
1836           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1837                        MachinePointerInfo::getFixedStack(
1838                          FuncInfo->getRegSaveFrameIndex(), Offset),
1839                        false, false, 0);
1840         MemOps.push_back(Store);
1841         Offset += 8;
1842       }
1843
1844       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1845         // Now store the XMM (fp + vector) parameter registers.
1846         SmallVector<SDValue, 11> SaveXMMOps;
1847         SaveXMMOps.push_back(Chain);
1848
1849         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass, dl);
1850         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1851         SaveXMMOps.push_back(ALVal);
1852
1853         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1854                                FuncInfo->getRegSaveFrameIndex()));
1855         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1856                                FuncInfo->getVarArgsFPOffset()));
1857
1858         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1859           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1860                                        X86::VR128RegisterClass, dl);
1861           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1862           SaveXMMOps.push_back(Val);
1863         }
1864         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1865                                      MVT::Other,
1866                                      &SaveXMMOps[0], SaveXMMOps.size()));
1867       }
1868
1869       if (!MemOps.empty())
1870         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1871                             &MemOps[0], MemOps.size());
1872     }
1873   }
1874
1875   // Some CCs need callee pop.
1876   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1877     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1878   } else {
1879     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1880     // If this is an sret function, the return should pop the hidden pointer.
1881     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1882       FuncInfo->setBytesToPopOnReturn(4);
1883   }
1884
1885   if (!Is64Bit) {
1886     // RegSaveFrameIndex is X86-64 only.
1887     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1888     if (CallConv == CallingConv::X86_FastCall ||
1889         CallConv == CallingConv::X86_ThisCall)
1890       // fastcc functions can't have varargs.
1891       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1892   }
1893
1894   return Chain;
1895 }
1896
1897 SDValue
1898 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1899                                     SDValue StackPtr, SDValue Arg,
1900                                     DebugLoc dl, SelectionDAG &DAG,
1901                                     const CCValAssign &VA,
1902                                     ISD::ArgFlagsTy Flags) const {
1903   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1904   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1905   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1906   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1907   if (Flags.isByVal())
1908     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1909
1910   return DAG.getStore(Chain, dl, Arg, PtrOff,
1911                       MachinePointerInfo::getStack(LocMemOffset),
1912                       false, false, 0);
1913 }
1914
1915 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1916 /// optimization is performed and it is required.
1917 SDValue
1918 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1919                                            SDValue &OutRetAddr, SDValue Chain,
1920                                            bool IsTailCall, bool Is64Bit,
1921                                            int FPDiff, DebugLoc dl) const {
1922   // Adjust the Return address stack slot.
1923   EVT VT = getPointerTy();
1924   OutRetAddr = getReturnAddressFrameIndex(DAG);
1925
1926   // Load the "old" Return address.
1927   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1928                            false, false, 0);
1929   return SDValue(OutRetAddr.getNode(), 1);
1930 }
1931
1932 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1933 /// optimization is performed and it is required (FPDiff!=0).
1934 static SDValue
1935 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1936                          SDValue Chain, SDValue RetAddrFrIdx,
1937                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1938   // Store the return address to the appropriate stack slot.
1939   if (!FPDiff) return Chain;
1940   // Calculate the new stack slot for the return address.
1941   int SlotSize = Is64Bit ? 8 : 4;
1942   int NewReturnAddrFI =
1943     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1944   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1945   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1946   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1947                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1948                        false, false, 0);
1949   return Chain;
1950 }
1951
1952 SDValue
1953 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1954                              CallingConv::ID CallConv, bool isVarArg,
1955                              bool &isTailCall,
1956                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1957                              const SmallVectorImpl<SDValue> &OutVals,
1958                              const SmallVectorImpl<ISD::InputArg> &Ins,
1959                              DebugLoc dl, SelectionDAG &DAG,
1960                              SmallVectorImpl<SDValue> &InVals) const {
1961   MachineFunction &MF = DAG.getMachineFunction();
1962   bool Is64Bit        = Subtarget->is64Bit();
1963   bool IsStructRet    = CallIsStructReturn(Outs);
1964   bool IsSibcall      = false;
1965
1966   if (isTailCall) {
1967     // Check if it's really possible to do a tail call.
1968     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1969                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1970                                                    Outs, OutVals, Ins, DAG);
1971
1972     // Sibcalls are automatically detected tailcalls which do not require
1973     // ABI changes.
1974     if (!GuaranteedTailCallOpt && isTailCall)
1975       IsSibcall = true;
1976
1977     if (isTailCall)
1978       ++NumTailCalls;
1979   }
1980
1981   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1982          "Var args not supported with calling convention fastcc or ghc");
1983
1984   // Analyze operands of the call, assigning locations to each operand.
1985   SmallVector<CCValAssign, 16> ArgLocs;
1986   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1987                  ArgLocs, *DAG.getContext());
1988   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1989
1990   // Get a count of how many bytes are to be pushed on the stack.
1991   unsigned NumBytes = CCInfo.getNextStackOffset();
1992   if (IsSibcall)
1993     // This is a sibcall. The memory operands are available in caller's
1994     // own caller's stack.
1995     NumBytes = 0;
1996   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1997     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1998
1999   int FPDiff = 0;
2000   if (isTailCall && !IsSibcall) {
2001     // Lower arguments at fp - stackoffset + fpdiff.
2002     unsigned NumBytesCallerPushed =
2003       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2004     FPDiff = NumBytesCallerPushed - NumBytes;
2005
2006     // Set the delta of movement of the returnaddr stackslot.
2007     // But only set if delta is greater than previous delta.
2008     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2009       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2010   }
2011
2012   if (!IsSibcall)
2013     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2014
2015   SDValue RetAddrFrIdx;
2016   // Load return adress for tail calls.
2017   if (isTailCall && FPDiff)
2018     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2019                                     Is64Bit, FPDiff, dl);
2020
2021   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2022   SmallVector<SDValue, 8> MemOpChains;
2023   SDValue StackPtr;
2024
2025   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2026   // of tail call optimization arguments are handle later.
2027   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2028     CCValAssign &VA = ArgLocs[i];
2029     EVT RegVT = VA.getLocVT();
2030     SDValue Arg = OutVals[i];
2031     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2032     bool isByVal = Flags.isByVal();
2033
2034     // Promote the value if needed.
2035     switch (VA.getLocInfo()) {
2036     default: llvm_unreachable("Unknown loc info!");
2037     case CCValAssign::Full: break;
2038     case CCValAssign::SExt:
2039       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2040       break;
2041     case CCValAssign::ZExt:
2042       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2043       break;
2044     case CCValAssign::AExt:
2045       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2046         // Special case: passing MMX values in XMM registers.
2047         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2048         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2049         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2050       } else
2051         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2052       break;
2053     case CCValAssign::BCvt:
2054       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2055       break;
2056     case CCValAssign::Indirect: {
2057       // Store the argument.
2058       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2059       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2060       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2061                            MachinePointerInfo::getFixedStack(FI),
2062                            false, false, 0);
2063       Arg = SpillSlot;
2064       break;
2065     }
2066     }
2067
2068     if (VA.isRegLoc()) {
2069       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2070       if (isVarArg && Subtarget->isTargetWin64()) {
2071         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2072         // shadow reg if callee is a varargs function.
2073         unsigned ShadowReg = 0;
2074         switch (VA.getLocReg()) {
2075         case X86::XMM0: ShadowReg = X86::RCX; break;
2076         case X86::XMM1: ShadowReg = X86::RDX; break;
2077         case X86::XMM2: ShadowReg = X86::R8; break;
2078         case X86::XMM3: ShadowReg = X86::R9; break;
2079         }
2080         if (ShadowReg)
2081           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2082       }
2083     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2084       assert(VA.isMemLoc());
2085       if (StackPtr.getNode() == 0)
2086         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2087       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2088                                              dl, DAG, VA, Flags));
2089     }
2090   }
2091
2092   if (!MemOpChains.empty())
2093     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2094                         &MemOpChains[0], MemOpChains.size());
2095
2096   // Build a sequence of copy-to-reg nodes chained together with token chain
2097   // and flag operands which copy the outgoing args into registers.
2098   SDValue InFlag;
2099   // Tail call byval lowering might overwrite argument registers so in case of
2100   // tail call optimization the copies to registers are lowered later.
2101   if (!isTailCall)
2102     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2103       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2104                                RegsToPass[i].second, InFlag);
2105       InFlag = Chain.getValue(1);
2106     }
2107
2108   if (Subtarget->isPICStyleGOT()) {
2109     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2110     // GOT pointer.
2111     if (!isTailCall) {
2112       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2113                                DAG.getNode(X86ISD::GlobalBaseReg,
2114                                            DebugLoc(), getPointerTy()),
2115                                InFlag);
2116       InFlag = Chain.getValue(1);
2117     } else {
2118       // If we are tail calling and generating PIC/GOT style code load the
2119       // address of the callee into ECX. The value in ecx is used as target of
2120       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2121       // for tail calls on PIC/GOT architectures. Normally we would just put the
2122       // address of GOT into ebx and then call target@PLT. But for tail calls
2123       // ebx would be restored (since ebx is callee saved) before jumping to the
2124       // target@PLT.
2125
2126       // Note: The actual moving to ECX is done further down.
2127       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2128       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2129           !G->getGlobal()->hasProtectedVisibility())
2130         Callee = LowerGlobalAddress(Callee, DAG);
2131       else if (isa<ExternalSymbolSDNode>(Callee))
2132         Callee = LowerExternalSymbol(Callee, DAG);
2133     }
2134   }
2135
2136   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2137     // From AMD64 ABI document:
2138     // For calls that may call functions that use varargs or stdargs
2139     // (prototype-less calls or calls to functions containing ellipsis (...) in
2140     // the declaration) %al is used as hidden argument to specify the number
2141     // of SSE registers used. The contents of %al do not need to match exactly
2142     // the number of registers, but must be an ubound on the number of SSE
2143     // registers used and is in the range 0 - 8 inclusive.
2144
2145     // Count the number of XMM registers allocated.
2146     static const unsigned XMMArgRegs[] = {
2147       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2148       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2149     };
2150     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2151     assert((Subtarget->hasXMM() || !NumXMMRegs)
2152            && "SSE registers cannot be used when SSE is disabled");
2153
2154     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2155                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2156     InFlag = Chain.getValue(1);
2157   }
2158
2159
2160   // For tail calls lower the arguments to the 'real' stack slot.
2161   if (isTailCall) {
2162     // Force all the incoming stack arguments to be loaded from the stack
2163     // before any new outgoing arguments are stored to the stack, because the
2164     // outgoing stack slots may alias the incoming argument stack slots, and
2165     // the alias isn't otherwise explicit. This is slightly more conservative
2166     // than necessary, because it means that each store effectively depends
2167     // on every argument instead of just those arguments it would clobber.
2168     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2169
2170     SmallVector<SDValue, 8> MemOpChains2;
2171     SDValue FIN;
2172     int FI = 0;
2173     // Do not flag preceeding copytoreg stuff together with the following stuff.
2174     InFlag = SDValue();
2175     if (GuaranteedTailCallOpt) {
2176       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2177         CCValAssign &VA = ArgLocs[i];
2178         if (VA.isRegLoc())
2179           continue;
2180         assert(VA.isMemLoc());
2181         SDValue Arg = OutVals[i];
2182         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2183         // Create frame index.
2184         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2185         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2186         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2187         FIN = DAG.getFrameIndex(FI, getPointerTy());
2188
2189         if (Flags.isByVal()) {
2190           // Copy relative to framepointer.
2191           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2192           if (StackPtr.getNode() == 0)
2193             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2194                                           getPointerTy());
2195           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2196
2197           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2198                                                            ArgChain,
2199                                                            Flags, DAG, dl));
2200         } else {
2201           // Store relative to framepointer.
2202           MemOpChains2.push_back(
2203             DAG.getStore(ArgChain, dl, Arg, FIN,
2204                          MachinePointerInfo::getFixedStack(FI),
2205                          false, false, 0));
2206         }
2207       }
2208     }
2209
2210     if (!MemOpChains2.empty())
2211       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2212                           &MemOpChains2[0], MemOpChains2.size());
2213
2214     // Copy arguments to their registers.
2215     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2216       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2217                                RegsToPass[i].second, InFlag);
2218       InFlag = Chain.getValue(1);
2219     }
2220     InFlag =SDValue();
2221
2222     // Store the return address to the appropriate stack slot.
2223     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2224                                      FPDiff, dl);
2225   }
2226
2227   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2228     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2229     // In the 64-bit large code model, we have to make all calls
2230     // through a register, since the call instruction's 32-bit
2231     // pc-relative offset may not be large enough to hold the whole
2232     // address.
2233   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2234     // If the callee is a GlobalAddress node (quite common, every direct call
2235     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2236     // it.
2237
2238     // We should use extra load for direct calls to dllimported functions in
2239     // non-JIT mode.
2240     const GlobalValue *GV = G->getGlobal();
2241     if (!GV->hasDLLImportLinkage()) {
2242       unsigned char OpFlags = 0;
2243
2244       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2245       // external symbols most go through the PLT in PIC mode.  If the symbol
2246       // has hidden or protected visibility, or if it is static or local, then
2247       // we don't need to use the PLT - we can directly call it.
2248       if (Subtarget->isTargetELF() &&
2249           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2250           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2251         OpFlags = X86II::MO_PLT;
2252       } else if (Subtarget->isPICStyleStubAny() &&
2253                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2254                  Subtarget->getDarwinVers() < 9) {
2255         // PC-relative references to external symbols should go through $stub,
2256         // unless we're building with the leopard linker or later, which
2257         // automatically synthesizes these stubs.
2258         OpFlags = X86II::MO_DARWIN_STUB;
2259       }
2260
2261       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2262                                           G->getOffset(), OpFlags);
2263     }
2264   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2265     unsigned char OpFlags = 0;
2266
2267     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2268     // external symbols should go through the PLT.
2269     if (Subtarget->isTargetELF() &&
2270         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2271       OpFlags = X86II::MO_PLT;
2272     } else if (Subtarget->isPICStyleStubAny() &&
2273                Subtarget->getDarwinVers() < 9) {
2274       // PC-relative references to external symbols should go through $stub,
2275       // unless we're building with the leopard linker or later, which
2276       // automatically synthesizes these stubs.
2277       OpFlags = X86II::MO_DARWIN_STUB;
2278     }
2279
2280     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2281                                          OpFlags);
2282   }
2283
2284   // Returns a chain & a flag for retval copy to use.
2285   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2286   SmallVector<SDValue, 8> Ops;
2287
2288   if (!IsSibcall && isTailCall) {
2289     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2290                            DAG.getIntPtrConstant(0, true), InFlag);
2291     InFlag = Chain.getValue(1);
2292   }
2293
2294   Ops.push_back(Chain);
2295   Ops.push_back(Callee);
2296
2297   if (isTailCall)
2298     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2299
2300   // Add argument registers to the end of the list so that they are known live
2301   // into the call.
2302   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2303     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2304                                   RegsToPass[i].second.getValueType()));
2305
2306   // Add an implicit use GOT pointer in EBX.
2307   if (!isTailCall && Subtarget->isPICStyleGOT())
2308     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2309
2310   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2311   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2312     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2313
2314   if (InFlag.getNode())
2315     Ops.push_back(InFlag);
2316
2317   if (isTailCall) {
2318     // We used to do:
2319     //// If this is the first return lowered for this function, add the regs
2320     //// to the liveout set for the function.
2321     // This isn't right, although it's probably harmless on x86; liveouts
2322     // should be computed from returns not tail calls.  Consider a void
2323     // function making a tail call to a function returning int.
2324     return DAG.getNode(X86ISD::TC_RETURN, dl,
2325                        NodeTys, &Ops[0], Ops.size());
2326   }
2327
2328   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2329   InFlag = Chain.getValue(1);
2330
2331   // Create the CALLSEQ_END node.
2332   unsigned NumBytesForCalleeToPush;
2333   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2334     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2335   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2336     // If this is a call to a struct-return function, the callee
2337     // pops the hidden struct pointer, so we have to push it back.
2338     // This is common for Darwin/X86, Linux & Mingw32 targets.
2339     NumBytesForCalleeToPush = 4;
2340   else
2341     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2342
2343   // Returns a flag for retval copy to use.
2344   if (!IsSibcall) {
2345     Chain = DAG.getCALLSEQ_END(Chain,
2346                                DAG.getIntPtrConstant(NumBytes, true),
2347                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2348                                                      true),
2349                                InFlag);
2350     InFlag = Chain.getValue(1);
2351   }
2352
2353   // Handle result values, copying them out of physregs into vregs that we
2354   // return.
2355   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2356                          Ins, dl, DAG, InVals);
2357 }
2358
2359
2360 //===----------------------------------------------------------------------===//
2361 //                Fast Calling Convention (tail call) implementation
2362 //===----------------------------------------------------------------------===//
2363
2364 //  Like std call, callee cleans arguments, convention except that ECX is
2365 //  reserved for storing the tail called function address. Only 2 registers are
2366 //  free for argument passing (inreg). Tail call optimization is performed
2367 //  provided:
2368 //                * tailcallopt is enabled
2369 //                * caller/callee are fastcc
2370 //  On X86_64 architecture with GOT-style position independent code only local
2371 //  (within module) calls are supported at the moment.
2372 //  To keep the stack aligned according to platform abi the function
2373 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2374 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2375 //  If a tail called function callee has more arguments than the caller the
2376 //  caller needs to make sure that there is room to move the RETADDR to. This is
2377 //  achieved by reserving an area the size of the argument delta right after the
2378 //  original REtADDR, but before the saved framepointer or the spilled registers
2379 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2380 //  stack layout:
2381 //    arg1
2382 //    arg2
2383 //    RETADDR
2384 //    [ new RETADDR
2385 //      move area ]
2386 //    (possible EBP)
2387 //    ESI
2388 //    EDI
2389 //    local1 ..
2390
2391 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2392 /// for a 16 byte align requirement.
2393 unsigned
2394 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2395                                                SelectionDAG& DAG) const {
2396   MachineFunction &MF = DAG.getMachineFunction();
2397   const TargetMachine &TM = MF.getTarget();
2398   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2399   unsigned StackAlignment = TFI.getStackAlignment();
2400   uint64_t AlignMask = StackAlignment - 1;
2401   int64_t Offset = StackSize;
2402   uint64_t SlotSize = TD->getPointerSize();
2403   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2404     // Number smaller than 12 so just add the difference.
2405     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2406   } else {
2407     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2408     Offset = ((~AlignMask) & Offset) + StackAlignment +
2409       (StackAlignment-SlotSize);
2410   }
2411   return Offset;
2412 }
2413
2414 /// MatchingStackOffset - Return true if the given stack call argument is
2415 /// already available in the same position (relatively) of the caller's
2416 /// incoming argument stack.
2417 static
2418 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2419                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2420                          const X86InstrInfo *TII) {
2421   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2422   int FI = INT_MAX;
2423   if (Arg.getOpcode() == ISD::CopyFromReg) {
2424     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2425     if (!TargetRegisterInfo::isVirtualRegister(VR))
2426       return false;
2427     MachineInstr *Def = MRI->getVRegDef(VR);
2428     if (!Def)
2429       return false;
2430     if (!Flags.isByVal()) {
2431       if (!TII->isLoadFromStackSlot(Def, FI))
2432         return false;
2433     } else {
2434       unsigned Opcode = Def->getOpcode();
2435       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2436           Def->getOperand(1).isFI()) {
2437         FI = Def->getOperand(1).getIndex();
2438         Bytes = Flags.getByValSize();
2439       } else
2440         return false;
2441     }
2442   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2443     if (Flags.isByVal())
2444       // ByVal argument is passed in as a pointer but it's now being
2445       // dereferenced. e.g.
2446       // define @foo(%struct.X* %A) {
2447       //   tail call @bar(%struct.X* byval %A)
2448       // }
2449       return false;
2450     SDValue Ptr = Ld->getBasePtr();
2451     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2452     if (!FINode)
2453       return false;
2454     FI = FINode->getIndex();
2455   } else
2456     return false;
2457
2458   assert(FI != INT_MAX);
2459   if (!MFI->isFixedObjectIndex(FI))
2460     return false;
2461   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2462 }
2463
2464 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2465 /// for tail call optimization. Targets which want to do tail call
2466 /// optimization should implement this function.
2467 bool
2468 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2469                                                      CallingConv::ID CalleeCC,
2470                                                      bool isVarArg,
2471                                                      bool isCalleeStructRet,
2472                                                      bool isCallerStructRet,
2473                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2474                                     const SmallVectorImpl<SDValue> &OutVals,
2475                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2476                                                      SelectionDAG& DAG) const {
2477   if (!IsTailCallConvention(CalleeCC) &&
2478       CalleeCC != CallingConv::C)
2479     return false;
2480
2481   // If -tailcallopt is specified, make fastcc functions tail-callable.
2482   const MachineFunction &MF = DAG.getMachineFunction();
2483   const Function *CallerF = DAG.getMachineFunction().getFunction();
2484   CallingConv::ID CallerCC = CallerF->getCallingConv();
2485   bool CCMatch = CallerCC == CalleeCC;
2486
2487   if (GuaranteedTailCallOpt) {
2488     if (IsTailCallConvention(CalleeCC) && CCMatch)
2489       return true;
2490     return false;
2491   }
2492
2493   // Look for obvious safe cases to perform tail call optimization that do not
2494   // require ABI changes. This is what gcc calls sibcall.
2495
2496   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2497   // emit a special epilogue.
2498   if (RegInfo->needsStackRealignment(MF))
2499     return false;
2500
2501   // Do not sibcall optimize vararg calls unless the call site is not passing
2502   // any arguments.
2503   if (isVarArg && !Outs.empty())
2504     return false;
2505
2506   // Also avoid sibcall optimization if either caller or callee uses struct
2507   // return semantics.
2508   if (isCalleeStructRet || isCallerStructRet)
2509     return false;
2510
2511   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2512   // Therefore if it's not used by the call it is not safe to optimize this into
2513   // a sibcall.
2514   bool Unused = false;
2515   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2516     if (!Ins[i].Used) {
2517       Unused = true;
2518       break;
2519     }
2520   }
2521   if (Unused) {
2522     SmallVector<CCValAssign, 16> RVLocs;
2523     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2524                    RVLocs, *DAG.getContext());
2525     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2526     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2527       CCValAssign &VA = RVLocs[i];
2528       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2529         return false;
2530     }
2531   }
2532
2533   // If the calling conventions do not match, then we'd better make sure the
2534   // results are returned in the same way as what the caller expects.
2535   if (!CCMatch) {
2536     SmallVector<CCValAssign, 16> RVLocs1;
2537     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2538                     RVLocs1, *DAG.getContext());
2539     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2540
2541     SmallVector<CCValAssign, 16> RVLocs2;
2542     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2543                     RVLocs2, *DAG.getContext());
2544     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2545
2546     if (RVLocs1.size() != RVLocs2.size())
2547       return false;
2548     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2549       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2550         return false;
2551       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2552         return false;
2553       if (RVLocs1[i].isRegLoc()) {
2554         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2555           return false;
2556       } else {
2557         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2558           return false;
2559       }
2560     }
2561   }
2562
2563   // If the callee takes no arguments then go on to check the results of the
2564   // call.
2565   if (!Outs.empty()) {
2566     // Check if stack adjustment is needed. For now, do not do this if any
2567     // argument is passed on the stack.
2568     SmallVector<CCValAssign, 16> ArgLocs;
2569     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2570                    ArgLocs, *DAG.getContext());
2571     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2572     if (CCInfo.getNextStackOffset()) {
2573       MachineFunction &MF = DAG.getMachineFunction();
2574       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2575         return false;
2576
2577       // Check if the arguments are already laid out in the right way as
2578       // the caller's fixed stack objects.
2579       MachineFrameInfo *MFI = MF.getFrameInfo();
2580       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2581       const X86InstrInfo *TII =
2582         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2583       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2584         CCValAssign &VA = ArgLocs[i];
2585         SDValue Arg = OutVals[i];
2586         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2587         if (VA.getLocInfo() == CCValAssign::Indirect)
2588           return false;
2589         if (!VA.isRegLoc()) {
2590           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2591                                    MFI, MRI, TII))
2592             return false;
2593         }
2594       }
2595     }
2596
2597     // If the tailcall address may be in a register, then make sure it's
2598     // possible to register allocate for it. In 32-bit, the call address can
2599     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2600     // callee-saved registers are restored. These happen to be the same
2601     // registers used to pass 'inreg' arguments so watch out for those.
2602     if (!Subtarget->is64Bit() &&
2603         !isa<GlobalAddressSDNode>(Callee) &&
2604         !isa<ExternalSymbolSDNode>(Callee)) {
2605       unsigned NumInRegs = 0;
2606       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2607         CCValAssign &VA = ArgLocs[i];
2608         if (!VA.isRegLoc())
2609           continue;
2610         unsigned Reg = VA.getLocReg();
2611         switch (Reg) {
2612         default: break;
2613         case X86::EAX: case X86::EDX: case X86::ECX:
2614           if (++NumInRegs == 3)
2615             return false;
2616           break;
2617         }
2618       }
2619     }
2620   }
2621
2622   // An stdcall caller is expected to clean up its arguments; the callee
2623   // isn't going to do that.
2624   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2625     return false;
2626
2627   return true;
2628 }
2629
2630 FastISel *
2631 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2632   return X86::createFastISel(funcInfo);
2633 }
2634
2635
2636 //===----------------------------------------------------------------------===//
2637 //                           Other Lowering Hooks
2638 //===----------------------------------------------------------------------===//
2639
2640 static bool MayFoldLoad(SDValue Op) {
2641   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2642 }
2643
2644 static bool MayFoldIntoStore(SDValue Op) {
2645   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2646 }
2647
2648 static bool isTargetShuffle(unsigned Opcode) {
2649   switch(Opcode) {
2650   default: return false;
2651   case X86ISD::PSHUFD:
2652   case X86ISD::PSHUFHW:
2653   case X86ISD::PSHUFLW:
2654   case X86ISD::SHUFPD:
2655   case X86ISD::PALIGN:
2656   case X86ISD::SHUFPS:
2657   case X86ISD::MOVLHPS:
2658   case X86ISD::MOVLHPD:
2659   case X86ISD::MOVHLPS:
2660   case X86ISD::MOVLPS:
2661   case X86ISD::MOVLPD:
2662   case X86ISD::MOVSHDUP:
2663   case X86ISD::MOVSLDUP:
2664   case X86ISD::MOVDDUP:
2665   case X86ISD::MOVSS:
2666   case X86ISD::MOVSD:
2667   case X86ISD::UNPCKLPS:
2668   case X86ISD::UNPCKLPD:
2669   case X86ISD::PUNPCKLWD:
2670   case X86ISD::PUNPCKLBW:
2671   case X86ISD::PUNPCKLDQ:
2672   case X86ISD::PUNPCKLQDQ:
2673   case X86ISD::UNPCKHPS:
2674   case X86ISD::UNPCKHPD:
2675   case X86ISD::PUNPCKHWD:
2676   case X86ISD::PUNPCKHBW:
2677   case X86ISD::PUNPCKHDQ:
2678   case X86ISD::PUNPCKHQDQ:
2679     return true;
2680   }
2681   return false;
2682 }
2683
2684 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2685                                                SDValue V1, SelectionDAG &DAG) {
2686   switch(Opc) {
2687   default: llvm_unreachable("Unknown x86 shuffle node");
2688   case X86ISD::MOVSHDUP:
2689   case X86ISD::MOVSLDUP:
2690   case X86ISD::MOVDDUP:
2691     return DAG.getNode(Opc, dl, VT, V1);
2692   }
2693
2694   return SDValue();
2695 }
2696
2697 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2698                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2699   switch(Opc) {
2700   default: llvm_unreachable("Unknown x86 shuffle node");
2701   case X86ISD::PSHUFD:
2702   case X86ISD::PSHUFHW:
2703   case X86ISD::PSHUFLW:
2704     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2705   }
2706
2707   return SDValue();
2708 }
2709
2710 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2711                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2712   switch(Opc) {
2713   default: llvm_unreachable("Unknown x86 shuffle node");
2714   case X86ISD::PALIGN:
2715   case X86ISD::SHUFPD:
2716   case X86ISD::SHUFPS:
2717     return DAG.getNode(Opc, dl, VT, V1, V2,
2718                        DAG.getConstant(TargetMask, MVT::i8));
2719   }
2720   return SDValue();
2721 }
2722
2723 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2724                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2725   switch(Opc) {
2726   default: llvm_unreachable("Unknown x86 shuffle node");
2727   case X86ISD::MOVLHPS:
2728   case X86ISD::MOVLHPD:
2729   case X86ISD::MOVHLPS:
2730   case X86ISD::MOVLPS:
2731   case X86ISD::MOVLPD:
2732   case X86ISD::MOVSS:
2733   case X86ISD::MOVSD:
2734   case X86ISD::UNPCKLPS:
2735   case X86ISD::UNPCKLPD:
2736   case X86ISD::PUNPCKLWD:
2737   case X86ISD::PUNPCKLBW:
2738   case X86ISD::PUNPCKLDQ:
2739   case X86ISD::PUNPCKLQDQ:
2740   case X86ISD::UNPCKHPS:
2741   case X86ISD::UNPCKHPD:
2742   case X86ISD::PUNPCKHWD:
2743   case X86ISD::PUNPCKHBW:
2744   case X86ISD::PUNPCKHDQ:
2745   case X86ISD::PUNPCKHQDQ:
2746     return DAG.getNode(Opc, dl, VT, V1, V2);
2747   }
2748   return SDValue();
2749 }
2750
2751 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2752   MachineFunction &MF = DAG.getMachineFunction();
2753   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2754   int ReturnAddrIndex = FuncInfo->getRAIndex();
2755
2756   if (ReturnAddrIndex == 0) {
2757     // Set up a frame object for the return address.
2758     uint64_t SlotSize = TD->getPointerSize();
2759     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2760                                                            false);
2761     FuncInfo->setRAIndex(ReturnAddrIndex);
2762   }
2763
2764   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2765 }
2766
2767
2768 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2769                                        bool hasSymbolicDisplacement) {
2770   // Offset should fit into 32 bit immediate field.
2771   if (!isInt<32>(Offset))
2772     return false;
2773
2774   // If we don't have a symbolic displacement - we don't have any extra
2775   // restrictions.
2776   if (!hasSymbolicDisplacement)
2777     return true;
2778
2779   // FIXME: Some tweaks might be needed for medium code model.
2780   if (M != CodeModel::Small && M != CodeModel::Kernel)
2781     return false;
2782
2783   // For small code model we assume that latest object is 16MB before end of 31
2784   // bits boundary. We may also accept pretty large negative constants knowing
2785   // that all objects are in the positive half of address space.
2786   if (M == CodeModel::Small && Offset < 16*1024*1024)
2787     return true;
2788
2789   // For kernel code model we know that all object resist in the negative half
2790   // of 32bits address space. We may not accept negative offsets, since they may
2791   // be just off and we may accept pretty large positive ones.
2792   if (M == CodeModel::Kernel && Offset > 0)
2793     return true;
2794
2795   return false;
2796 }
2797
2798 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2799 /// specific condition code, returning the condition code and the LHS/RHS of the
2800 /// comparison to make.
2801 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2802                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2803   if (!isFP) {
2804     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2805       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2806         // X > -1   -> X == 0, jump !sign.
2807         RHS = DAG.getConstant(0, RHS.getValueType());
2808         return X86::COND_NS;
2809       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2810         // X < 0   -> X == 0, jump on sign.
2811         return X86::COND_S;
2812       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2813         // X < 1   -> X <= 0
2814         RHS = DAG.getConstant(0, RHS.getValueType());
2815         return X86::COND_LE;
2816       }
2817     }
2818
2819     switch (SetCCOpcode) {
2820     default: llvm_unreachable("Invalid integer condition!");
2821     case ISD::SETEQ:  return X86::COND_E;
2822     case ISD::SETGT:  return X86::COND_G;
2823     case ISD::SETGE:  return X86::COND_GE;
2824     case ISD::SETLT:  return X86::COND_L;
2825     case ISD::SETLE:  return X86::COND_LE;
2826     case ISD::SETNE:  return X86::COND_NE;
2827     case ISD::SETULT: return X86::COND_B;
2828     case ISD::SETUGT: return X86::COND_A;
2829     case ISD::SETULE: return X86::COND_BE;
2830     case ISD::SETUGE: return X86::COND_AE;
2831     }
2832   }
2833
2834   // First determine if it is required or is profitable to flip the operands.
2835
2836   // If LHS is a foldable load, but RHS is not, flip the condition.
2837   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2838       !ISD::isNON_EXTLoad(RHS.getNode())) {
2839     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2840     std::swap(LHS, RHS);
2841   }
2842
2843   switch (SetCCOpcode) {
2844   default: break;
2845   case ISD::SETOLT:
2846   case ISD::SETOLE:
2847   case ISD::SETUGT:
2848   case ISD::SETUGE:
2849     std::swap(LHS, RHS);
2850     break;
2851   }
2852
2853   // On a floating point condition, the flags are set as follows:
2854   // ZF  PF  CF   op
2855   //  0 | 0 | 0 | X > Y
2856   //  0 | 0 | 1 | X < Y
2857   //  1 | 0 | 0 | X == Y
2858   //  1 | 1 | 1 | unordered
2859   switch (SetCCOpcode) {
2860   default: llvm_unreachable("Condcode should be pre-legalized away");
2861   case ISD::SETUEQ:
2862   case ISD::SETEQ:   return X86::COND_E;
2863   case ISD::SETOLT:              // flipped
2864   case ISD::SETOGT:
2865   case ISD::SETGT:   return X86::COND_A;
2866   case ISD::SETOLE:              // flipped
2867   case ISD::SETOGE:
2868   case ISD::SETGE:   return X86::COND_AE;
2869   case ISD::SETUGT:              // flipped
2870   case ISD::SETULT:
2871   case ISD::SETLT:   return X86::COND_B;
2872   case ISD::SETUGE:              // flipped
2873   case ISD::SETULE:
2874   case ISD::SETLE:   return X86::COND_BE;
2875   case ISD::SETONE:
2876   case ISD::SETNE:   return X86::COND_NE;
2877   case ISD::SETUO:   return X86::COND_P;
2878   case ISD::SETO:    return X86::COND_NP;
2879   case ISD::SETOEQ:
2880   case ISD::SETUNE:  return X86::COND_INVALID;
2881   }
2882 }
2883
2884 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2885 /// code. Current x86 isa includes the following FP cmov instructions:
2886 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2887 static bool hasFPCMov(unsigned X86CC) {
2888   switch (X86CC) {
2889   default:
2890     return false;
2891   case X86::COND_B:
2892   case X86::COND_BE:
2893   case X86::COND_E:
2894   case X86::COND_P:
2895   case X86::COND_A:
2896   case X86::COND_AE:
2897   case X86::COND_NE:
2898   case X86::COND_NP:
2899     return true;
2900   }
2901 }
2902
2903 /// isFPImmLegal - Returns true if the target can instruction select the
2904 /// specified FP immediate natively. If false, the legalizer will
2905 /// materialize the FP immediate as a load from a constant pool.
2906 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2907   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2908     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2909       return true;
2910   }
2911   return false;
2912 }
2913
2914 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2915 /// the specified range (L, H].
2916 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2917   return (Val < 0) || (Val >= Low && Val < Hi);
2918 }
2919
2920 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2921 /// specified value.
2922 static bool isUndefOrEqual(int Val, int CmpVal) {
2923   if (Val < 0 || Val == CmpVal)
2924     return true;
2925   return false;
2926 }
2927
2928 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2929 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2930 /// the second operand.
2931 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2932   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2933     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2934   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2935     return (Mask[0] < 2 && Mask[1] < 2);
2936   return false;
2937 }
2938
2939 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2940   SmallVector<int, 8> M;
2941   N->getMask(M);
2942   return ::isPSHUFDMask(M, N->getValueType(0));
2943 }
2944
2945 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2946 /// is suitable for input to PSHUFHW.
2947 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2948   if (VT != MVT::v8i16)
2949     return false;
2950
2951   // Lower quadword copied in order or undef.
2952   for (int i = 0; i != 4; ++i)
2953     if (Mask[i] >= 0 && Mask[i] != i)
2954       return false;
2955
2956   // Upper quadword shuffled.
2957   for (int i = 4; i != 8; ++i)
2958     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2959       return false;
2960
2961   return true;
2962 }
2963
2964 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2965   SmallVector<int, 8> M;
2966   N->getMask(M);
2967   return ::isPSHUFHWMask(M, N->getValueType(0));
2968 }
2969
2970 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2971 /// is suitable for input to PSHUFLW.
2972 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2973   if (VT != MVT::v8i16)
2974     return false;
2975
2976   // Upper quadword copied in order.
2977   for (int i = 4; i != 8; ++i)
2978     if (Mask[i] >= 0 && Mask[i] != i)
2979       return false;
2980
2981   // Lower quadword shuffled.
2982   for (int i = 0; i != 4; ++i)
2983     if (Mask[i] >= 4)
2984       return false;
2985
2986   return true;
2987 }
2988
2989 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2990   SmallVector<int, 8> M;
2991   N->getMask(M);
2992   return ::isPSHUFLWMask(M, N->getValueType(0));
2993 }
2994
2995 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2996 /// is suitable for input to PALIGNR.
2997 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2998                           bool hasSSSE3) {
2999   int i, e = VT.getVectorNumElements();
3000
3001   // Do not handle v2i64 / v2f64 shuffles with palignr.
3002   if (e < 4 || !hasSSSE3)
3003     return false;
3004
3005   for (i = 0; i != e; ++i)
3006     if (Mask[i] >= 0)
3007       break;
3008
3009   // All undef, not a palignr.
3010   if (i == e)
3011     return false;
3012
3013   // Determine if it's ok to perform a palignr with only the LHS, since we
3014   // don't have access to the actual shuffle elements to see if RHS is undef.
3015   bool Unary = Mask[i] < (int)e;
3016   bool NeedsUnary = false;
3017
3018   int s = Mask[i] - i;
3019
3020   // Check the rest of the elements to see if they are consecutive.
3021   for (++i; i != e; ++i) {
3022     int m = Mask[i];
3023     if (m < 0)
3024       continue;
3025
3026     Unary = Unary && (m < (int)e);
3027     NeedsUnary = NeedsUnary || (m < s);
3028
3029     if (NeedsUnary && !Unary)
3030       return false;
3031     if (Unary && m != ((s+i) & (e-1)))
3032       return false;
3033     if (!Unary && m != (s+i))
3034       return false;
3035   }
3036   return true;
3037 }
3038
3039 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3040   SmallVector<int, 8> M;
3041   N->getMask(M);
3042   return ::isPALIGNRMask(M, N->getValueType(0), true);
3043 }
3044
3045 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3046 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3047 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3048   int NumElems = VT.getVectorNumElements();
3049   if (NumElems != 2 && NumElems != 4)
3050     return false;
3051
3052   int Half = NumElems / 2;
3053   for (int i = 0; i < Half; ++i)
3054     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3055       return false;
3056   for (int i = Half; i < NumElems; ++i)
3057     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3058       return false;
3059
3060   return true;
3061 }
3062
3063 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3064   SmallVector<int, 8> M;
3065   N->getMask(M);
3066   return ::isSHUFPMask(M, N->getValueType(0));
3067 }
3068
3069 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3070 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3071 /// half elements to come from vector 1 (which would equal the dest.) and
3072 /// the upper half to come from vector 2.
3073 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3074   int NumElems = VT.getVectorNumElements();
3075
3076   if (NumElems != 2 && NumElems != 4)
3077     return false;
3078
3079   int Half = NumElems / 2;
3080   for (int i = 0; i < Half; ++i)
3081     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3082       return false;
3083   for (int i = Half; i < NumElems; ++i)
3084     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3085       return false;
3086   return true;
3087 }
3088
3089 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3090   SmallVector<int, 8> M;
3091   N->getMask(M);
3092   return isCommutedSHUFPMask(M, N->getValueType(0));
3093 }
3094
3095 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3096 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3097 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3098   if (N->getValueType(0).getVectorNumElements() != 4)
3099     return false;
3100
3101   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3102   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3103          isUndefOrEqual(N->getMaskElt(1), 7) &&
3104          isUndefOrEqual(N->getMaskElt(2), 2) &&
3105          isUndefOrEqual(N->getMaskElt(3), 3);
3106 }
3107
3108 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3109 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3110 /// <2, 3, 2, 3>
3111 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3112   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3113
3114   if (NumElems != 4)
3115     return false;
3116
3117   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3118   isUndefOrEqual(N->getMaskElt(1), 3) &&
3119   isUndefOrEqual(N->getMaskElt(2), 2) &&
3120   isUndefOrEqual(N->getMaskElt(3), 3);
3121 }
3122
3123 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3124 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3125 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3126   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3127
3128   if (NumElems != 2 && NumElems != 4)
3129     return false;
3130
3131   for (unsigned i = 0; i < NumElems/2; ++i)
3132     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3133       return false;
3134
3135   for (unsigned i = NumElems/2; i < NumElems; ++i)
3136     if (!isUndefOrEqual(N->getMaskElt(i), i))
3137       return false;
3138
3139   return true;
3140 }
3141
3142 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3143 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3144 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3145   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3146
3147   if (NumElems != 2 && NumElems != 4)
3148     return false;
3149
3150   for (unsigned i = 0; i < NumElems/2; ++i)
3151     if (!isUndefOrEqual(N->getMaskElt(i), i))
3152       return false;
3153
3154   for (unsigned i = 0; i < NumElems/2; ++i)
3155     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3156       return false;
3157
3158   return true;
3159 }
3160
3161 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3162 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3163 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3164                          bool V2IsSplat = false) {
3165   int NumElts = VT.getVectorNumElements();
3166   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3167     return false;
3168
3169   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3170     int BitI  = Mask[i];
3171     int BitI1 = Mask[i+1];
3172     if (!isUndefOrEqual(BitI, j))
3173       return false;
3174     if (V2IsSplat) {
3175       if (!isUndefOrEqual(BitI1, NumElts))
3176         return false;
3177     } else {
3178       if (!isUndefOrEqual(BitI1, j + NumElts))
3179         return false;
3180     }
3181   }
3182   return true;
3183 }
3184
3185 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3186   SmallVector<int, 8> M;
3187   N->getMask(M);
3188   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3189 }
3190
3191 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3192 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3193 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3194                          bool V2IsSplat = false) {
3195   int NumElts = VT.getVectorNumElements();
3196   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3197     return false;
3198
3199   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3200     int BitI  = Mask[i];
3201     int BitI1 = Mask[i+1];
3202     if (!isUndefOrEqual(BitI, j + NumElts/2))
3203       return false;
3204     if (V2IsSplat) {
3205       if (isUndefOrEqual(BitI1, NumElts))
3206         return false;
3207     } else {
3208       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3209         return false;
3210     }
3211   }
3212   return true;
3213 }
3214
3215 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3216   SmallVector<int, 8> M;
3217   N->getMask(M);
3218   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3219 }
3220
3221 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3222 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3223 /// <0, 0, 1, 1>
3224 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3225   int NumElems = VT.getVectorNumElements();
3226   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3227     return false;
3228
3229   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3230     int BitI  = Mask[i];
3231     int BitI1 = Mask[i+1];
3232     if (!isUndefOrEqual(BitI, j))
3233       return false;
3234     if (!isUndefOrEqual(BitI1, j))
3235       return false;
3236   }
3237   return true;
3238 }
3239
3240 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3241   SmallVector<int, 8> M;
3242   N->getMask(M);
3243   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3244 }
3245
3246 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3247 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3248 /// <2, 2, 3, 3>
3249 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3250   int NumElems = VT.getVectorNumElements();
3251   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3252     return false;
3253
3254   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3255     int BitI  = Mask[i];
3256     int BitI1 = Mask[i+1];
3257     if (!isUndefOrEqual(BitI, j))
3258       return false;
3259     if (!isUndefOrEqual(BitI1, j))
3260       return false;
3261   }
3262   return true;
3263 }
3264
3265 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3266   SmallVector<int, 8> M;
3267   N->getMask(M);
3268   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3269 }
3270
3271 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3273 /// MOVSD, and MOVD, i.e. setting the lowest element.
3274 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3275   if (VT.getVectorElementType().getSizeInBits() < 32)
3276     return false;
3277
3278   int NumElts = VT.getVectorNumElements();
3279
3280   if (!isUndefOrEqual(Mask[0], NumElts))
3281     return false;
3282
3283   for (int i = 1; i < NumElts; ++i)
3284     if (!isUndefOrEqual(Mask[i], i))
3285       return false;
3286
3287   return true;
3288 }
3289
3290 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3291   SmallVector<int, 8> M;
3292   N->getMask(M);
3293   return ::isMOVLMask(M, N->getValueType(0));
3294 }
3295
3296 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3297 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3298 /// element of vector 2 and the other elements to come from vector 1 in order.
3299 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3300                                bool V2IsSplat = false, bool V2IsUndef = false) {
3301   int NumOps = VT.getVectorNumElements();
3302   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3303     return false;
3304
3305   if (!isUndefOrEqual(Mask[0], 0))
3306     return false;
3307
3308   for (int i = 1; i < NumOps; ++i)
3309     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3310           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3311           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3312       return false;
3313
3314   return true;
3315 }
3316
3317 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3318                            bool V2IsUndef = false) {
3319   SmallVector<int, 8> M;
3320   N->getMask(M);
3321   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3322 }
3323
3324 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3325 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3326 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3327   if (N->getValueType(0).getVectorNumElements() != 4)
3328     return false;
3329
3330   // Expect 1, 1, 3, 3
3331   for (unsigned i = 0; i < 2; ++i) {
3332     int Elt = N->getMaskElt(i);
3333     if (Elt >= 0 && Elt != 1)
3334       return false;
3335   }
3336
3337   bool HasHi = false;
3338   for (unsigned i = 2; i < 4; ++i) {
3339     int Elt = N->getMaskElt(i);
3340     if (Elt >= 0 && Elt != 3)
3341       return false;
3342     if (Elt == 3)
3343       HasHi = true;
3344   }
3345   // Don't use movshdup if it can be done with a shufps.
3346   // FIXME: verify that matching u, u, 3, 3 is what we want.
3347   return HasHi;
3348 }
3349
3350 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3351 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3352 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3353   if (N->getValueType(0).getVectorNumElements() != 4)
3354     return false;
3355
3356   // Expect 0, 0, 2, 2
3357   for (unsigned i = 0; i < 2; ++i)
3358     if (N->getMaskElt(i) > 0)
3359       return false;
3360
3361   bool HasHi = false;
3362   for (unsigned i = 2; i < 4; ++i) {
3363     int Elt = N->getMaskElt(i);
3364     if (Elt >= 0 && Elt != 2)
3365       return false;
3366     if (Elt == 2)
3367       HasHi = true;
3368   }
3369   // Don't use movsldup if it can be done with a shufps.
3370   return HasHi;
3371 }
3372
3373 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3374 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3375 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3376   int e = N->getValueType(0).getVectorNumElements() / 2;
3377
3378   for (int i = 0; i < e; ++i)
3379     if (!isUndefOrEqual(N->getMaskElt(i), i))
3380       return false;
3381   for (int i = 0; i < e; ++i)
3382     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3383       return false;
3384   return true;
3385 }
3386
3387 /// isVEXTRACTF128Index - Return true if the specified
3388 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3389 /// suitable for input to VEXTRACTF128.
3390 bool X86::isVEXTRACTF128Index(SDNode *N) {
3391   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3392     return false;
3393
3394   // The index should be aligned on a 128-bit boundary.
3395   uint64_t Index =
3396     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3397
3398   unsigned VL = N->getValueType(0).getVectorNumElements();
3399   unsigned VBits = N->getValueType(0).getSizeInBits();
3400   unsigned ElSize = VBits / VL;
3401   bool Result = (Index * ElSize) % 128 == 0;
3402
3403   return Result;
3404 }
3405
3406 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3407 /// operand specifies a subvector insert that is suitable for input to
3408 /// VINSERTF128.
3409 bool X86::isVINSERTF128Index(SDNode *N) {
3410   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3411     return false;
3412
3413   // The index should be aligned on a 128-bit boundary.
3414   uint64_t Index =
3415     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3416
3417   unsigned VL = N->getValueType(0).getVectorNumElements();
3418   unsigned VBits = N->getValueType(0).getSizeInBits();
3419   unsigned ElSize = VBits / VL;
3420   bool Result = (Index * ElSize) % 128 == 0;
3421
3422   return Result;
3423 }
3424
3425 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3426 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3427 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3428   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3429   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3430
3431   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3432   unsigned Mask = 0;
3433   for (int i = 0; i < NumOperands; ++i) {
3434     int Val = SVOp->getMaskElt(NumOperands-i-1);
3435     if (Val < 0) Val = 0;
3436     if (Val >= NumOperands) Val -= NumOperands;
3437     Mask |= Val;
3438     if (i != NumOperands - 1)
3439       Mask <<= Shift;
3440   }
3441   return Mask;
3442 }
3443
3444 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3445 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3446 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3447   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3448   unsigned Mask = 0;
3449   // 8 nodes, but we only care about the last 4.
3450   for (unsigned i = 7; i >= 4; --i) {
3451     int Val = SVOp->getMaskElt(i);
3452     if (Val >= 0)
3453       Mask |= (Val - 4);
3454     if (i != 4)
3455       Mask <<= 2;
3456   }
3457   return Mask;
3458 }
3459
3460 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3461 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3462 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3463   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3464   unsigned Mask = 0;
3465   // 8 nodes, but we only care about the first 4.
3466   for (int i = 3; i >= 0; --i) {
3467     int Val = SVOp->getMaskElt(i);
3468     if (Val >= 0)
3469       Mask |= Val;
3470     if (i != 0)
3471       Mask <<= 2;
3472   }
3473   return Mask;
3474 }
3475
3476 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3477 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3478 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3479   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3480   EVT VVT = N->getValueType(0);
3481   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3482   int Val = 0;
3483
3484   unsigned i, e;
3485   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3486     Val = SVOp->getMaskElt(i);
3487     if (Val >= 0)
3488       break;
3489   }
3490   return (Val - i) * EltSize;
3491 }
3492
3493 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3494 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3495 /// instructions.
3496 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3497   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3498     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3499
3500   uint64_t Index =
3501     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3502
3503   EVT VecVT = N->getOperand(0).getValueType();
3504   EVT ElVT = VecVT.getVectorElementType();
3505
3506   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3507
3508   return Index / NumElemsPerChunk;
3509 }
3510
3511 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3512 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3513 /// instructions.
3514 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3515   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3516     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3517
3518   uint64_t Index =
3519     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();  
3520
3521   EVT VecVT = N->getValueType(0);
3522   EVT ElVT = VecVT.getVectorElementType();
3523
3524   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3525
3526   return Index / NumElemsPerChunk;
3527 }
3528
3529 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3530 /// constant +0.0.
3531 bool X86::isZeroNode(SDValue Elt) {
3532   return ((isa<ConstantSDNode>(Elt) &&
3533            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3534           (isa<ConstantFPSDNode>(Elt) &&
3535            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3536 }
3537
3538 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3539 /// their permute mask.
3540 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3541                                     SelectionDAG &DAG) {
3542   EVT VT = SVOp->getValueType(0);
3543   unsigned NumElems = VT.getVectorNumElements();
3544   SmallVector<int, 8> MaskVec;
3545
3546   for (unsigned i = 0; i != NumElems; ++i) {
3547     int idx = SVOp->getMaskElt(i);
3548     if (idx < 0)
3549       MaskVec.push_back(idx);
3550     else if (idx < (int)NumElems)
3551       MaskVec.push_back(idx + NumElems);
3552     else
3553       MaskVec.push_back(idx - NumElems);
3554   }
3555   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3556                               SVOp->getOperand(0), &MaskVec[0]);
3557 }
3558
3559 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3560 /// the two vector operands have swapped position.
3561 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3562   unsigned NumElems = VT.getVectorNumElements();
3563   for (unsigned i = 0; i != NumElems; ++i) {
3564     int idx = Mask[i];
3565     if (idx < 0)
3566       continue;
3567     else if (idx < (int)NumElems)
3568       Mask[i] = idx + NumElems;
3569     else
3570       Mask[i] = idx - NumElems;
3571   }
3572 }
3573
3574 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3575 /// match movhlps. The lower half elements should come from upper half of
3576 /// V1 (and in order), and the upper half elements should come from the upper
3577 /// half of V2 (and in order).
3578 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3579   if (Op->getValueType(0).getVectorNumElements() != 4)
3580     return false;
3581   for (unsigned i = 0, e = 2; i != e; ++i)
3582     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3583       return false;
3584   for (unsigned i = 2; i != 4; ++i)
3585     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3586       return false;
3587   return true;
3588 }
3589
3590 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3591 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3592 /// required.
3593 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3594   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3595     return false;
3596   N = N->getOperand(0).getNode();
3597   if (!ISD::isNON_EXTLoad(N))
3598     return false;
3599   if (LD)
3600     *LD = cast<LoadSDNode>(N);
3601   return true;
3602 }
3603
3604 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3605 /// match movlp{s|d}. The lower half elements should come from lower half of
3606 /// V1 (and in order), and the upper half elements should come from the upper
3607 /// half of V2 (and in order). And since V1 will become the source of the
3608 /// MOVLP, it must be either a vector load or a scalar load to vector.
3609 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3610                                ShuffleVectorSDNode *Op) {
3611   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3612     return false;
3613   // Is V2 is a vector load, don't do this transformation. We will try to use
3614   // load folding shufps op.
3615   if (ISD::isNON_EXTLoad(V2))
3616     return false;
3617
3618   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3619
3620   if (NumElems != 2 && NumElems != 4)
3621     return false;
3622   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3623     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3624       return false;
3625   for (unsigned i = NumElems/2; i != NumElems; ++i)
3626     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3627       return false;
3628   return true;
3629 }
3630
3631 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3632 /// all the same.
3633 static bool isSplatVector(SDNode *N) {
3634   if (N->getOpcode() != ISD::BUILD_VECTOR)
3635     return false;
3636
3637   SDValue SplatValue = N->getOperand(0);
3638   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3639     if (N->getOperand(i) != SplatValue)
3640       return false;
3641   return true;
3642 }
3643
3644 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3645 /// to an zero vector.
3646 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3647 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3648   SDValue V1 = N->getOperand(0);
3649   SDValue V2 = N->getOperand(1);
3650   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3651   for (unsigned i = 0; i != NumElems; ++i) {
3652     int Idx = N->getMaskElt(i);
3653     if (Idx >= (int)NumElems) {
3654       unsigned Opc = V2.getOpcode();
3655       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3656         continue;
3657       if (Opc != ISD::BUILD_VECTOR ||
3658           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3659         return false;
3660     } else if (Idx >= 0) {
3661       unsigned Opc = V1.getOpcode();
3662       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3663         continue;
3664       if (Opc != ISD::BUILD_VECTOR ||
3665           !X86::isZeroNode(V1.getOperand(Idx)))
3666         return false;
3667     }
3668   }
3669   return true;
3670 }
3671
3672 /// getZeroVector - Returns a vector of specified type with all zero elements.
3673 ///
3674 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3675                              DebugLoc dl) {
3676   assert(VT.isVector() && "Expected a vector type");
3677
3678   // Always build SSE zero vectors as <4 x i32> bitcasted
3679   // to their dest type. This ensures they get CSE'd.
3680   SDValue Vec;
3681   if (VT.getSizeInBits() == 128) {  // SSE
3682     if (HasSSE2) {  // SSE2
3683       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3684       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3685     } else { // SSE1
3686       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3688     }
3689   } else if (VT.getSizeInBits() == 256) { // AVX
3690     // 256-bit logic and arithmetic instructions in AVX are
3691     // all floating-point, no support for integer ops. Default
3692     // to emitting fp zeroed vectors then.
3693     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3694     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3695     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3696   }
3697   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3698 }
3699
3700 /// getOnesVector - Returns a vector of specified type with all bits set.
3701 ///
3702 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3703   assert(VT.isVector() && "Expected a vector type");
3704
3705   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3706   // type.  This ensures they get CSE'd.
3707   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3708   SDValue Vec;
3709   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3710   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3711 }
3712
3713
3714 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3715 /// that point to V2 points to its first element.
3716 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3717   EVT VT = SVOp->getValueType(0);
3718   unsigned NumElems = VT.getVectorNumElements();
3719
3720   bool Changed = false;
3721   SmallVector<int, 8> MaskVec;
3722   SVOp->getMask(MaskVec);
3723
3724   for (unsigned i = 0; i != NumElems; ++i) {
3725     if (MaskVec[i] > (int)NumElems) {
3726       MaskVec[i] = NumElems;
3727       Changed = true;
3728     }
3729   }
3730   if (Changed)
3731     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3732                                 SVOp->getOperand(1), &MaskVec[0]);
3733   return SDValue(SVOp, 0);
3734 }
3735
3736 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3737 /// operation of specified width.
3738 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3739                        SDValue V2) {
3740   unsigned NumElems = VT.getVectorNumElements();
3741   SmallVector<int, 8> Mask;
3742   Mask.push_back(NumElems);
3743   for (unsigned i = 1; i != NumElems; ++i)
3744     Mask.push_back(i);
3745   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3746 }
3747
3748 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3749 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3750                           SDValue V2) {
3751   unsigned NumElems = VT.getVectorNumElements();
3752   SmallVector<int, 8> Mask;
3753   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3754     Mask.push_back(i);
3755     Mask.push_back(i + NumElems);
3756   }
3757   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3758 }
3759
3760 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3761 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3762                           SDValue V2) {
3763   unsigned NumElems = VT.getVectorNumElements();
3764   unsigned Half = NumElems/2;
3765   SmallVector<int, 8> Mask;
3766   for (unsigned i = 0; i != Half; ++i) {
3767     Mask.push_back(i + Half);
3768     Mask.push_back(i + NumElems + Half);
3769   }
3770   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3771 }
3772
3773 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3774 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3775   EVT PVT = MVT::v4f32;
3776   EVT VT = SV->getValueType(0);
3777   DebugLoc dl = SV->getDebugLoc();
3778   SDValue V1 = SV->getOperand(0);
3779   int NumElems = VT.getVectorNumElements();
3780   int EltNo = SV->getSplatIndex();
3781
3782   // unpack elements to the correct location
3783   while (NumElems > 4) {
3784     if (EltNo < NumElems/2) {
3785       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3786     } else {
3787       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3788       EltNo -= NumElems/2;
3789     }
3790     NumElems >>= 1;
3791   }
3792
3793   // Perform the splat.
3794   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3795   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3796   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3797   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3798 }
3799
3800 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3801 /// vector of zero or undef vector.  This produces a shuffle where the low
3802 /// element of V2 is swizzled into the zero/undef vector, landing at element
3803 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3804 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3805                                              bool isZero, bool HasSSE2,
3806                                              SelectionDAG &DAG) {
3807   EVT VT = V2.getValueType();
3808   SDValue V1 = isZero
3809     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3810   unsigned NumElems = VT.getVectorNumElements();
3811   SmallVector<int, 16> MaskVec;
3812   for (unsigned i = 0; i != NumElems; ++i)
3813     // If this is the insertion idx, put the low elt of V2 here.
3814     MaskVec.push_back(i == Idx ? NumElems : i);
3815   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3816 }
3817
3818 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3819 /// element of the result of the vector shuffle.
3820 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3821                             unsigned Depth) {
3822   if (Depth == 6)
3823     return SDValue();  // Limit search depth.
3824
3825   SDValue V = SDValue(N, 0);
3826   EVT VT = V.getValueType();
3827   unsigned Opcode = V.getOpcode();
3828
3829   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3830   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3831     Index = SV->getMaskElt(Index);
3832
3833     if (Index < 0)
3834       return DAG.getUNDEF(VT.getVectorElementType());
3835
3836     int NumElems = VT.getVectorNumElements();
3837     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3838     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3839   }
3840
3841   // Recurse into target specific vector shuffles to find scalars.
3842   if (isTargetShuffle(Opcode)) {
3843     int NumElems = VT.getVectorNumElements();
3844     SmallVector<unsigned, 16> ShuffleMask;
3845     SDValue ImmN;
3846
3847     switch(Opcode) {
3848     case X86ISD::SHUFPS:
3849     case X86ISD::SHUFPD:
3850       ImmN = N->getOperand(N->getNumOperands()-1);
3851       DecodeSHUFPSMask(NumElems,
3852                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3853                        ShuffleMask);
3854       break;
3855     case X86ISD::PUNPCKHBW:
3856     case X86ISD::PUNPCKHWD:
3857     case X86ISD::PUNPCKHDQ:
3858     case X86ISD::PUNPCKHQDQ:
3859       DecodePUNPCKHMask(NumElems, ShuffleMask);
3860       break;
3861     case X86ISD::UNPCKHPS:
3862     case X86ISD::UNPCKHPD:
3863       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3864       break;
3865     case X86ISD::PUNPCKLBW:
3866     case X86ISD::PUNPCKLWD:
3867     case X86ISD::PUNPCKLDQ:
3868     case X86ISD::PUNPCKLQDQ:
3869       DecodePUNPCKLMask(NumElems, ShuffleMask);
3870       break;
3871     case X86ISD::UNPCKLPS:
3872     case X86ISD::UNPCKLPD:
3873       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3874       break;
3875     case X86ISD::MOVHLPS:
3876       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3877       break;
3878     case X86ISD::MOVLHPS:
3879       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3880       break;
3881     case X86ISD::PSHUFD:
3882       ImmN = N->getOperand(N->getNumOperands()-1);
3883       DecodePSHUFMask(NumElems,
3884                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3885                       ShuffleMask);
3886       break;
3887     case X86ISD::PSHUFHW:
3888       ImmN = N->getOperand(N->getNumOperands()-1);
3889       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3890                         ShuffleMask);
3891       break;
3892     case X86ISD::PSHUFLW:
3893       ImmN = N->getOperand(N->getNumOperands()-1);
3894       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3895                         ShuffleMask);
3896       break;
3897     case X86ISD::MOVSS:
3898     case X86ISD::MOVSD: {
3899       // The index 0 always comes from the first element of the second source,
3900       // this is why MOVSS and MOVSD are used in the first place. The other
3901       // elements come from the other positions of the first source vector.
3902       unsigned OpNum = (Index == 0) ? 1 : 0;
3903       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3904                                  Depth+1);
3905     }
3906     default:
3907       assert("not implemented for target shuffle node");
3908       return SDValue();
3909     }
3910
3911     Index = ShuffleMask[Index];
3912     if (Index < 0)
3913       return DAG.getUNDEF(VT.getVectorElementType());
3914
3915     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3916     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3917                                Depth+1);
3918   }
3919
3920   // Actual nodes that may contain scalar elements
3921   if (Opcode == ISD::BITCAST) {
3922     V = V.getOperand(0);
3923     EVT SrcVT = V.getValueType();
3924     unsigned NumElems = VT.getVectorNumElements();
3925
3926     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3927       return SDValue();
3928   }
3929
3930   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3931     return (Index == 0) ? V.getOperand(0)
3932                           : DAG.getUNDEF(VT.getVectorElementType());
3933
3934   if (V.getOpcode() == ISD::BUILD_VECTOR)
3935     return V.getOperand(Index);
3936
3937   return SDValue();
3938 }
3939
3940 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3941 /// shuffle operation which come from a consecutively from a zero. The
3942 /// search can start in two diferent directions, from left or right.
3943 static
3944 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3945                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3946   int i = 0;
3947
3948   while (i < NumElems) {
3949     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3950     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3951     if (!(Elt.getNode() &&
3952          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3953       break;
3954     ++i;
3955   }
3956
3957   return i;
3958 }
3959
3960 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3961 /// MaskE correspond consecutively to elements from one of the vector operands,
3962 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3963 static
3964 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3965                               int OpIdx, int NumElems, unsigned &OpNum) {
3966   bool SeenV1 = false;
3967   bool SeenV2 = false;
3968
3969   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3970     int Idx = SVOp->getMaskElt(i);
3971     // Ignore undef indicies
3972     if (Idx < 0)
3973       continue;
3974
3975     if (Idx < NumElems)
3976       SeenV1 = true;
3977     else
3978       SeenV2 = true;
3979
3980     // Only accept consecutive elements from the same vector
3981     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3982       return false;
3983   }
3984
3985   OpNum = SeenV1 ? 0 : 1;
3986   return true;
3987 }
3988
3989 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3990 /// logical left shift of a vector.
3991 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3992                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3993   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3994   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3995               false /* check zeros from right */, DAG);
3996   unsigned OpSrc;
3997
3998   if (!NumZeros)
3999     return false;
4000
4001   // Considering the elements in the mask that are not consecutive zeros,
4002   // check if they consecutively come from only one of the source vectors.
4003   //
4004   //               V1 = {X, A, B, C}     0
4005   //                         \  \  \    /
4006   //   vector_shuffle V1, V2 <1, 2, 3, X>
4007   //
4008   if (!isShuffleMaskConsecutive(SVOp,
4009             0,                   // Mask Start Index
4010             NumElems-NumZeros-1, // Mask End Index
4011             NumZeros,            // Where to start looking in the src vector
4012             NumElems,            // Number of elements in vector
4013             OpSrc))              // Which source operand ?
4014     return false;
4015
4016   isLeft = false;
4017   ShAmt = NumZeros;
4018   ShVal = SVOp->getOperand(OpSrc);
4019   return true;
4020 }
4021
4022 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4023 /// logical left shift of a vector.
4024 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4025                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4026   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4027   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4028               true /* check zeros from left */, DAG);
4029   unsigned OpSrc;
4030
4031   if (!NumZeros)
4032     return false;
4033
4034   // Considering the elements in the mask that are not consecutive zeros,
4035   // check if they consecutively come from only one of the source vectors.
4036   //
4037   //                           0    { A, B, X, X } = V2
4038   //                          / \    /  /
4039   //   vector_shuffle V1, V2 <X, X, 4, 5>
4040   //
4041   if (!isShuffleMaskConsecutive(SVOp,
4042             NumZeros,     // Mask Start Index
4043             NumElems-1,   // Mask End Index
4044             0,            // Where to start looking in the src vector
4045             NumElems,     // Number of elements in vector
4046             OpSrc))       // Which source operand ?
4047     return false;
4048
4049   isLeft = true;
4050   ShAmt = NumZeros;
4051   ShVal = SVOp->getOperand(OpSrc);
4052   return true;
4053 }
4054
4055 /// isVectorShift - Returns true if the shuffle can be implemented as a
4056 /// logical left or right shift of a vector.
4057 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4058                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4059   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4060       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4061     return true;
4062
4063   return false;
4064 }
4065
4066 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4067 ///
4068 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4069                                        unsigned NumNonZero, unsigned NumZero,
4070                                        SelectionDAG &DAG,
4071                                        const TargetLowering &TLI) {
4072   if (NumNonZero > 8)
4073     return SDValue();
4074
4075   DebugLoc dl = Op.getDebugLoc();
4076   SDValue V(0, 0);
4077   bool First = true;
4078   for (unsigned i = 0; i < 16; ++i) {
4079     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4080     if (ThisIsNonZero && First) {
4081       if (NumZero)
4082         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4083       else
4084         V = DAG.getUNDEF(MVT::v8i16);
4085       First = false;
4086     }
4087
4088     if ((i & 1) != 0) {
4089       SDValue ThisElt(0, 0), LastElt(0, 0);
4090       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4091       if (LastIsNonZero) {
4092         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4093                               MVT::i16, Op.getOperand(i-1));
4094       }
4095       if (ThisIsNonZero) {
4096         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4097         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4098                               ThisElt, DAG.getConstant(8, MVT::i8));
4099         if (LastIsNonZero)
4100           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4101       } else
4102         ThisElt = LastElt;
4103
4104       if (ThisElt.getNode())
4105         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4106                         DAG.getIntPtrConstant(i/2));
4107     }
4108   }
4109
4110   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4111 }
4112
4113 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4114 ///
4115 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4116                                      unsigned NumNonZero, unsigned NumZero,
4117                                      SelectionDAG &DAG,
4118                                      const TargetLowering &TLI) {
4119   if (NumNonZero > 4)
4120     return SDValue();
4121
4122   DebugLoc dl = Op.getDebugLoc();
4123   SDValue V(0, 0);
4124   bool First = true;
4125   for (unsigned i = 0; i < 8; ++i) {
4126     bool isNonZero = (NonZeros & (1 << i)) != 0;
4127     if (isNonZero) {
4128       if (First) {
4129         if (NumZero)
4130           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4131         else
4132           V = DAG.getUNDEF(MVT::v8i16);
4133         First = false;
4134       }
4135       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4136                       MVT::v8i16, V, Op.getOperand(i),
4137                       DAG.getIntPtrConstant(i));
4138     }
4139   }
4140
4141   return V;
4142 }
4143
4144 /// getVShift - Return a vector logical shift node.
4145 ///
4146 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4147                          unsigned NumBits, SelectionDAG &DAG,
4148                          const TargetLowering &TLI, DebugLoc dl) {
4149   EVT ShVT = MVT::v2i64;
4150   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4151   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4152   return DAG.getNode(ISD::BITCAST, dl, VT,
4153                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4154                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4155 }
4156
4157 SDValue
4158 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4159                                           SelectionDAG &DAG) const {
4160
4161   // Check if the scalar load can be widened into a vector load. And if
4162   // the address is "base + cst" see if the cst can be "absorbed" into
4163   // the shuffle mask.
4164   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4165     SDValue Ptr = LD->getBasePtr();
4166     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4167       return SDValue();
4168     EVT PVT = LD->getValueType(0);
4169     if (PVT != MVT::i32 && PVT != MVT::f32)
4170       return SDValue();
4171
4172     int FI = -1;
4173     int64_t Offset = 0;
4174     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4175       FI = FINode->getIndex();
4176       Offset = 0;
4177     } else if (Ptr.getOpcode() == ISD::ADD &&
4178                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4179                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4180       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4181       Offset = Ptr.getConstantOperandVal(1);
4182       Ptr = Ptr.getOperand(0);
4183     } else {
4184       return SDValue();
4185     }
4186
4187     SDValue Chain = LD->getChain();
4188     // Make sure the stack object alignment is at least 16.
4189     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4190     if (DAG.InferPtrAlignment(Ptr) < 16) {
4191       if (MFI->isFixedObjectIndex(FI)) {
4192         // Can't change the alignment. FIXME: It's possible to compute
4193         // the exact stack offset and reference FI + adjust offset instead.
4194         // If someone *really* cares about this. That's the way to implement it.
4195         return SDValue();
4196       } else {
4197         MFI->setObjectAlignment(FI, 16);
4198       }
4199     }
4200
4201     // (Offset % 16) must be multiple of 4. Then address is then
4202     // Ptr + (Offset & ~15).
4203     if (Offset < 0)
4204       return SDValue();
4205     if ((Offset % 16) & 3)
4206       return SDValue();
4207     int64_t StartOffset = Offset & ~15;
4208     if (StartOffset)
4209       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4210                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4211
4212     int EltNo = (Offset - StartOffset) >> 2;
4213     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4214     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4215     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4216                              LD->getPointerInfo().getWithOffset(StartOffset),
4217                              false, false, 0);
4218     // Canonicalize it to a v4i32 shuffle.
4219     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4220     return DAG.getNode(ISD::BITCAST, dl, VT,
4221                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4222                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4223   }
4224
4225   return SDValue();
4226 }
4227
4228 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4229 /// vector of type 'VT', see if the elements can be replaced by a single large
4230 /// load which has the same value as a build_vector whose operands are 'elts'.
4231 ///
4232 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4233 ///
4234 /// FIXME: we'd also like to handle the case where the last elements are zero
4235 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4236 /// There's even a handy isZeroNode for that purpose.
4237 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4238                                         DebugLoc &DL, SelectionDAG &DAG) {
4239   EVT EltVT = VT.getVectorElementType();
4240   unsigned NumElems = Elts.size();
4241
4242   LoadSDNode *LDBase = NULL;
4243   unsigned LastLoadedElt = -1U;
4244
4245   // For each element in the initializer, see if we've found a load or an undef.
4246   // If we don't find an initial load element, or later load elements are
4247   // non-consecutive, bail out.
4248   for (unsigned i = 0; i < NumElems; ++i) {
4249     SDValue Elt = Elts[i];
4250
4251     if (!Elt.getNode() ||
4252         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4253       return SDValue();
4254     if (!LDBase) {
4255       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4256         return SDValue();
4257       LDBase = cast<LoadSDNode>(Elt.getNode());
4258       LastLoadedElt = i;
4259       continue;
4260     }
4261     if (Elt.getOpcode() == ISD::UNDEF)
4262       continue;
4263
4264     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4265     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4266       return SDValue();
4267     LastLoadedElt = i;
4268   }
4269
4270   // If we have found an entire vector of loads and undefs, then return a large
4271   // load of the entire vector width starting at the base pointer.  If we found
4272   // consecutive loads for the low half, generate a vzext_load node.
4273   if (LastLoadedElt == NumElems - 1) {
4274     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4275       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4276                          LDBase->getPointerInfo(),
4277                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4278     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4279                        LDBase->getPointerInfo(),
4280                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4281                        LDBase->getAlignment());
4282   } else if (NumElems == 4 && LastLoadedElt == 1) {
4283     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4284     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4285     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4286                                               Ops, 2, MVT::i32,
4287                                               LDBase->getMemOperand());
4288     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4289   }
4290   return SDValue();
4291 }
4292
4293 SDValue
4294 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4295   DebugLoc dl = Op.getDebugLoc();
4296   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4297   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4298   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4299   // is present, so AllOnes is ignored.
4300   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4301       (Op.getValueType().getSizeInBits() != 256 &&
4302        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4303     // Canonicalize this to <4 x i32> (SSE) to
4304     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4305     // eliminated on x86-32 hosts.
4306     if (Op.getValueType() == MVT::v4i32)
4307       return Op;
4308
4309     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4310       return getOnesVector(Op.getValueType(), DAG, dl);
4311     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4312   }
4313
4314   EVT VT = Op.getValueType();
4315   EVT ExtVT = VT.getVectorElementType();
4316   unsigned EVTBits = ExtVT.getSizeInBits();
4317
4318   unsigned NumElems = Op.getNumOperands();
4319   unsigned NumZero  = 0;
4320   unsigned NumNonZero = 0;
4321   unsigned NonZeros = 0;
4322   bool IsAllConstants = true;
4323   SmallSet<SDValue, 8> Values;
4324   for (unsigned i = 0; i < NumElems; ++i) {
4325     SDValue Elt = Op.getOperand(i);
4326     if (Elt.getOpcode() == ISD::UNDEF)
4327       continue;
4328     Values.insert(Elt);
4329     if (Elt.getOpcode() != ISD::Constant &&
4330         Elt.getOpcode() != ISD::ConstantFP)
4331       IsAllConstants = false;
4332     if (X86::isZeroNode(Elt))
4333       NumZero++;
4334     else {
4335       NonZeros |= (1 << i);
4336       NumNonZero++;
4337     }
4338   }
4339
4340   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4341   if (NumNonZero == 0)
4342     return DAG.getUNDEF(VT);
4343
4344   // Special case for single non-zero, non-undef, element.
4345   if (NumNonZero == 1) {
4346     unsigned Idx = CountTrailingZeros_32(NonZeros);
4347     SDValue Item = Op.getOperand(Idx);
4348
4349     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4350     // the value are obviously zero, truncate the value to i32 and do the
4351     // insertion that way.  Only do this if the value is non-constant or if the
4352     // value is a constant being inserted into element 0.  It is cheaper to do
4353     // a constant pool load than it is to do a movd + shuffle.
4354     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4355         (!IsAllConstants || Idx == 0)) {
4356       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4357         // Handle SSE only.
4358         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4359         EVT VecVT = MVT::v4i32;
4360         unsigned VecElts = 4;
4361
4362         // Truncate the value (which may itself be a constant) to i32, and
4363         // convert it to a vector with movd (S2V+shuffle to zero extend).
4364         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4365         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4366         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4367                                            Subtarget->hasSSE2(), DAG);
4368
4369         // Now we have our 32-bit value zero extended in the low element of
4370         // a vector.  If Idx != 0, swizzle it into place.
4371         if (Idx != 0) {
4372           SmallVector<int, 4> Mask;
4373           Mask.push_back(Idx);
4374           for (unsigned i = 1; i != VecElts; ++i)
4375             Mask.push_back(i);
4376           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4377                                       DAG.getUNDEF(Item.getValueType()),
4378                                       &Mask[0]);
4379         }
4380         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4381       }
4382     }
4383
4384     // If we have a constant or non-constant insertion into the low element of
4385     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4386     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4387     // depending on what the source datatype is.
4388     if (Idx == 0) {
4389       if (NumZero == 0) {
4390         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4391       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4392           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4393         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4394         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4395         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4396                                            DAG);
4397       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4398         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4399         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4400         EVT MiddleVT = MVT::v4i32;
4401         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4402         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4403                                            Subtarget->hasSSE2(), DAG);
4404         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4405       }
4406     }
4407
4408     // Is it a vector logical left shift?
4409     if (NumElems == 2 && Idx == 1 &&
4410         X86::isZeroNode(Op.getOperand(0)) &&
4411         !X86::isZeroNode(Op.getOperand(1))) {
4412       unsigned NumBits = VT.getSizeInBits();
4413       return getVShift(true, VT,
4414                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4415                                    VT, Op.getOperand(1)),
4416                        NumBits/2, DAG, *this, dl);
4417     }
4418
4419     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4420       return SDValue();
4421
4422     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4423     // is a non-constant being inserted into an element other than the low one,
4424     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4425     // movd/movss) to move this into the low element, then shuffle it into
4426     // place.
4427     if (EVTBits == 32) {
4428       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4429
4430       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4431       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4432                                          Subtarget->hasSSE2(), DAG);
4433       SmallVector<int, 8> MaskVec;
4434       for (unsigned i = 0; i < NumElems; i++)
4435         MaskVec.push_back(i == Idx ? 0 : 1);
4436       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4437     }
4438   }
4439
4440   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4441   if (Values.size() == 1) {
4442     if (EVTBits == 32) {
4443       // Instead of a shuffle like this:
4444       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4445       // Check if it's possible to issue this instead.
4446       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4447       unsigned Idx = CountTrailingZeros_32(NonZeros);
4448       SDValue Item = Op.getOperand(Idx);
4449       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4450         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4451     }
4452     return SDValue();
4453   }
4454
4455   // A vector full of immediates; various special cases are already
4456   // handled, so this is best done with a single constant-pool load.
4457   if (IsAllConstants)
4458     return SDValue();
4459
4460   // Let legalizer expand 2-wide build_vectors.
4461   if (EVTBits == 64) {
4462     if (NumNonZero == 1) {
4463       // One half is zero or undef.
4464       unsigned Idx = CountTrailingZeros_32(NonZeros);
4465       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4466                                  Op.getOperand(Idx));
4467       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4468                                          Subtarget->hasSSE2(), DAG);
4469     }
4470     return SDValue();
4471   }
4472
4473   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4474   if (EVTBits == 8 && NumElems == 16) {
4475     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4476                                         *this);
4477     if (V.getNode()) return V;
4478   }
4479
4480   if (EVTBits == 16 && NumElems == 8) {
4481     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4482                                       *this);
4483     if (V.getNode()) return V;
4484   }
4485
4486   // If element VT is == 32 bits, turn it into a number of shuffles.
4487   SmallVector<SDValue, 8> V;
4488   V.resize(NumElems);
4489   if (NumElems == 4 && NumZero > 0) {
4490     for (unsigned i = 0; i < 4; ++i) {
4491       bool isZero = !(NonZeros & (1 << i));
4492       if (isZero)
4493         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4494       else
4495         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4496     }
4497
4498     for (unsigned i = 0; i < 2; ++i) {
4499       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4500         default: break;
4501         case 0:
4502           V[i] = V[i*2];  // Must be a zero vector.
4503           break;
4504         case 1:
4505           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4506           break;
4507         case 2:
4508           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4509           break;
4510         case 3:
4511           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4512           break;
4513       }
4514     }
4515
4516     SmallVector<int, 8> MaskVec;
4517     bool Reverse = (NonZeros & 0x3) == 2;
4518     for (unsigned i = 0; i < 2; ++i)
4519       MaskVec.push_back(Reverse ? 1-i : i);
4520     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4521     for (unsigned i = 0; i < 2; ++i)
4522       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4523     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4524   }
4525
4526   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4527     // Check for a build vector of consecutive loads.
4528     for (unsigned i = 0; i < NumElems; ++i)
4529       V[i] = Op.getOperand(i);
4530
4531     // Check for elements which are consecutive loads.
4532     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4533     if (LD.getNode())
4534       return LD;
4535
4536     // For SSE 4.1, use insertps to put the high elements into the low element.
4537     if (getSubtarget()->hasSSE41()) {
4538       SDValue Result;
4539       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4540         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4541       else
4542         Result = DAG.getUNDEF(VT);
4543
4544       for (unsigned i = 1; i < NumElems; ++i) {
4545         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4546         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4547                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4548       }
4549       return Result;
4550     }
4551
4552     // Otherwise, expand into a number of unpckl*, start by extending each of
4553     // our (non-undef) elements to the full vector width with the element in the
4554     // bottom slot of the vector (which generates no code for SSE).
4555     for (unsigned i = 0; i < NumElems; ++i) {
4556       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4557         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4558       else
4559         V[i] = DAG.getUNDEF(VT);
4560     }
4561
4562     // Next, we iteratively mix elements, e.g. for v4f32:
4563     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4564     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4565     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4566     unsigned EltStride = NumElems >> 1;
4567     while (EltStride != 0) {
4568       for (unsigned i = 0; i < EltStride; ++i) {
4569         // If V[i+EltStride] is undef and this is the first round of mixing,
4570         // then it is safe to just drop this shuffle: V[i] is already in the
4571         // right place, the one element (since it's the first round) being
4572         // inserted as undef can be dropped.  This isn't safe for successive
4573         // rounds because they will permute elements within both vectors.
4574         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4575             EltStride == NumElems/2)
4576           continue;
4577
4578         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4579       }
4580       EltStride >>= 1;
4581     }
4582     return V[0];
4583   }
4584   return SDValue();
4585 }
4586
4587 SDValue
4588 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4589   // We support concatenate two MMX registers and place them in a MMX
4590   // register.  This is better than doing a stack convert.
4591   DebugLoc dl = Op.getDebugLoc();
4592   EVT ResVT = Op.getValueType();
4593   assert(Op.getNumOperands() == 2);
4594   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4595          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4596   int Mask[2];
4597   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4598   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4599   InVec = Op.getOperand(1);
4600   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4601     unsigned NumElts = ResVT.getVectorNumElements();
4602     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4603     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4604                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4605   } else {
4606     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4607     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4608     Mask[0] = 0; Mask[1] = 2;
4609     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4610   }
4611   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4612 }
4613
4614 // v8i16 shuffles - Prefer shuffles in the following order:
4615 // 1. [all]   pshuflw, pshufhw, optional move
4616 // 2. [ssse3] 1 x pshufb
4617 // 3. [ssse3] 2 x pshufb + 1 x por
4618 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4619 SDValue
4620 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4621                                             SelectionDAG &DAG) const {
4622   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4623   SDValue V1 = SVOp->getOperand(0);
4624   SDValue V2 = SVOp->getOperand(1);
4625   DebugLoc dl = SVOp->getDebugLoc();
4626   SmallVector<int, 8> MaskVals;
4627
4628   // Determine if more than 1 of the words in each of the low and high quadwords
4629   // of the result come from the same quadword of one of the two inputs.  Undef
4630   // mask values count as coming from any quadword, for better codegen.
4631   SmallVector<unsigned, 4> LoQuad(4);
4632   SmallVector<unsigned, 4> HiQuad(4);
4633   BitVector InputQuads(4);
4634   for (unsigned i = 0; i < 8; ++i) {
4635     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4636     int EltIdx = SVOp->getMaskElt(i);
4637     MaskVals.push_back(EltIdx);
4638     if (EltIdx < 0) {
4639       ++Quad[0];
4640       ++Quad[1];
4641       ++Quad[2];
4642       ++Quad[3];
4643       continue;
4644     }
4645     ++Quad[EltIdx / 4];
4646     InputQuads.set(EltIdx / 4);
4647   }
4648
4649   int BestLoQuad = -1;
4650   unsigned MaxQuad = 1;
4651   for (unsigned i = 0; i < 4; ++i) {
4652     if (LoQuad[i] > MaxQuad) {
4653       BestLoQuad = i;
4654       MaxQuad = LoQuad[i];
4655     }
4656   }
4657
4658   int BestHiQuad = -1;
4659   MaxQuad = 1;
4660   for (unsigned i = 0; i < 4; ++i) {
4661     if (HiQuad[i] > MaxQuad) {
4662       BestHiQuad = i;
4663       MaxQuad = HiQuad[i];
4664     }
4665   }
4666
4667   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4668   // of the two input vectors, shuffle them into one input vector so only a
4669   // single pshufb instruction is necessary. If There are more than 2 input
4670   // quads, disable the next transformation since it does not help SSSE3.
4671   bool V1Used = InputQuads[0] || InputQuads[1];
4672   bool V2Used = InputQuads[2] || InputQuads[3];
4673   if (Subtarget->hasSSSE3()) {
4674     if (InputQuads.count() == 2 && V1Used && V2Used) {
4675       BestLoQuad = InputQuads.find_first();
4676       BestHiQuad = InputQuads.find_next(BestLoQuad);
4677     }
4678     if (InputQuads.count() > 2) {
4679       BestLoQuad = -1;
4680       BestHiQuad = -1;
4681     }
4682   }
4683
4684   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4685   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4686   // words from all 4 input quadwords.
4687   SDValue NewV;
4688   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4689     SmallVector<int, 8> MaskV;
4690     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4691     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4692     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4693                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4694                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4695     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4696
4697     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4698     // source words for the shuffle, to aid later transformations.
4699     bool AllWordsInNewV = true;
4700     bool InOrder[2] = { true, true };
4701     for (unsigned i = 0; i != 8; ++i) {
4702       int idx = MaskVals[i];
4703       if (idx != (int)i)
4704         InOrder[i/4] = false;
4705       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4706         continue;
4707       AllWordsInNewV = false;
4708       break;
4709     }
4710
4711     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4712     if (AllWordsInNewV) {
4713       for (int i = 0; i != 8; ++i) {
4714         int idx = MaskVals[i];
4715         if (idx < 0)
4716           continue;
4717         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4718         if ((idx != i) && idx < 4)
4719           pshufhw = false;
4720         if ((idx != i) && idx > 3)
4721           pshuflw = false;
4722       }
4723       V1 = NewV;
4724       V2Used = false;
4725       BestLoQuad = 0;
4726       BestHiQuad = 1;
4727     }
4728
4729     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4730     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4731     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4732       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4733       unsigned TargetMask = 0;
4734       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4735                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4736       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4737                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4738       V1 = NewV.getOperand(0);
4739       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4740     }
4741   }
4742
4743   // If we have SSSE3, and all words of the result are from 1 input vector,
4744   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4745   // is present, fall back to case 4.
4746   if (Subtarget->hasSSSE3()) {
4747     SmallVector<SDValue,16> pshufbMask;
4748
4749     // If we have elements from both input vectors, set the high bit of the
4750     // shuffle mask element to zero out elements that come from V2 in the V1
4751     // mask, and elements that come from V1 in the V2 mask, so that the two
4752     // results can be OR'd together.
4753     bool TwoInputs = V1Used && V2Used;
4754     for (unsigned i = 0; i != 8; ++i) {
4755       int EltIdx = MaskVals[i] * 2;
4756       if (TwoInputs && (EltIdx >= 16)) {
4757         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4758         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4759         continue;
4760       }
4761       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4762       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4763     }
4764     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4765     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4766                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4767                                  MVT::v16i8, &pshufbMask[0], 16));
4768     if (!TwoInputs)
4769       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4770
4771     // Calculate the shuffle mask for the second input, shuffle it, and
4772     // OR it with the first shuffled input.
4773     pshufbMask.clear();
4774     for (unsigned i = 0; i != 8; ++i) {
4775       int EltIdx = MaskVals[i] * 2;
4776       if (EltIdx < 16) {
4777         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4778         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4779         continue;
4780       }
4781       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4782       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4783     }
4784     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4785     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4786                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4787                                  MVT::v16i8, &pshufbMask[0], 16));
4788     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4789     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4790   }
4791
4792   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4793   // and update MaskVals with new element order.
4794   BitVector InOrder(8);
4795   if (BestLoQuad >= 0) {
4796     SmallVector<int, 8> MaskV;
4797     for (int i = 0; i != 4; ++i) {
4798       int idx = MaskVals[i];
4799       if (idx < 0) {
4800         MaskV.push_back(-1);
4801         InOrder.set(i);
4802       } else if ((idx / 4) == BestLoQuad) {
4803         MaskV.push_back(idx & 3);
4804         InOrder.set(i);
4805       } else {
4806         MaskV.push_back(-1);
4807       }
4808     }
4809     for (unsigned i = 4; i != 8; ++i)
4810       MaskV.push_back(i);
4811     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4812                                 &MaskV[0]);
4813
4814     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4815       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4816                                NewV.getOperand(0),
4817                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4818                                DAG);
4819   }
4820
4821   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4822   // and update MaskVals with the new element order.
4823   if (BestHiQuad >= 0) {
4824     SmallVector<int, 8> MaskV;
4825     for (unsigned i = 0; i != 4; ++i)
4826       MaskV.push_back(i);
4827     for (unsigned i = 4; i != 8; ++i) {
4828       int idx = MaskVals[i];
4829       if (idx < 0) {
4830         MaskV.push_back(-1);
4831         InOrder.set(i);
4832       } else if ((idx / 4) == BestHiQuad) {
4833         MaskV.push_back((idx & 3) + 4);
4834         InOrder.set(i);
4835       } else {
4836         MaskV.push_back(-1);
4837       }
4838     }
4839     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4840                                 &MaskV[0]);
4841
4842     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4843       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4844                               NewV.getOperand(0),
4845                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4846                               DAG);
4847   }
4848
4849   // In case BestHi & BestLo were both -1, which means each quadword has a word
4850   // from each of the four input quadwords, calculate the InOrder bitvector now
4851   // before falling through to the insert/extract cleanup.
4852   if (BestLoQuad == -1 && BestHiQuad == -1) {
4853     NewV = V1;
4854     for (int i = 0; i != 8; ++i)
4855       if (MaskVals[i] < 0 || MaskVals[i] == i)
4856         InOrder.set(i);
4857   }
4858
4859   // The other elements are put in the right place using pextrw and pinsrw.
4860   for (unsigned i = 0; i != 8; ++i) {
4861     if (InOrder[i])
4862       continue;
4863     int EltIdx = MaskVals[i];
4864     if (EltIdx < 0)
4865       continue;
4866     SDValue ExtOp = (EltIdx < 8)
4867     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4868                   DAG.getIntPtrConstant(EltIdx))
4869     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4870                   DAG.getIntPtrConstant(EltIdx - 8));
4871     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4872                        DAG.getIntPtrConstant(i));
4873   }
4874   return NewV;
4875 }
4876
4877 // v16i8 shuffles - Prefer shuffles in the following order:
4878 // 1. [ssse3] 1 x pshufb
4879 // 2. [ssse3] 2 x pshufb + 1 x por
4880 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4881 static
4882 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4883                                  SelectionDAG &DAG,
4884                                  const X86TargetLowering &TLI) {
4885   SDValue V1 = SVOp->getOperand(0);
4886   SDValue V2 = SVOp->getOperand(1);
4887   DebugLoc dl = SVOp->getDebugLoc();
4888   SmallVector<int, 16> MaskVals;
4889   SVOp->getMask(MaskVals);
4890
4891   // If we have SSSE3, case 1 is generated when all result bytes come from
4892   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4893   // present, fall back to case 3.
4894   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4895   bool V1Only = true;
4896   bool V2Only = true;
4897   for (unsigned i = 0; i < 16; ++i) {
4898     int EltIdx = MaskVals[i];
4899     if (EltIdx < 0)
4900       continue;
4901     if (EltIdx < 16)
4902       V2Only = false;
4903     else
4904       V1Only = false;
4905   }
4906
4907   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4908   if (TLI.getSubtarget()->hasSSSE3()) {
4909     SmallVector<SDValue,16> pshufbMask;
4910
4911     // If all result elements are from one input vector, then only translate
4912     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4913     //
4914     // Otherwise, we have elements from both input vectors, and must zero out
4915     // elements that come from V2 in the first mask, and V1 in the second mask
4916     // so that we can OR them together.
4917     bool TwoInputs = !(V1Only || V2Only);
4918     for (unsigned i = 0; i != 16; ++i) {
4919       int EltIdx = MaskVals[i];
4920       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4921         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4922         continue;
4923       }
4924       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4925     }
4926     // If all the elements are from V2, assign it to V1 and return after
4927     // building the first pshufb.
4928     if (V2Only)
4929       V1 = V2;
4930     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4931                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4932                                  MVT::v16i8, &pshufbMask[0], 16));
4933     if (!TwoInputs)
4934       return V1;
4935
4936     // Calculate the shuffle mask for the second input, shuffle it, and
4937     // OR it with the first shuffled input.
4938     pshufbMask.clear();
4939     for (unsigned i = 0; i != 16; ++i) {
4940       int EltIdx = MaskVals[i];
4941       if (EltIdx < 16) {
4942         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4943         continue;
4944       }
4945       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4946     }
4947     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4948                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4949                                  MVT::v16i8, &pshufbMask[0], 16));
4950     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4951   }
4952
4953   // No SSSE3 - Calculate in place words and then fix all out of place words
4954   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4955   // the 16 different words that comprise the two doublequadword input vectors.
4956   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4957   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4958   SDValue NewV = V2Only ? V2 : V1;
4959   for (int i = 0; i != 8; ++i) {
4960     int Elt0 = MaskVals[i*2];
4961     int Elt1 = MaskVals[i*2+1];
4962
4963     // This word of the result is all undef, skip it.
4964     if (Elt0 < 0 && Elt1 < 0)
4965       continue;
4966
4967     // This word of the result is already in the correct place, skip it.
4968     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4969       continue;
4970     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4971       continue;
4972
4973     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4974     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4975     SDValue InsElt;
4976
4977     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4978     // using a single extract together, load it and store it.
4979     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4980       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4981                            DAG.getIntPtrConstant(Elt1 / 2));
4982       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4983                         DAG.getIntPtrConstant(i));
4984       continue;
4985     }
4986
4987     // If Elt1 is defined, extract it from the appropriate source.  If the
4988     // source byte is not also odd, shift the extracted word left 8 bits
4989     // otherwise clear the bottom 8 bits if we need to do an or.
4990     if (Elt1 >= 0) {
4991       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4992                            DAG.getIntPtrConstant(Elt1 / 2));
4993       if ((Elt1 & 1) == 0)
4994         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4995                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4996       else if (Elt0 >= 0)
4997         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4998                              DAG.getConstant(0xFF00, MVT::i16));
4999     }
5000     // If Elt0 is defined, extract it from the appropriate source.  If the
5001     // source byte is not also even, shift the extracted word right 8 bits. If
5002     // Elt1 was also defined, OR the extracted values together before
5003     // inserting them in the result.
5004     if (Elt0 >= 0) {
5005       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5006                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5007       if ((Elt0 & 1) != 0)
5008         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5009                               DAG.getConstant(8, TLI.getShiftAmountTy()));
5010       else if (Elt1 >= 0)
5011         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5012                              DAG.getConstant(0x00FF, MVT::i16));
5013       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5014                          : InsElt0;
5015     }
5016     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5017                        DAG.getIntPtrConstant(i));
5018   }
5019   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5020 }
5021
5022 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5023 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5024 /// done when every pair / quad of shuffle mask elements point to elements in
5025 /// the right sequence. e.g.
5026 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5027 static
5028 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5029                                  SelectionDAG &DAG, DebugLoc dl) {
5030   EVT VT = SVOp->getValueType(0);
5031   SDValue V1 = SVOp->getOperand(0);
5032   SDValue V2 = SVOp->getOperand(1);
5033   unsigned NumElems = VT.getVectorNumElements();
5034   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5035   EVT NewVT;
5036   switch (VT.getSimpleVT().SimpleTy) {
5037   default: assert(false && "Unexpected!");
5038   case MVT::v4f32: NewVT = MVT::v2f64; break;
5039   case MVT::v4i32: NewVT = MVT::v2i64; break;
5040   case MVT::v8i16: NewVT = MVT::v4i32; break;
5041   case MVT::v16i8: NewVT = MVT::v4i32; break;
5042   }
5043
5044   int Scale = NumElems / NewWidth;
5045   SmallVector<int, 8> MaskVec;
5046   for (unsigned i = 0; i < NumElems; i += Scale) {
5047     int StartIdx = -1;
5048     for (int j = 0; j < Scale; ++j) {
5049       int EltIdx = SVOp->getMaskElt(i+j);
5050       if (EltIdx < 0)
5051         continue;
5052       if (StartIdx == -1)
5053         StartIdx = EltIdx - (EltIdx % Scale);
5054       if (EltIdx != StartIdx + j)
5055         return SDValue();
5056     }
5057     if (StartIdx == -1)
5058       MaskVec.push_back(-1);
5059     else
5060       MaskVec.push_back(StartIdx / Scale);
5061   }
5062
5063   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5064   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5065   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5066 }
5067
5068 /// getVZextMovL - Return a zero-extending vector move low node.
5069 ///
5070 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5071                             SDValue SrcOp, SelectionDAG &DAG,
5072                             const X86Subtarget *Subtarget, DebugLoc dl) {
5073   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5074     LoadSDNode *LD = NULL;
5075     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5076       LD = dyn_cast<LoadSDNode>(SrcOp);
5077     if (!LD) {
5078       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5079       // instead.
5080       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5081       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5082           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5083           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5084           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5085         // PR2108
5086         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5087         return DAG.getNode(ISD::BITCAST, dl, VT,
5088                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5089                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5090                                                    OpVT,
5091                                                    SrcOp.getOperand(0)
5092                                                           .getOperand(0))));
5093       }
5094     }
5095   }
5096
5097   return DAG.getNode(ISD::BITCAST, dl, VT,
5098                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5099                                  DAG.getNode(ISD::BITCAST, dl,
5100                                              OpVT, SrcOp)));
5101 }
5102
5103 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5104 /// shuffles.
5105 static SDValue
5106 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5107   SDValue V1 = SVOp->getOperand(0);
5108   SDValue V2 = SVOp->getOperand(1);
5109   DebugLoc dl = SVOp->getDebugLoc();
5110   EVT VT = SVOp->getValueType(0);
5111
5112   SmallVector<std::pair<int, int>, 8> Locs;
5113   Locs.resize(4);
5114   SmallVector<int, 8> Mask1(4U, -1);
5115   SmallVector<int, 8> PermMask;
5116   SVOp->getMask(PermMask);
5117
5118   unsigned NumHi = 0;
5119   unsigned NumLo = 0;
5120   for (unsigned i = 0; i != 4; ++i) {
5121     int Idx = PermMask[i];
5122     if (Idx < 0) {
5123       Locs[i] = std::make_pair(-1, -1);
5124     } else {
5125       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5126       if (Idx < 4) {
5127         Locs[i] = std::make_pair(0, NumLo);
5128         Mask1[NumLo] = Idx;
5129         NumLo++;
5130       } else {
5131         Locs[i] = std::make_pair(1, NumHi);
5132         if (2+NumHi < 4)
5133           Mask1[2+NumHi] = Idx;
5134         NumHi++;
5135       }
5136     }
5137   }
5138
5139   if (NumLo <= 2 && NumHi <= 2) {
5140     // If no more than two elements come from either vector. This can be
5141     // implemented with two shuffles. First shuffle gather the elements.
5142     // The second shuffle, which takes the first shuffle as both of its
5143     // vector operands, put the elements into the right order.
5144     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5145
5146     SmallVector<int, 8> Mask2(4U, -1);
5147
5148     for (unsigned i = 0; i != 4; ++i) {
5149       if (Locs[i].first == -1)
5150         continue;
5151       else {
5152         unsigned Idx = (i < 2) ? 0 : 4;
5153         Idx += Locs[i].first * 2 + Locs[i].second;
5154         Mask2[i] = Idx;
5155       }
5156     }
5157
5158     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5159   } else if (NumLo == 3 || NumHi == 3) {
5160     // Otherwise, we must have three elements from one vector, call it X, and
5161     // one element from the other, call it Y.  First, use a shufps to build an
5162     // intermediate vector with the one element from Y and the element from X
5163     // that will be in the same half in the final destination (the indexes don't
5164     // matter). Then, use a shufps to build the final vector, taking the half
5165     // containing the element from Y from the intermediate, and the other half
5166     // from X.
5167     if (NumHi == 3) {
5168       // Normalize it so the 3 elements come from V1.
5169       CommuteVectorShuffleMask(PermMask, VT);
5170       std::swap(V1, V2);
5171     }
5172
5173     // Find the element from V2.
5174     unsigned HiIndex;
5175     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5176       int Val = PermMask[HiIndex];
5177       if (Val < 0)
5178         continue;
5179       if (Val >= 4)
5180         break;
5181     }
5182
5183     Mask1[0] = PermMask[HiIndex];
5184     Mask1[1] = -1;
5185     Mask1[2] = PermMask[HiIndex^1];
5186     Mask1[3] = -1;
5187     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5188
5189     if (HiIndex >= 2) {
5190       Mask1[0] = PermMask[0];
5191       Mask1[1] = PermMask[1];
5192       Mask1[2] = HiIndex & 1 ? 6 : 4;
5193       Mask1[3] = HiIndex & 1 ? 4 : 6;
5194       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5195     } else {
5196       Mask1[0] = HiIndex & 1 ? 2 : 0;
5197       Mask1[1] = HiIndex & 1 ? 0 : 2;
5198       Mask1[2] = PermMask[2];
5199       Mask1[3] = PermMask[3];
5200       if (Mask1[2] >= 0)
5201         Mask1[2] += 4;
5202       if (Mask1[3] >= 0)
5203         Mask1[3] += 4;
5204       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5205     }
5206   }
5207
5208   // Break it into (shuffle shuffle_hi, shuffle_lo).
5209   Locs.clear();
5210   SmallVector<int,8> LoMask(4U, -1);
5211   SmallVector<int,8> HiMask(4U, -1);
5212
5213   SmallVector<int,8> *MaskPtr = &LoMask;
5214   unsigned MaskIdx = 0;
5215   unsigned LoIdx = 0;
5216   unsigned HiIdx = 2;
5217   for (unsigned i = 0; i != 4; ++i) {
5218     if (i == 2) {
5219       MaskPtr = &HiMask;
5220       MaskIdx = 1;
5221       LoIdx = 0;
5222       HiIdx = 2;
5223     }
5224     int Idx = PermMask[i];
5225     if (Idx < 0) {
5226       Locs[i] = std::make_pair(-1, -1);
5227     } else if (Idx < 4) {
5228       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5229       (*MaskPtr)[LoIdx] = Idx;
5230       LoIdx++;
5231     } else {
5232       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5233       (*MaskPtr)[HiIdx] = Idx;
5234       HiIdx++;
5235     }
5236   }
5237
5238   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5239   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5240   SmallVector<int, 8> MaskOps;
5241   for (unsigned i = 0; i != 4; ++i) {
5242     if (Locs[i].first == -1) {
5243       MaskOps.push_back(-1);
5244     } else {
5245       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5246       MaskOps.push_back(Idx);
5247     }
5248   }
5249   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5250 }
5251
5252 static bool MayFoldVectorLoad(SDValue V) {
5253   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5254     V = V.getOperand(0);
5255   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5256     V = V.getOperand(0);
5257   if (MayFoldLoad(V))
5258     return true;
5259   return false;
5260 }
5261
5262 // FIXME: the version above should always be used. Since there's
5263 // a bug where several vector shuffles can't be folded because the
5264 // DAG is not updated during lowering and a node claims to have two
5265 // uses while it only has one, use this version, and let isel match
5266 // another instruction if the load really happens to have more than
5267 // one use. Remove this version after this bug get fixed.
5268 // rdar://8434668, PR8156
5269 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5270   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5271     V = V.getOperand(0);
5272   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5273     V = V.getOperand(0);
5274   if (ISD::isNormalLoad(V.getNode()))
5275     return true;
5276   return false;
5277 }
5278
5279 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5280 /// a vector extract, and if both can be later optimized into a single load.
5281 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5282 /// here because otherwise a target specific shuffle node is going to be
5283 /// emitted for this shuffle, and the optimization not done.
5284 /// FIXME: This is probably not the best approach, but fix the problem
5285 /// until the right path is decided.
5286 static
5287 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5288                                          const TargetLowering &TLI) {
5289   EVT VT = V.getValueType();
5290   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5291
5292   // Be sure that the vector shuffle is present in a pattern like this:
5293   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5294   if (!V.hasOneUse())
5295     return false;
5296
5297   SDNode *N = *V.getNode()->use_begin();
5298   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5299     return false;
5300
5301   SDValue EltNo = N->getOperand(1);
5302   if (!isa<ConstantSDNode>(EltNo))
5303     return false;
5304
5305   // If the bit convert changed the number of elements, it is unsafe
5306   // to examine the mask.
5307   bool HasShuffleIntoBitcast = false;
5308   if (V.getOpcode() == ISD::BITCAST) {
5309     EVT SrcVT = V.getOperand(0).getValueType();
5310     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5311       return false;
5312     V = V.getOperand(0);
5313     HasShuffleIntoBitcast = true;
5314   }
5315
5316   // Select the input vector, guarding against out of range extract vector.
5317   unsigned NumElems = VT.getVectorNumElements();
5318   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5319   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5320   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5321
5322   // Skip one more bit_convert if necessary
5323   if (V.getOpcode() == ISD::BITCAST)
5324     V = V.getOperand(0);
5325
5326   if (ISD::isNormalLoad(V.getNode())) {
5327     // Is the original load suitable?
5328     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5329
5330     // FIXME: avoid the multi-use bug that is preventing lots of
5331     // of foldings to be detected, this is still wrong of course, but
5332     // give the temporary desired behavior, and if it happens that
5333     // the load has real more uses, during isel it will not fold, and
5334     // will generate poor code.
5335     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5336       return false;
5337
5338     if (!HasShuffleIntoBitcast)
5339       return true;
5340
5341     // If there's a bitcast before the shuffle, check if the load type and
5342     // alignment is valid.
5343     unsigned Align = LN0->getAlignment();
5344     unsigned NewAlign =
5345       TLI.getTargetData()->getABITypeAlignment(
5346                                     VT.getTypeForEVT(*DAG.getContext()));
5347
5348     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5349       return false;
5350   }
5351
5352   return true;
5353 }
5354
5355 static
5356 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5357   EVT VT = Op.getValueType();
5358
5359   // Canonizalize to v2f64.
5360   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5361   return DAG.getNode(ISD::BITCAST, dl, VT,
5362                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5363                                           V1, DAG));
5364 }
5365
5366 static
5367 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5368                         bool HasSSE2) {
5369   SDValue V1 = Op.getOperand(0);
5370   SDValue V2 = Op.getOperand(1);
5371   EVT VT = Op.getValueType();
5372
5373   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5374
5375   if (HasSSE2 && VT == MVT::v2f64)
5376     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5377
5378   // v4f32 or v4i32
5379   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5380 }
5381
5382 static
5383 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5384   SDValue V1 = Op.getOperand(0);
5385   SDValue V2 = Op.getOperand(1);
5386   EVT VT = Op.getValueType();
5387
5388   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5389          "unsupported shuffle type");
5390
5391   if (V2.getOpcode() == ISD::UNDEF)
5392     V2 = V1;
5393
5394   // v4i32 or v4f32
5395   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5396 }
5397
5398 static
5399 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5400   SDValue V1 = Op.getOperand(0);
5401   SDValue V2 = Op.getOperand(1);
5402   EVT VT = Op.getValueType();
5403   unsigned NumElems = VT.getVectorNumElements();
5404
5405   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5406   // operand of these instructions is only memory, so check if there's a
5407   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5408   // same masks.
5409   bool CanFoldLoad = false;
5410
5411   // Trivial case, when V2 comes from a load.
5412   if (MayFoldVectorLoad(V2))
5413     CanFoldLoad = true;
5414
5415   // When V1 is a load, it can be folded later into a store in isel, example:
5416   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5417   //    turns into:
5418   //  (MOVLPSmr addr:$src1, VR128:$src2)
5419   // So, recognize this potential and also use MOVLPS or MOVLPD
5420   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5421     CanFoldLoad = true;
5422
5423   if (CanFoldLoad) {
5424     if (HasSSE2 && NumElems == 2)
5425       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5426
5427     if (NumElems == 4)
5428       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5429   }
5430
5431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5432   // movl and movlp will both match v2i64, but v2i64 is never matched by
5433   // movl earlier because we make it strict to avoid messing with the movlp load
5434   // folding logic (see the code above getMOVLP call). Match it here then,
5435   // this is horrible, but will stay like this until we move all shuffle
5436   // matching to x86 specific nodes. Note that for the 1st condition all
5437   // types are matched with movsd.
5438   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5439     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5440   else if (HasSSE2)
5441     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5442
5443
5444   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5445
5446   // Invert the operand order and use SHUFPS to match it.
5447   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5448                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5449 }
5450
5451 static inline unsigned getUNPCKLOpcode(EVT VT) {
5452   switch(VT.getSimpleVT().SimpleTy) {
5453   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5454   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5455   case MVT::v4f32: return X86ISD::UNPCKLPS;
5456   case MVT::v2f64: return X86ISD::UNPCKLPD;
5457   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5458   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5459   default:
5460     llvm_unreachable("Unknow type for unpckl");
5461   }
5462   return 0;
5463 }
5464
5465 static inline unsigned getUNPCKHOpcode(EVT VT) {
5466   switch(VT.getSimpleVT().SimpleTy) {
5467   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5468   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5469   case MVT::v4f32: return X86ISD::UNPCKHPS;
5470   case MVT::v2f64: return X86ISD::UNPCKHPD;
5471   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5472   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5473   default:
5474     llvm_unreachable("Unknow type for unpckh");
5475   }
5476   return 0;
5477 }
5478
5479 static
5480 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5481                                const TargetLowering &TLI,
5482                                const X86Subtarget *Subtarget) {
5483   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5484   EVT VT = Op.getValueType();
5485   DebugLoc dl = Op.getDebugLoc();
5486   SDValue V1 = Op.getOperand(0);
5487   SDValue V2 = Op.getOperand(1);
5488
5489   if (isZeroShuffle(SVOp))
5490     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5491
5492   // Handle splat operations
5493   if (SVOp->isSplat()) {
5494     // Special case, this is the only place now where it's
5495     // allowed to return a vector_shuffle operation without
5496     // using a target specific node, because *hopefully* it
5497     // will be optimized away by the dag combiner.
5498     if (VT.getVectorNumElements() <= 4 &&
5499         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5500       return Op;
5501
5502     // Handle splats by matching through known masks
5503     if (VT.getVectorNumElements() <= 4)
5504       return SDValue();
5505
5506     // Canonicalize all of the remaining to v4f32.
5507     return PromoteSplat(SVOp, DAG);
5508   }
5509
5510   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5511   // do it!
5512   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5513     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5514     if (NewOp.getNode())
5515       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5516   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5517     // FIXME: Figure out a cleaner way to do this.
5518     // Try to make use of movq to zero out the top part.
5519     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5520       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5521       if (NewOp.getNode()) {
5522         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5523           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5524                               DAG, Subtarget, dl);
5525       }
5526     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5527       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5528       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5529         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5530                             DAG, Subtarget, dl);
5531     }
5532   }
5533   return SDValue();
5534 }
5535
5536 SDValue
5537 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5538   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5539   SDValue V1 = Op.getOperand(0);
5540   SDValue V2 = Op.getOperand(1);
5541   EVT VT = Op.getValueType();
5542   DebugLoc dl = Op.getDebugLoc();
5543   unsigned NumElems = VT.getVectorNumElements();
5544   bool isMMX = VT.getSizeInBits() == 64;
5545   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5546   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5547   bool V1IsSplat = false;
5548   bool V2IsSplat = false;
5549   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5550   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5551   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5552   MachineFunction &MF = DAG.getMachineFunction();
5553   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5554
5555   // Shuffle operations on MMX not supported.
5556   if (isMMX)
5557     return Op;
5558
5559   // Vector shuffle lowering takes 3 steps:
5560   //
5561   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5562   //    narrowing and commutation of operands should be handled.
5563   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5564   //    shuffle nodes.
5565   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5566   //    so the shuffle can be broken into other shuffles and the legalizer can
5567   //    try the lowering again.
5568   //
5569   // The general ideia is that no vector_shuffle operation should be left to
5570   // be matched during isel, all of them must be converted to a target specific
5571   // node here.
5572
5573   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5574   // narrowing and commutation of operands should be handled. The actual code
5575   // doesn't include all of those, work in progress...
5576   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5577   if (NewOp.getNode())
5578     return NewOp;
5579
5580   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5581   // unpckh_undef). Only use pshufd if speed is more important than size.
5582   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5583     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5584       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5585   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5586     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5587       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5588
5589   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5590       RelaxedMayFoldVectorLoad(V1))
5591     return getMOVDDup(Op, dl, V1, DAG);
5592
5593   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5594     return getMOVHighToLow(Op, dl, DAG);
5595
5596   // Use to match splats
5597   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5598       (VT == MVT::v2f64 || VT == MVT::v2i64))
5599     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5600
5601   if (X86::isPSHUFDMask(SVOp)) {
5602     // The actual implementation will match the mask in the if above and then
5603     // during isel it can match several different instructions, not only pshufd
5604     // as its name says, sad but true, emulate the behavior for now...
5605     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5606         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5607
5608     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5609
5610     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5611       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5612
5613     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5614       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5615                                   TargetMask, DAG);
5616
5617     if (VT == MVT::v4f32)
5618       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5619                                   TargetMask, DAG);
5620   }
5621
5622   // Check if this can be converted into a logical shift.
5623   bool isLeft = false;
5624   unsigned ShAmt = 0;
5625   SDValue ShVal;
5626   bool isShift = getSubtarget()->hasSSE2() &&
5627     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5628   if (isShift && ShVal.hasOneUse()) {
5629     // If the shifted value has multiple uses, it may be cheaper to use
5630     // v_set0 + movlhps or movhlps, etc.
5631     EVT EltVT = VT.getVectorElementType();
5632     ShAmt *= EltVT.getSizeInBits();
5633     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5634   }
5635
5636   if (X86::isMOVLMask(SVOp)) {
5637     if (V1IsUndef)
5638       return V2;
5639     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5640       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5641     if (!X86::isMOVLPMask(SVOp)) {
5642       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5643         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5644
5645       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5646         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5647     }
5648   }
5649
5650   // FIXME: fold these into legal mask.
5651   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5652     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5653
5654   if (X86::isMOVHLPSMask(SVOp))
5655     return getMOVHighToLow(Op, dl, DAG);
5656
5657   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5658     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5659
5660   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5661     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5662
5663   if (X86::isMOVLPMask(SVOp))
5664     return getMOVLP(Op, dl, DAG, HasSSE2);
5665
5666   if (ShouldXformToMOVHLPS(SVOp) ||
5667       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5668     return CommuteVectorShuffle(SVOp, DAG);
5669
5670   if (isShift) {
5671     // No better options. Use a vshl / vsrl.
5672     EVT EltVT = VT.getVectorElementType();
5673     ShAmt *= EltVT.getSizeInBits();
5674     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5675   }
5676
5677   bool Commuted = false;
5678   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5679   // 1,1,1,1 -> v8i16 though.
5680   V1IsSplat = isSplatVector(V1.getNode());
5681   V2IsSplat = isSplatVector(V2.getNode());
5682
5683   // Canonicalize the splat or undef, if present, to be on the RHS.
5684   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5685     Op = CommuteVectorShuffle(SVOp, DAG);
5686     SVOp = cast<ShuffleVectorSDNode>(Op);
5687     V1 = SVOp->getOperand(0);
5688     V2 = SVOp->getOperand(1);
5689     std::swap(V1IsSplat, V2IsSplat);
5690     std::swap(V1IsUndef, V2IsUndef);
5691     Commuted = true;
5692   }
5693
5694   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5695     // Shuffling low element of v1 into undef, just return v1.
5696     if (V2IsUndef)
5697       return V1;
5698     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5699     // the instruction selector will not match, so get a canonical MOVL with
5700     // swapped operands to undo the commute.
5701     return getMOVL(DAG, dl, VT, V2, V1);
5702   }
5703
5704   if (X86::isUNPCKLMask(SVOp))
5705     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5706
5707   if (X86::isUNPCKHMask(SVOp))
5708     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5709
5710   if (V2IsSplat) {
5711     // Normalize mask so all entries that point to V2 points to its first
5712     // element then try to match unpck{h|l} again. If match, return a
5713     // new vector_shuffle with the corrected mask.
5714     SDValue NewMask = NormalizeMask(SVOp, DAG);
5715     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5716     if (NSVOp != SVOp) {
5717       if (X86::isUNPCKLMask(NSVOp, true)) {
5718         return NewMask;
5719       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5720         return NewMask;
5721       }
5722     }
5723   }
5724
5725   if (Commuted) {
5726     // Commute is back and try unpck* again.
5727     // FIXME: this seems wrong.
5728     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5729     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5730
5731     if (X86::isUNPCKLMask(NewSVOp))
5732       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5733
5734     if (X86::isUNPCKHMask(NewSVOp))
5735       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5736   }
5737
5738   // Normalize the node to match x86 shuffle ops if needed
5739   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5740     return CommuteVectorShuffle(SVOp, DAG);
5741
5742   // The checks below are all present in isShuffleMaskLegal, but they are
5743   // inlined here right now to enable us to directly emit target specific
5744   // nodes, and remove one by one until they don't return Op anymore.
5745   SmallVector<int, 16> M;
5746   SVOp->getMask(M);
5747
5748   if (isPALIGNRMask(M, VT, HasSSSE3))
5749     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5750                                 X86::getShufflePALIGNRImmediate(SVOp),
5751                                 DAG);
5752
5753   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5754       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5755     if (VT == MVT::v2f64)
5756       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5757     if (VT == MVT::v2i64)
5758       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5759   }
5760
5761   if (isPSHUFHWMask(M, VT))
5762     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5763                                 X86::getShufflePSHUFHWImmediate(SVOp),
5764                                 DAG);
5765
5766   if (isPSHUFLWMask(M, VT))
5767     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5768                                 X86::getShufflePSHUFLWImmediate(SVOp),
5769                                 DAG);
5770
5771   if (isSHUFPMask(M, VT)) {
5772     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5773     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5774       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5775                                   TargetMask, DAG);
5776     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5777       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5778                                   TargetMask, DAG);
5779   }
5780
5781   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5782     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5783       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5784   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5785     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5786       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5787
5788   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5789   if (VT == MVT::v8i16) {
5790     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5791     if (NewOp.getNode())
5792       return NewOp;
5793   }
5794
5795   if (VT == MVT::v16i8) {
5796     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5797     if (NewOp.getNode())
5798       return NewOp;
5799   }
5800
5801   // Handle all 4 wide cases with a number of shuffles.
5802   if (NumElems == 4)
5803     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5804
5805   return SDValue();
5806 }
5807
5808 SDValue
5809 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5810                                                 SelectionDAG &DAG) const {
5811   EVT VT = Op.getValueType();
5812   DebugLoc dl = Op.getDebugLoc();
5813   if (VT.getSizeInBits() == 8) {
5814     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5815                                     Op.getOperand(0), Op.getOperand(1));
5816     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5817                                     DAG.getValueType(VT));
5818     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5819   } else if (VT.getSizeInBits() == 16) {
5820     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5821     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5822     if (Idx == 0)
5823       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5824                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5825                                      DAG.getNode(ISD::BITCAST, dl,
5826                                                  MVT::v4i32,
5827                                                  Op.getOperand(0)),
5828                                      Op.getOperand(1)));
5829     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5830                                     Op.getOperand(0), Op.getOperand(1));
5831     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5832                                     DAG.getValueType(VT));
5833     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5834   } else if (VT == MVT::f32) {
5835     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5836     // the result back to FR32 register. It's only worth matching if the
5837     // result has a single use which is a store or a bitcast to i32.  And in
5838     // the case of a store, it's not worth it if the index is a constant 0,
5839     // because a MOVSSmr can be used instead, which is smaller and faster.
5840     if (!Op.hasOneUse())
5841       return SDValue();
5842     SDNode *User = *Op.getNode()->use_begin();
5843     if ((User->getOpcode() != ISD::STORE ||
5844          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5845           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5846         (User->getOpcode() != ISD::BITCAST ||
5847          User->getValueType(0) != MVT::i32))
5848       return SDValue();
5849     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5850                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5851                                               Op.getOperand(0)),
5852                                               Op.getOperand(1));
5853     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5854   } else if (VT == MVT::i32) {
5855     // ExtractPS works with constant index.
5856     if (isa<ConstantSDNode>(Op.getOperand(1)))
5857       return Op;
5858   }
5859   return SDValue();
5860 }
5861
5862
5863 SDValue
5864 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5865                                            SelectionDAG &DAG) const {
5866   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5867     return SDValue();
5868
5869   if (Subtarget->hasSSE41()) {
5870     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5871     if (Res.getNode())
5872       return Res;
5873   }
5874
5875   EVT VT = Op.getValueType();
5876   DebugLoc dl = Op.getDebugLoc();
5877   // TODO: handle v16i8.
5878   if (VT.getSizeInBits() == 16) {
5879     SDValue Vec = Op.getOperand(0);
5880     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5881     if (Idx == 0)
5882       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5883                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5884                                      DAG.getNode(ISD::BITCAST, dl,
5885                                                  MVT::v4i32, Vec),
5886                                      Op.getOperand(1)));
5887     // Transform it so it match pextrw which produces a 32-bit result.
5888     EVT EltVT = MVT::i32;
5889     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5890                                     Op.getOperand(0), Op.getOperand(1));
5891     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5892                                     DAG.getValueType(VT));
5893     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5894   } else if (VT.getSizeInBits() == 32) {
5895     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5896     if (Idx == 0)
5897       return Op;
5898
5899     // SHUFPS the element to the lowest double word, then movss.
5900     int Mask[4] = { Idx, -1, -1, -1 };
5901     EVT VVT = Op.getOperand(0).getValueType();
5902     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5903                                        DAG.getUNDEF(VVT), Mask);
5904     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5905                        DAG.getIntPtrConstant(0));
5906   } else if (VT.getSizeInBits() == 64) {
5907     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5908     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5909     //        to match extract_elt for f64.
5910     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5911     if (Idx == 0)
5912       return Op;
5913
5914     // UNPCKHPD the element to the lowest double word, then movsd.
5915     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5916     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5917     int Mask[2] = { 1, -1 };
5918     EVT VVT = Op.getOperand(0).getValueType();
5919     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5920                                        DAG.getUNDEF(VVT), Mask);
5921     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5922                        DAG.getIntPtrConstant(0));
5923   }
5924
5925   return SDValue();
5926 }
5927
5928 SDValue
5929 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5930                                                SelectionDAG &DAG) const {
5931   EVT VT = Op.getValueType();
5932   EVT EltVT = VT.getVectorElementType();
5933   DebugLoc dl = Op.getDebugLoc();
5934
5935   SDValue N0 = Op.getOperand(0);
5936   SDValue N1 = Op.getOperand(1);
5937   SDValue N2 = Op.getOperand(2);
5938
5939   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5940       isa<ConstantSDNode>(N2)) {
5941     unsigned Opc;
5942     if (VT == MVT::v8i16)
5943       Opc = X86ISD::PINSRW;
5944     else if (VT == MVT::v16i8)
5945       Opc = X86ISD::PINSRB;
5946     else
5947       Opc = X86ISD::PINSRB;
5948
5949     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5950     // argument.
5951     if (N1.getValueType() != MVT::i32)
5952       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5953     if (N2.getValueType() != MVT::i32)
5954       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5955     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5956   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5957     // Bits [7:6] of the constant are the source select.  This will always be
5958     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5959     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5960     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5961     // Bits [5:4] of the constant are the destination select.  This is the
5962     //  value of the incoming immediate.
5963     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5964     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5965     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5966     // Create this as a scalar to vector..
5967     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5968     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5969   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5970     // PINSR* works with constant index.
5971     return Op;
5972   }
5973   return SDValue();
5974 }
5975
5976 SDValue
5977 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5978   EVT VT = Op.getValueType();
5979   EVT EltVT = VT.getVectorElementType();
5980
5981   if (Subtarget->hasSSE41())
5982     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5983
5984   if (EltVT == MVT::i8)
5985     return SDValue();
5986
5987   DebugLoc dl = Op.getDebugLoc();
5988   SDValue N0 = Op.getOperand(0);
5989   SDValue N1 = Op.getOperand(1);
5990   SDValue N2 = Op.getOperand(2);
5991
5992   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5993     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5994     // as its second argument.
5995     if (N1.getValueType() != MVT::i32)
5996       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5997     if (N2.getValueType() != MVT::i32)
5998       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5999     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6000   }
6001   return SDValue();
6002 }
6003
6004 SDValue
6005 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6006   DebugLoc dl = Op.getDebugLoc();
6007
6008   if (Op.getValueType() == MVT::v1i64 &&
6009       Op.getOperand(0).getValueType() == MVT::i64)
6010     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6011
6012   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6013   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6014          "Expected an SSE type!");
6015   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6016                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6017 }
6018
6019 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6020 // a simple subregister reference or explicit instructions to grab
6021 // upper bits of a vector.
6022 SDValue
6023 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6024   if (Subtarget->hasAVX()) {
6025     // TODO
6026   }
6027   return SDValue();
6028 }
6029
6030 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6031 // simple superregister reference or explicit instructions to insert
6032 // the upper bits of a vector.
6033 SDValue
6034 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6035   if (Subtarget->hasAVX()) {
6036     DebugLoc dl = Op.getNode()->getDebugLoc();
6037     SDValue Vec = Op.getNode()->getOperand(0);
6038     SDValue SubVec = Op.getNode()->getOperand(1);
6039     SDValue Idx = Op.getNode()->getOperand(2);
6040
6041     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6042         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6043       // TODO
6044     }
6045   }
6046   return SDValue();
6047 }
6048
6049 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6050 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6051 // one of the above mentioned nodes. It has to be wrapped because otherwise
6052 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6053 // be used to form addressing mode. These wrapped nodes will be selected
6054 // into MOV32ri.
6055 SDValue
6056 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6057   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6058
6059   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6060   // global base reg.
6061   unsigned char OpFlag = 0;
6062   unsigned WrapperKind = X86ISD::Wrapper;
6063   CodeModel::Model M = getTargetMachine().getCodeModel();
6064
6065   if (Subtarget->isPICStyleRIPRel() &&
6066       (M == CodeModel::Small || M == CodeModel::Kernel))
6067     WrapperKind = X86ISD::WrapperRIP;
6068   else if (Subtarget->isPICStyleGOT())
6069     OpFlag = X86II::MO_GOTOFF;
6070   else if (Subtarget->isPICStyleStubPIC())
6071     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6072
6073   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6074                                              CP->getAlignment(),
6075                                              CP->getOffset(), OpFlag);
6076   DebugLoc DL = CP->getDebugLoc();
6077   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6078   // With PIC, the address is actually $g + Offset.
6079   if (OpFlag) {
6080     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6081                          DAG.getNode(X86ISD::GlobalBaseReg,
6082                                      DebugLoc(), getPointerTy()),
6083                          Result);
6084   }
6085
6086   return Result;
6087 }
6088
6089 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6090   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6091
6092   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6093   // global base reg.
6094   unsigned char OpFlag = 0;
6095   unsigned WrapperKind = X86ISD::Wrapper;
6096   CodeModel::Model M = getTargetMachine().getCodeModel();
6097
6098   if (Subtarget->isPICStyleRIPRel() &&
6099       (M == CodeModel::Small || M == CodeModel::Kernel))
6100     WrapperKind = X86ISD::WrapperRIP;
6101   else if (Subtarget->isPICStyleGOT())
6102     OpFlag = X86II::MO_GOTOFF;
6103   else if (Subtarget->isPICStyleStubPIC())
6104     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6105
6106   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6107                                           OpFlag);
6108   DebugLoc DL = JT->getDebugLoc();
6109   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6110
6111   // With PIC, the address is actually $g + Offset.
6112   if (OpFlag)
6113     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6114                          DAG.getNode(X86ISD::GlobalBaseReg,
6115                                      DebugLoc(), getPointerTy()),
6116                          Result);
6117
6118   return Result;
6119 }
6120
6121 SDValue
6122 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6123   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6124
6125   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6126   // global base reg.
6127   unsigned char OpFlag = 0;
6128   unsigned WrapperKind = X86ISD::Wrapper;
6129   CodeModel::Model M = getTargetMachine().getCodeModel();
6130
6131   if (Subtarget->isPICStyleRIPRel() &&
6132       (M == CodeModel::Small || M == CodeModel::Kernel))
6133     WrapperKind = X86ISD::WrapperRIP;
6134   else if (Subtarget->isPICStyleGOT())
6135     OpFlag = X86II::MO_GOTOFF;
6136   else if (Subtarget->isPICStyleStubPIC())
6137     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6138
6139   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6140
6141   DebugLoc DL = Op.getDebugLoc();
6142   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6143
6144
6145   // With PIC, the address is actually $g + Offset.
6146   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6147       !Subtarget->is64Bit()) {
6148     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6149                          DAG.getNode(X86ISD::GlobalBaseReg,
6150                                      DebugLoc(), getPointerTy()),
6151                          Result);
6152   }
6153
6154   return Result;
6155 }
6156
6157 SDValue
6158 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6159   // Create the TargetBlockAddressAddress node.
6160   unsigned char OpFlags =
6161     Subtarget->ClassifyBlockAddressReference();
6162   CodeModel::Model M = getTargetMachine().getCodeModel();
6163   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6164   DebugLoc dl = Op.getDebugLoc();
6165   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6166                                        /*isTarget=*/true, OpFlags);
6167
6168   if (Subtarget->isPICStyleRIPRel() &&
6169       (M == CodeModel::Small || M == CodeModel::Kernel))
6170     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6171   else
6172     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6173
6174   // With PIC, the address is actually $g + Offset.
6175   if (isGlobalRelativeToPICBase(OpFlags)) {
6176     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6177                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6178                          Result);
6179   }
6180
6181   return Result;
6182 }
6183
6184 SDValue
6185 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6186                                       int64_t Offset,
6187                                       SelectionDAG &DAG) const {
6188   // Create the TargetGlobalAddress node, folding in the constant
6189   // offset if it is legal.
6190   unsigned char OpFlags =
6191     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6192   CodeModel::Model M = getTargetMachine().getCodeModel();
6193   SDValue Result;
6194   if (OpFlags == X86II::MO_NO_FLAG &&
6195       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6196     // A direct static reference to a global.
6197     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6198     Offset = 0;
6199   } else {
6200     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6201   }
6202
6203   if (Subtarget->isPICStyleRIPRel() &&
6204       (M == CodeModel::Small || M == CodeModel::Kernel))
6205     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6206   else
6207     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6208
6209   // With PIC, the address is actually $g + Offset.
6210   if (isGlobalRelativeToPICBase(OpFlags)) {
6211     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6212                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6213                          Result);
6214   }
6215
6216   // For globals that require a load from a stub to get the address, emit the
6217   // load.
6218   if (isGlobalStubReference(OpFlags))
6219     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6220                          MachinePointerInfo::getGOT(), false, false, 0);
6221
6222   // If there was a non-zero offset that we didn't fold, create an explicit
6223   // addition for it.
6224   if (Offset != 0)
6225     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6226                          DAG.getConstant(Offset, getPointerTy()));
6227
6228   return Result;
6229 }
6230
6231 SDValue
6232 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6233   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6234   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6235   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6236 }
6237
6238 static SDValue
6239 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6240            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6241            unsigned char OperandFlags) {
6242   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6243   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6244   DebugLoc dl = GA->getDebugLoc();
6245   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6246                                            GA->getValueType(0),
6247                                            GA->getOffset(),
6248                                            OperandFlags);
6249   if (InFlag) {
6250     SDValue Ops[] = { Chain,  TGA, *InFlag };
6251     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6252   } else {
6253     SDValue Ops[]  = { Chain, TGA };
6254     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6255   }
6256
6257   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6258   MFI->setAdjustsStack(true);
6259
6260   SDValue Flag = Chain.getValue(1);
6261   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6262 }
6263
6264 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6265 static SDValue
6266 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6267                                 const EVT PtrVT) {
6268   SDValue InFlag;
6269   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6270   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6271                                      DAG.getNode(X86ISD::GlobalBaseReg,
6272                                                  DebugLoc(), PtrVT), InFlag);
6273   InFlag = Chain.getValue(1);
6274
6275   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6276 }
6277
6278 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6279 static SDValue
6280 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6281                                 const EVT PtrVT) {
6282   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6283                     X86::RAX, X86II::MO_TLSGD);
6284 }
6285
6286 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6287 // "local exec" model.
6288 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6289                                    const EVT PtrVT, TLSModel::Model model,
6290                                    bool is64Bit) {
6291   DebugLoc dl = GA->getDebugLoc();
6292
6293   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6294   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6295                                                          is64Bit ? 257 : 256));
6296
6297   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6298                                       DAG.getIntPtrConstant(0),
6299                                       MachinePointerInfo(Ptr), false, false, 0);
6300
6301   unsigned char OperandFlags = 0;
6302   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6303   // initialexec.
6304   unsigned WrapperKind = X86ISD::Wrapper;
6305   if (model == TLSModel::LocalExec) {
6306     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6307   } else if (is64Bit) {
6308     assert(model == TLSModel::InitialExec);
6309     OperandFlags = X86II::MO_GOTTPOFF;
6310     WrapperKind = X86ISD::WrapperRIP;
6311   } else {
6312     assert(model == TLSModel::InitialExec);
6313     OperandFlags = X86II::MO_INDNTPOFF;
6314   }
6315
6316   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6317   // exec)
6318   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6319                                            GA->getValueType(0),
6320                                            GA->getOffset(), OperandFlags);
6321   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6322
6323   if (model == TLSModel::InitialExec)
6324     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6325                          MachinePointerInfo::getGOT(), false, false, 0);
6326
6327   // The address of the thread local variable is the add of the thread
6328   // pointer with the offset of the variable.
6329   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6330 }
6331
6332 SDValue
6333 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6334
6335   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6336   const GlobalValue *GV = GA->getGlobal();
6337
6338   if (Subtarget->isTargetELF()) {
6339     // TODO: implement the "local dynamic" model
6340     // TODO: implement the "initial exec"model for pic executables
6341
6342     // If GV is an alias then use the aliasee for determining
6343     // thread-localness.
6344     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6345       GV = GA->resolveAliasedGlobal(false);
6346
6347     TLSModel::Model model
6348       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6349
6350     switch (model) {
6351       case TLSModel::GeneralDynamic:
6352       case TLSModel::LocalDynamic: // not implemented
6353         if (Subtarget->is64Bit())
6354           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6355         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6356
6357       case TLSModel::InitialExec:
6358       case TLSModel::LocalExec:
6359         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6360                                    Subtarget->is64Bit());
6361     }
6362   } else if (Subtarget->isTargetDarwin()) {
6363     // Darwin only has one model of TLS.  Lower to that.
6364     unsigned char OpFlag = 0;
6365     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6366                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6367
6368     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6369     // global base reg.
6370     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6371                   !Subtarget->is64Bit();
6372     if (PIC32)
6373       OpFlag = X86II::MO_TLVP_PIC_BASE;
6374     else
6375       OpFlag = X86II::MO_TLVP;
6376     DebugLoc DL = Op.getDebugLoc();
6377     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6378                                                 GA->getValueType(0),
6379                                                 GA->getOffset(), OpFlag);
6380     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6381
6382     // With PIC32, the address is actually $g + Offset.
6383     if (PIC32)
6384       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6385                            DAG.getNode(X86ISD::GlobalBaseReg,
6386                                        DebugLoc(), getPointerTy()),
6387                            Offset);
6388
6389     // Lowering the machine isd will make sure everything is in the right
6390     // location.
6391     SDValue Chain = DAG.getEntryNode();
6392     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6393     SDValue Args[] = { Chain, Offset };
6394     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6395
6396     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6397     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6398     MFI->setAdjustsStack(true);
6399
6400     // And our return value (tls address) is in the standard call return value
6401     // location.
6402     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6403     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6404   }
6405
6406   assert(false &&
6407          "TLS not implemented for this target.");
6408
6409   llvm_unreachable("Unreachable");
6410   return SDValue();
6411 }
6412
6413
6414 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6415 /// take a 2 x i32 value to shift plus a shift amount.
6416 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6417   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6418   EVT VT = Op.getValueType();
6419   unsigned VTBits = VT.getSizeInBits();
6420   DebugLoc dl = Op.getDebugLoc();
6421   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6422   SDValue ShOpLo = Op.getOperand(0);
6423   SDValue ShOpHi = Op.getOperand(1);
6424   SDValue ShAmt  = Op.getOperand(2);
6425   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6426                                      DAG.getConstant(VTBits - 1, MVT::i8))
6427                        : DAG.getConstant(0, VT);
6428
6429   SDValue Tmp2, Tmp3;
6430   if (Op.getOpcode() == ISD::SHL_PARTS) {
6431     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6432     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6433   } else {
6434     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6435     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6436   }
6437
6438   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6439                                 DAG.getConstant(VTBits, MVT::i8));
6440   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6441                              AndNode, DAG.getConstant(0, MVT::i8));
6442
6443   SDValue Hi, Lo;
6444   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6445   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6446   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6447
6448   if (Op.getOpcode() == ISD::SHL_PARTS) {
6449     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6450     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6451   } else {
6452     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6453     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6454   }
6455
6456   SDValue Ops[2] = { Lo, Hi };
6457   return DAG.getMergeValues(Ops, 2, dl);
6458 }
6459
6460 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6461                                            SelectionDAG &DAG) const {
6462   EVT SrcVT = Op.getOperand(0).getValueType();
6463
6464   if (SrcVT.isVector())
6465     return SDValue();
6466
6467   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6468          "Unknown SINT_TO_FP to lower!");
6469
6470   // These are really Legal; return the operand so the caller accepts it as
6471   // Legal.
6472   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6473     return Op;
6474   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6475       Subtarget->is64Bit()) {
6476     return Op;
6477   }
6478
6479   DebugLoc dl = Op.getDebugLoc();
6480   unsigned Size = SrcVT.getSizeInBits()/8;
6481   MachineFunction &MF = DAG.getMachineFunction();
6482   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6483   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6484   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6485                                StackSlot,
6486                                MachinePointerInfo::getFixedStack(SSFI),
6487                                false, false, 0);
6488   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6489 }
6490
6491 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6492                                      SDValue StackSlot,
6493                                      SelectionDAG &DAG) const {
6494   // Build the FILD
6495   DebugLoc DL = Op.getDebugLoc();
6496   SDVTList Tys;
6497   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6498   if (useSSE)
6499     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6500   else
6501     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6502
6503   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6504
6505   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6506   MachineMemOperand *MMO =
6507     DAG.getMachineFunction()
6508     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6509                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6510
6511   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6512   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6513                                            X86ISD::FILD, DL,
6514                                            Tys, Ops, array_lengthof(Ops),
6515                                            SrcVT, MMO);
6516
6517   if (useSSE) {
6518     Chain = Result.getValue(1);
6519     SDValue InFlag = Result.getValue(2);
6520
6521     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6522     // shouldn't be necessary except that RFP cannot be live across
6523     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6524     MachineFunction &MF = DAG.getMachineFunction();
6525     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6526     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6527     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6528     Tys = DAG.getVTList(MVT::Other);
6529     SDValue Ops[] = {
6530       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6531     };
6532     MachineMemOperand *MMO =
6533       DAG.getMachineFunction()
6534       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6535                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6536
6537     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6538                                     Ops, array_lengthof(Ops),
6539                                     Op.getValueType(), MMO);
6540     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6541                          MachinePointerInfo::getFixedStack(SSFI),
6542                          false, false, 0);
6543   }
6544
6545   return Result;
6546 }
6547
6548 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6549 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6550                                                SelectionDAG &DAG) const {
6551   // This algorithm is not obvious. Here it is in C code, more or less:
6552   /*
6553     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6554       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6555       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6556
6557       // Copy ints to xmm registers.
6558       __m128i xh = _mm_cvtsi32_si128( hi );
6559       __m128i xl = _mm_cvtsi32_si128( lo );
6560
6561       // Combine into low half of a single xmm register.
6562       __m128i x = _mm_unpacklo_epi32( xh, xl );
6563       __m128d d;
6564       double sd;
6565
6566       // Merge in appropriate exponents to give the integer bits the right
6567       // magnitude.
6568       x = _mm_unpacklo_epi32( x, exp );
6569
6570       // Subtract away the biases to deal with the IEEE-754 double precision
6571       // implicit 1.
6572       d = _mm_sub_pd( (__m128d) x, bias );
6573
6574       // All conversions up to here are exact. The correctly rounded result is
6575       // calculated using the current rounding mode using the following
6576       // horizontal add.
6577       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6578       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6579                                 // store doesn't really need to be here (except
6580                                 // maybe to zero the other double)
6581       return sd;
6582     }
6583   */
6584
6585   DebugLoc dl = Op.getDebugLoc();
6586   LLVMContext *Context = DAG.getContext();
6587
6588   // Build some magic constants.
6589   std::vector<Constant*> CV0;
6590   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6591   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6592   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6593   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6594   Constant *C0 = ConstantVector::get(CV0);
6595   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6596
6597   std::vector<Constant*> CV1;
6598   CV1.push_back(
6599     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6600   CV1.push_back(
6601     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6602   Constant *C1 = ConstantVector::get(CV1);
6603   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6604
6605   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6606                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6607                                         Op.getOperand(0),
6608                                         DAG.getIntPtrConstant(1)));
6609   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6610                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6611                                         Op.getOperand(0),
6612                                         DAG.getIntPtrConstant(0)));
6613   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6614   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6615                               MachinePointerInfo::getConstantPool(),
6616                               false, false, 16);
6617   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6618   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6619   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6620                               MachinePointerInfo::getConstantPool(),
6621                               false, false, 16);
6622   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6623
6624   // Add the halves; easiest way is to swap them into another reg first.
6625   int ShufMask[2] = { 1, -1 };
6626   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6627                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6628   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6629   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6630                      DAG.getIntPtrConstant(0));
6631 }
6632
6633 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6634 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6635                                                SelectionDAG &DAG) const {
6636   DebugLoc dl = Op.getDebugLoc();
6637   // FP constant to bias correct the final result.
6638   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6639                                    MVT::f64);
6640
6641   // Load the 32-bit value into an XMM register.
6642   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6643                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6644                                          Op.getOperand(0),
6645                                          DAG.getIntPtrConstant(0)));
6646
6647   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6648                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6649                      DAG.getIntPtrConstant(0));
6650
6651   // Or the load with the bias.
6652   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6653                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6654                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6655                                                    MVT::v2f64, Load)),
6656                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6657                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6658                                                    MVT::v2f64, Bias)));
6659   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6660                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6661                    DAG.getIntPtrConstant(0));
6662
6663   // Subtract the bias.
6664   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6665
6666   // Handle final rounding.
6667   EVT DestVT = Op.getValueType();
6668
6669   if (DestVT.bitsLT(MVT::f64)) {
6670     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6671                        DAG.getIntPtrConstant(0));
6672   } else if (DestVT.bitsGT(MVT::f64)) {
6673     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6674   }
6675
6676   // Handle final rounding.
6677   return Sub;
6678 }
6679
6680 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6681                                            SelectionDAG &DAG) const {
6682   SDValue N0 = Op.getOperand(0);
6683   DebugLoc dl = Op.getDebugLoc();
6684
6685   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6686   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6687   // the optimization here.
6688   if (DAG.SignBitIsZero(N0))
6689     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6690
6691   EVT SrcVT = N0.getValueType();
6692   EVT DstVT = Op.getValueType();
6693   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6694     return LowerUINT_TO_FP_i64(Op, DAG);
6695   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6696     return LowerUINT_TO_FP_i32(Op, DAG);
6697
6698   // Make a 64-bit buffer, and use it to build an FILD.
6699   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6700   if (SrcVT == MVT::i32) {
6701     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6702     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6703                                      getPointerTy(), StackSlot, WordOff);
6704     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6705                                   StackSlot, MachinePointerInfo(),
6706                                   false, false, 0);
6707     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6708                                   OffsetSlot, MachinePointerInfo(),
6709                                   false, false, 0);
6710     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6711     return Fild;
6712   }
6713
6714   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6715   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6716                                 StackSlot, MachinePointerInfo(),
6717                                false, false, 0);
6718   // For i64 source, we need to add the appropriate power of 2 if the input
6719   // was negative.  This is the same as the optimization in
6720   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6721   // we must be careful to do the computation in x87 extended precision, not
6722   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6723   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6724   MachineMemOperand *MMO =
6725     DAG.getMachineFunction()
6726     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6727                           MachineMemOperand::MOLoad, 8, 8);
6728
6729   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6730   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6731   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6732                                          MVT::i64, MMO);
6733
6734   APInt FF(32, 0x5F800000ULL);
6735
6736   // Check whether the sign bit is set.
6737   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6738                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6739                                  ISD::SETLT);
6740
6741   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6742   SDValue FudgePtr = DAG.getConstantPool(
6743                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6744                                          getPointerTy());
6745
6746   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6747   SDValue Zero = DAG.getIntPtrConstant(0);
6748   SDValue Four = DAG.getIntPtrConstant(4);
6749   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6750                                Zero, Four);
6751   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6752
6753   // Load the value out, extending it from f32 to f80.
6754   // FIXME: Avoid the extend by constructing the right constant pool?
6755   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6756                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6757                                  MVT::f32, false, false, 4);
6758   // Extend everything to 80 bits to force it to be done on x87.
6759   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6760   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6761 }
6762
6763 std::pair<SDValue,SDValue> X86TargetLowering::
6764 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6765   DebugLoc DL = Op.getDebugLoc();
6766
6767   EVT DstTy = Op.getValueType();
6768
6769   if (!IsSigned) {
6770     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6771     DstTy = MVT::i64;
6772   }
6773
6774   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6775          DstTy.getSimpleVT() >= MVT::i16 &&
6776          "Unknown FP_TO_SINT to lower!");
6777
6778   // These are really Legal.
6779   if (DstTy == MVT::i32 &&
6780       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6781     return std::make_pair(SDValue(), SDValue());
6782   if (Subtarget->is64Bit() &&
6783       DstTy == MVT::i64 &&
6784       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6785     return std::make_pair(SDValue(), SDValue());
6786
6787   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6788   // stack slot.
6789   MachineFunction &MF = DAG.getMachineFunction();
6790   unsigned MemSize = DstTy.getSizeInBits()/8;
6791   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6792   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6793
6794
6795
6796   unsigned Opc;
6797   switch (DstTy.getSimpleVT().SimpleTy) {
6798   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6799   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6800   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6801   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6802   }
6803
6804   SDValue Chain = DAG.getEntryNode();
6805   SDValue Value = Op.getOperand(0);
6806   EVT TheVT = Op.getOperand(0).getValueType();
6807   if (isScalarFPTypeInSSEReg(TheVT)) {
6808     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6809     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6810                          MachinePointerInfo::getFixedStack(SSFI),
6811                          false, false, 0);
6812     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6813     SDValue Ops[] = {
6814       Chain, StackSlot, DAG.getValueType(TheVT)
6815     };
6816
6817     MachineMemOperand *MMO =
6818       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6819                               MachineMemOperand::MOLoad, MemSize, MemSize);
6820     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6821                                     DstTy, MMO);
6822     Chain = Value.getValue(1);
6823     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6824     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6825   }
6826
6827   MachineMemOperand *MMO =
6828     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6829                             MachineMemOperand::MOStore, MemSize, MemSize);
6830
6831   // Build the FP_TO_INT*_IN_MEM
6832   SDValue Ops[] = { Chain, Value, StackSlot };
6833   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6834                                          Ops, 3, DstTy, MMO);
6835
6836   return std::make_pair(FIST, StackSlot);
6837 }
6838
6839 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6840                                            SelectionDAG &DAG) const {
6841   if (Op.getValueType().isVector())
6842     return SDValue();
6843
6844   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6845   SDValue FIST = Vals.first, StackSlot = Vals.second;
6846   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6847   if (FIST.getNode() == 0) return Op;
6848
6849   // Load the result.
6850   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6851                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6852 }
6853
6854 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6855                                            SelectionDAG &DAG) const {
6856   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6857   SDValue FIST = Vals.first, StackSlot = Vals.second;
6858   assert(FIST.getNode() && "Unexpected failure");
6859
6860   // Load the result.
6861   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6862                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6863 }
6864
6865 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6866                                      SelectionDAG &DAG) const {
6867   LLVMContext *Context = DAG.getContext();
6868   DebugLoc dl = Op.getDebugLoc();
6869   EVT VT = Op.getValueType();
6870   EVT EltVT = VT;
6871   if (VT.isVector())
6872     EltVT = VT.getVectorElementType();
6873   std::vector<Constant*> CV;
6874   if (EltVT == MVT::f64) {
6875     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6876     CV.push_back(C);
6877     CV.push_back(C);
6878   } else {
6879     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6880     CV.push_back(C);
6881     CV.push_back(C);
6882     CV.push_back(C);
6883     CV.push_back(C);
6884   }
6885   Constant *C = ConstantVector::get(CV);
6886   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6887   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6888                              MachinePointerInfo::getConstantPool(),
6889                              false, false, 16);
6890   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6891 }
6892
6893 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6894   LLVMContext *Context = DAG.getContext();
6895   DebugLoc dl = Op.getDebugLoc();
6896   EVT VT = Op.getValueType();
6897   EVT EltVT = VT;
6898   if (VT.isVector())
6899     EltVT = VT.getVectorElementType();
6900   std::vector<Constant*> CV;
6901   if (EltVT == MVT::f64) {
6902     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6903     CV.push_back(C);
6904     CV.push_back(C);
6905   } else {
6906     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6907     CV.push_back(C);
6908     CV.push_back(C);
6909     CV.push_back(C);
6910     CV.push_back(C);
6911   }
6912   Constant *C = ConstantVector::get(CV);
6913   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6914   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6915                              MachinePointerInfo::getConstantPool(),
6916                              false, false, 16);
6917   if (VT.isVector()) {
6918     return DAG.getNode(ISD::BITCAST, dl, VT,
6919                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6920                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6921                                 Op.getOperand(0)),
6922                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6923   } else {
6924     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6925   }
6926 }
6927
6928 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6929   LLVMContext *Context = DAG.getContext();
6930   SDValue Op0 = Op.getOperand(0);
6931   SDValue Op1 = Op.getOperand(1);
6932   DebugLoc dl = Op.getDebugLoc();
6933   EVT VT = Op.getValueType();
6934   EVT SrcVT = Op1.getValueType();
6935
6936   // If second operand is smaller, extend it first.
6937   if (SrcVT.bitsLT(VT)) {
6938     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6939     SrcVT = VT;
6940   }
6941   // And if it is bigger, shrink it first.
6942   if (SrcVT.bitsGT(VT)) {
6943     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6944     SrcVT = VT;
6945   }
6946
6947   // At this point the operands and the result should have the same
6948   // type, and that won't be f80 since that is not custom lowered.
6949
6950   // First get the sign bit of second operand.
6951   std::vector<Constant*> CV;
6952   if (SrcVT == MVT::f64) {
6953     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6954     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6955   } else {
6956     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6957     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6958     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6959     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6960   }
6961   Constant *C = ConstantVector::get(CV);
6962   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6963   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6964                               MachinePointerInfo::getConstantPool(),
6965                               false, false, 16);
6966   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6967
6968   // Shift sign bit right or left if the two operands have different types.
6969   if (SrcVT.bitsGT(VT)) {
6970     // Op0 is MVT::f32, Op1 is MVT::f64.
6971     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6972     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6973                           DAG.getConstant(32, MVT::i32));
6974     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6975     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6976                           DAG.getIntPtrConstant(0));
6977   }
6978
6979   // Clear first operand sign bit.
6980   CV.clear();
6981   if (VT == MVT::f64) {
6982     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6983     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6984   } else {
6985     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6986     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6987     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6988     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6989   }
6990   C = ConstantVector::get(CV);
6991   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6992   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6993                               MachinePointerInfo::getConstantPool(),
6994                               false, false, 16);
6995   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6996
6997   // Or the value with the sign bit.
6998   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6999 }
7000
7001 /// Emit nodes that will be selected as "test Op0,Op0", or something
7002 /// equivalent.
7003 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7004                                     SelectionDAG &DAG) const {
7005   DebugLoc dl = Op.getDebugLoc();
7006
7007   // CF and OF aren't always set the way we want. Determine which
7008   // of these we need.
7009   bool NeedCF = false;
7010   bool NeedOF = false;
7011   switch (X86CC) {
7012   default: break;
7013   case X86::COND_A: case X86::COND_AE:
7014   case X86::COND_B: case X86::COND_BE:
7015     NeedCF = true;
7016     break;
7017   case X86::COND_G: case X86::COND_GE:
7018   case X86::COND_L: case X86::COND_LE:
7019   case X86::COND_O: case X86::COND_NO:
7020     NeedOF = true;
7021     break;
7022   }
7023
7024   // See if we can use the EFLAGS value from the operand instead of
7025   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7026   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7027   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7028     // Emit a CMP with 0, which is the TEST pattern.
7029     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7030                        DAG.getConstant(0, Op.getValueType()));
7031
7032   unsigned Opcode = 0;
7033   unsigned NumOperands = 0;
7034   switch (Op.getNode()->getOpcode()) {
7035   case ISD::ADD:
7036     // Due to an isel shortcoming, be conservative if this add is likely to be
7037     // selected as part of a load-modify-store instruction. When the root node
7038     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7039     // uses of other nodes in the match, such as the ADD in this case. This
7040     // leads to the ADD being left around and reselected, with the result being
7041     // two adds in the output.  Alas, even if none our users are stores, that
7042     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7043     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7044     // climbing the DAG back to the root, and it doesn't seem to be worth the
7045     // effort.
7046     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7047            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7048       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7049         goto default_case;
7050
7051     if (ConstantSDNode *C =
7052         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7053       // An add of one will be selected as an INC.
7054       if (C->getAPIntValue() == 1) {
7055         Opcode = X86ISD::INC;
7056         NumOperands = 1;
7057         break;
7058       }
7059
7060       // An add of negative one (subtract of one) will be selected as a DEC.
7061       if (C->getAPIntValue().isAllOnesValue()) {
7062         Opcode = X86ISD::DEC;
7063         NumOperands = 1;
7064         break;
7065       }
7066     }
7067
7068     // Otherwise use a regular EFLAGS-setting add.
7069     Opcode = X86ISD::ADD;
7070     NumOperands = 2;
7071     break;
7072   case ISD::AND: {
7073     // If the primary and result isn't used, don't bother using X86ISD::AND,
7074     // because a TEST instruction will be better.
7075     bool NonFlagUse = false;
7076     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7077            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7078       SDNode *User = *UI;
7079       unsigned UOpNo = UI.getOperandNo();
7080       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7081         // Look pass truncate.
7082         UOpNo = User->use_begin().getOperandNo();
7083         User = *User->use_begin();
7084       }
7085
7086       if (User->getOpcode() != ISD::BRCOND &&
7087           User->getOpcode() != ISD::SETCC &&
7088           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7089         NonFlagUse = true;
7090         break;
7091       }
7092     }
7093
7094     if (!NonFlagUse)
7095       break;
7096   }
7097     // FALL THROUGH
7098   case ISD::SUB:
7099   case ISD::OR:
7100   case ISD::XOR:
7101     // Due to the ISEL shortcoming noted above, be conservative if this op is
7102     // likely to be selected as part of a load-modify-store instruction.
7103     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7104            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7105       if (UI->getOpcode() == ISD::STORE)
7106         goto default_case;
7107
7108     // Otherwise use a regular EFLAGS-setting instruction.
7109     switch (Op.getNode()->getOpcode()) {
7110     default: llvm_unreachable("unexpected operator!");
7111     case ISD::SUB: Opcode = X86ISD::SUB; break;
7112     case ISD::OR:  Opcode = X86ISD::OR;  break;
7113     case ISD::XOR: Opcode = X86ISD::XOR; break;
7114     case ISD::AND: Opcode = X86ISD::AND; break;
7115     }
7116
7117     NumOperands = 2;
7118     break;
7119   case X86ISD::ADD:
7120   case X86ISD::SUB:
7121   case X86ISD::INC:
7122   case X86ISD::DEC:
7123   case X86ISD::OR:
7124   case X86ISD::XOR:
7125   case X86ISD::AND:
7126     return SDValue(Op.getNode(), 1);
7127   default:
7128   default_case:
7129     break;
7130   }
7131
7132   if (Opcode == 0)
7133     // Emit a CMP with 0, which is the TEST pattern.
7134     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7135                        DAG.getConstant(0, Op.getValueType()));
7136
7137   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7138   SmallVector<SDValue, 4> Ops;
7139   for (unsigned i = 0; i != NumOperands; ++i)
7140     Ops.push_back(Op.getOperand(i));
7141
7142   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7143   DAG.ReplaceAllUsesWith(Op, New);
7144   return SDValue(New.getNode(), 1);
7145 }
7146
7147 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7148 /// equivalent.
7149 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7150                                    SelectionDAG &DAG) const {
7151   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7152     if (C->getAPIntValue() == 0)
7153       return EmitTest(Op0, X86CC, DAG);
7154
7155   DebugLoc dl = Op0.getDebugLoc();
7156   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7157 }
7158
7159 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7160 /// if it's possible.
7161 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7162                                      DebugLoc dl, SelectionDAG &DAG) const {
7163   SDValue Op0 = And.getOperand(0);
7164   SDValue Op1 = And.getOperand(1);
7165   if (Op0.getOpcode() == ISD::TRUNCATE)
7166     Op0 = Op0.getOperand(0);
7167   if (Op1.getOpcode() == ISD::TRUNCATE)
7168     Op1 = Op1.getOperand(0);
7169
7170   SDValue LHS, RHS;
7171   if (Op1.getOpcode() == ISD::SHL)
7172     std::swap(Op0, Op1);
7173   if (Op0.getOpcode() == ISD::SHL) {
7174     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7175       if (And00C->getZExtValue() == 1) {
7176         // If we looked past a truncate, check that it's only truncating away
7177         // known zeros.
7178         unsigned BitWidth = Op0.getValueSizeInBits();
7179         unsigned AndBitWidth = And.getValueSizeInBits();
7180         if (BitWidth > AndBitWidth) {
7181           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7182           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7183           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7184             return SDValue();
7185         }
7186         LHS = Op1;
7187         RHS = Op0.getOperand(1);
7188       }
7189   } else if (Op1.getOpcode() == ISD::Constant) {
7190     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7191     SDValue AndLHS = Op0;
7192     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7193       LHS = AndLHS.getOperand(0);
7194       RHS = AndLHS.getOperand(1);
7195     }
7196   }
7197
7198   if (LHS.getNode()) {
7199     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7200     // instruction.  Since the shift amount is in-range-or-undefined, we know
7201     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7202     // the encoding for the i16 version is larger than the i32 version.
7203     // Also promote i16 to i32 for performance / code size reason.
7204     if (LHS.getValueType() == MVT::i8 ||
7205         LHS.getValueType() == MVT::i16)
7206       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7207
7208     // If the operand types disagree, extend the shift amount to match.  Since
7209     // BT ignores high bits (like shifts) we can use anyextend.
7210     if (LHS.getValueType() != RHS.getValueType())
7211       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7212
7213     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7214     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7215     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7216                        DAG.getConstant(Cond, MVT::i8), BT);
7217   }
7218
7219   return SDValue();
7220 }
7221
7222 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7223   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7224   SDValue Op0 = Op.getOperand(0);
7225   SDValue Op1 = Op.getOperand(1);
7226   DebugLoc dl = Op.getDebugLoc();
7227   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7228
7229   // Optimize to BT if possible.
7230   // Lower (X & (1 << N)) == 0 to BT(X, N).
7231   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7232   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7233   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7234       Op1.getOpcode() == ISD::Constant &&
7235       cast<ConstantSDNode>(Op1)->isNullValue() &&
7236       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7237     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7238     if (NewSetCC.getNode())
7239       return NewSetCC;
7240   }
7241
7242   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7243   // these.
7244   if (Op1.getOpcode() == ISD::Constant &&
7245       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7246        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7247       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7248
7249     // If the input is a setcc, then reuse the input setcc or use a new one with
7250     // the inverted condition.
7251     if (Op0.getOpcode() == X86ISD::SETCC) {
7252       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7253       bool Invert = (CC == ISD::SETNE) ^
7254         cast<ConstantSDNode>(Op1)->isNullValue();
7255       if (!Invert) return Op0;
7256
7257       CCode = X86::GetOppositeBranchCondition(CCode);
7258       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7259                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7260     }
7261   }
7262
7263   bool isFP = Op1.getValueType().isFloatingPoint();
7264   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7265   if (X86CC == X86::COND_INVALID)
7266     return SDValue();
7267
7268   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7269   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7270                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7271 }
7272
7273 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7274   SDValue Cond;
7275   SDValue Op0 = Op.getOperand(0);
7276   SDValue Op1 = Op.getOperand(1);
7277   SDValue CC = Op.getOperand(2);
7278   EVT VT = Op.getValueType();
7279   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7280   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7281   DebugLoc dl = Op.getDebugLoc();
7282
7283   if (isFP) {
7284     unsigned SSECC = 8;
7285     EVT VT0 = Op0.getValueType();
7286     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7287     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7288     bool Swap = false;
7289
7290     switch (SetCCOpcode) {
7291     default: break;
7292     case ISD::SETOEQ:
7293     case ISD::SETEQ:  SSECC = 0; break;
7294     case ISD::SETOGT:
7295     case ISD::SETGT: Swap = true; // Fallthrough
7296     case ISD::SETLT:
7297     case ISD::SETOLT: SSECC = 1; break;
7298     case ISD::SETOGE:
7299     case ISD::SETGE: Swap = true; // Fallthrough
7300     case ISD::SETLE:
7301     case ISD::SETOLE: SSECC = 2; break;
7302     case ISD::SETUO:  SSECC = 3; break;
7303     case ISD::SETUNE:
7304     case ISD::SETNE:  SSECC = 4; break;
7305     case ISD::SETULE: Swap = true;
7306     case ISD::SETUGE: SSECC = 5; break;
7307     case ISD::SETULT: Swap = true;
7308     case ISD::SETUGT: SSECC = 6; break;
7309     case ISD::SETO:   SSECC = 7; break;
7310     }
7311     if (Swap)
7312       std::swap(Op0, Op1);
7313
7314     // In the two special cases we can't handle, emit two comparisons.
7315     if (SSECC == 8) {
7316       if (SetCCOpcode == ISD::SETUEQ) {
7317         SDValue UNORD, EQ;
7318         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7319         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7320         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7321       }
7322       else if (SetCCOpcode == ISD::SETONE) {
7323         SDValue ORD, NEQ;
7324         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7325         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7326         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7327       }
7328       llvm_unreachable("Illegal FP comparison");
7329     }
7330     // Handle all other FP comparisons here.
7331     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7332   }
7333
7334   // We are handling one of the integer comparisons here.  Since SSE only has
7335   // GT and EQ comparisons for integer, swapping operands and multiple
7336   // operations may be required for some comparisons.
7337   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7338   bool Swap = false, Invert = false, FlipSigns = false;
7339
7340   switch (VT.getSimpleVT().SimpleTy) {
7341   default: break;
7342   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7343   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7344   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7345   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7346   }
7347
7348   switch (SetCCOpcode) {
7349   default: break;
7350   case ISD::SETNE:  Invert = true;
7351   case ISD::SETEQ:  Opc = EQOpc; break;
7352   case ISD::SETLT:  Swap = true;
7353   case ISD::SETGT:  Opc = GTOpc; break;
7354   case ISD::SETGE:  Swap = true;
7355   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7356   case ISD::SETULT: Swap = true;
7357   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7358   case ISD::SETUGE: Swap = true;
7359   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7360   }
7361   if (Swap)
7362     std::swap(Op0, Op1);
7363
7364   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7365   // bits of the inputs before performing those operations.
7366   if (FlipSigns) {
7367     EVT EltVT = VT.getVectorElementType();
7368     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7369                                       EltVT);
7370     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7371     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7372                                     SignBits.size());
7373     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7374     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7375   }
7376
7377   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7378
7379   // If the logical-not of the result is required, perform that now.
7380   if (Invert)
7381     Result = DAG.getNOT(dl, Result, VT);
7382
7383   return Result;
7384 }
7385
7386 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7387 static bool isX86LogicalCmp(SDValue Op) {
7388   unsigned Opc = Op.getNode()->getOpcode();
7389   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7390     return true;
7391   if (Op.getResNo() == 1 &&
7392       (Opc == X86ISD::ADD ||
7393        Opc == X86ISD::SUB ||
7394        Opc == X86ISD::ADC ||
7395        Opc == X86ISD::SBB ||
7396        Opc == X86ISD::SMUL ||
7397        Opc == X86ISD::UMUL ||
7398        Opc == X86ISD::INC ||
7399        Opc == X86ISD::DEC ||
7400        Opc == X86ISD::OR ||
7401        Opc == X86ISD::XOR ||
7402        Opc == X86ISD::AND))
7403     return true;
7404
7405   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7406     return true;
7407
7408   return false;
7409 }
7410
7411 static bool isZero(SDValue V) {
7412   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7413   return C && C->isNullValue();
7414 }
7415
7416 static bool isAllOnes(SDValue V) {
7417   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7418   return C && C->isAllOnesValue();
7419 }
7420
7421 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7422   bool addTest = true;
7423   SDValue Cond  = Op.getOperand(0);
7424   SDValue Op1 = Op.getOperand(1);
7425   SDValue Op2 = Op.getOperand(2);
7426   DebugLoc DL = Op.getDebugLoc();
7427   SDValue CC;
7428
7429   if (Cond.getOpcode() == ISD::SETCC) {
7430     SDValue NewCond = LowerSETCC(Cond, DAG);
7431     if (NewCond.getNode())
7432       Cond = NewCond;
7433   }
7434
7435   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7436   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7437   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7438   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7439   if (Cond.getOpcode() == X86ISD::SETCC &&
7440       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7441       isZero(Cond.getOperand(1).getOperand(1))) {
7442     SDValue Cmp = Cond.getOperand(1);
7443
7444     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7445
7446     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7447         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7448       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7449
7450       SDValue CmpOp0 = Cmp.getOperand(0);
7451       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7452                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7453
7454       SDValue Res =   // Res = 0 or -1.
7455         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7456                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7457
7458       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7459         Res = DAG.getNOT(DL, Res, Res.getValueType());
7460
7461       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7462       if (N2C == 0 || !N2C->isNullValue())
7463         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7464       return Res;
7465     }
7466   }
7467
7468   // Look past (and (setcc_carry (cmp ...)), 1).
7469   if (Cond.getOpcode() == ISD::AND &&
7470       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7471     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7472     if (C && C->getAPIntValue() == 1)
7473       Cond = Cond.getOperand(0);
7474   }
7475
7476   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7477   // setting operand in place of the X86ISD::SETCC.
7478   if (Cond.getOpcode() == X86ISD::SETCC ||
7479       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7480     CC = Cond.getOperand(0);
7481
7482     SDValue Cmp = Cond.getOperand(1);
7483     unsigned Opc = Cmp.getOpcode();
7484     EVT VT = Op.getValueType();
7485
7486     bool IllegalFPCMov = false;
7487     if (VT.isFloatingPoint() && !VT.isVector() &&
7488         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7489       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7490
7491     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7492         Opc == X86ISD::BT) { // FIXME
7493       Cond = Cmp;
7494       addTest = false;
7495     }
7496   }
7497
7498   if (addTest) {
7499     // Look pass the truncate.
7500     if (Cond.getOpcode() == ISD::TRUNCATE)
7501       Cond = Cond.getOperand(0);
7502
7503     // We know the result of AND is compared against zero. Try to match
7504     // it to BT.
7505     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7506       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7507       if (NewSetCC.getNode()) {
7508         CC = NewSetCC.getOperand(0);
7509         Cond = NewSetCC.getOperand(1);
7510         addTest = false;
7511       }
7512     }
7513   }
7514
7515   if (addTest) {
7516     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7517     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7518   }
7519
7520   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7521   // a <  b ?  0 : -1 -> RES = setcc_carry
7522   // a >= b ? -1 :  0 -> RES = setcc_carry
7523   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7524   if (Cond.getOpcode() == X86ISD::CMP) {
7525     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7526
7527     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7528         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7529       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7530                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7531       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7532         return DAG.getNOT(DL, Res, Res.getValueType());
7533       return Res;
7534     }
7535   }
7536
7537   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7538   // condition is true.
7539   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7540   SDValue Ops[] = { Op2, Op1, CC, Cond };
7541   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7542 }
7543
7544 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7545 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7546 // from the AND / OR.
7547 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7548   Opc = Op.getOpcode();
7549   if (Opc != ISD::OR && Opc != ISD::AND)
7550     return false;
7551   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7552           Op.getOperand(0).hasOneUse() &&
7553           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7554           Op.getOperand(1).hasOneUse());
7555 }
7556
7557 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7558 // 1 and that the SETCC node has a single use.
7559 static bool isXor1OfSetCC(SDValue Op) {
7560   if (Op.getOpcode() != ISD::XOR)
7561     return false;
7562   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7563   if (N1C && N1C->getAPIntValue() == 1) {
7564     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7565       Op.getOperand(0).hasOneUse();
7566   }
7567   return false;
7568 }
7569
7570 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7571   bool addTest = true;
7572   SDValue Chain = Op.getOperand(0);
7573   SDValue Cond  = Op.getOperand(1);
7574   SDValue Dest  = Op.getOperand(2);
7575   DebugLoc dl = Op.getDebugLoc();
7576   SDValue CC;
7577
7578   if (Cond.getOpcode() == ISD::SETCC) {
7579     SDValue NewCond = LowerSETCC(Cond, DAG);
7580     if (NewCond.getNode())
7581       Cond = NewCond;
7582   }
7583 #if 0
7584   // FIXME: LowerXALUO doesn't handle these!!
7585   else if (Cond.getOpcode() == X86ISD::ADD  ||
7586            Cond.getOpcode() == X86ISD::SUB  ||
7587            Cond.getOpcode() == X86ISD::SMUL ||
7588            Cond.getOpcode() == X86ISD::UMUL)
7589     Cond = LowerXALUO(Cond, DAG);
7590 #endif
7591
7592   // Look pass (and (setcc_carry (cmp ...)), 1).
7593   if (Cond.getOpcode() == ISD::AND &&
7594       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7595     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7596     if (C && C->getAPIntValue() == 1)
7597       Cond = Cond.getOperand(0);
7598   }
7599
7600   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7601   // setting operand in place of the X86ISD::SETCC.
7602   if (Cond.getOpcode() == X86ISD::SETCC ||
7603       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7604     CC = Cond.getOperand(0);
7605
7606     SDValue Cmp = Cond.getOperand(1);
7607     unsigned Opc = Cmp.getOpcode();
7608     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7609     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7610       Cond = Cmp;
7611       addTest = false;
7612     } else {
7613       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7614       default: break;
7615       case X86::COND_O:
7616       case X86::COND_B:
7617         // These can only come from an arithmetic instruction with overflow,
7618         // e.g. SADDO, UADDO.
7619         Cond = Cond.getNode()->getOperand(1);
7620         addTest = false;
7621         break;
7622       }
7623     }
7624   } else {
7625     unsigned CondOpc;
7626     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7627       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7628       if (CondOpc == ISD::OR) {
7629         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7630         // two branches instead of an explicit OR instruction with a
7631         // separate test.
7632         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7633             isX86LogicalCmp(Cmp)) {
7634           CC = Cond.getOperand(0).getOperand(0);
7635           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7636                               Chain, Dest, CC, Cmp);
7637           CC = Cond.getOperand(1).getOperand(0);
7638           Cond = Cmp;
7639           addTest = false;
7640         }
7641       } else { // ISD::AND
7642         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7643         // two branches instead of an explicit AND instruction with a
7644         // separate test. However, we only do this if this block doesn't
7645         // have a fall-through edge, because this requires an explicit
7646         // jmp when the condition is false.
7647         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7648             isX86LogicalCmp(Cmp) &&
7649             Op.getNode()->hasOneUse()) {
7650           X86::CondCode CCode =
7651             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7652           CCode = X86::GetOppositeBranchCondition(CCode);
7653           CC = DAG.getConstant(CCode, MVT::i8);
7654           SDNode *User = *Op.getNode()->use_begin();
7655           // Look for an unconditional branch following this conditional branch.
7656           // We need this because we need to reverse the successors in order
7657           // to implement FCMP_OEQ.
7658           if (User->getOpcode() == ISD::BR) {
7659             SDValue FalseBB = User->getOperand(1);
7660             SDNode *NewBR =
7661               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7662             assert(NewBR == User);
7663             (void)NewBR;
7664             Dest = FalseBB;
7665
7666             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7667                                 Chain, Dest, CC, Cmp);
7668             X86::CondCode CCode =
7669               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7670             CCode = X86::GetOppositeBranchCondition(CCode);
7671             CC = DAG.getConstant(CCode, MVT::i8);
7672             Cond = Cmp;
7673             addTest = false;
7674           }
7675         }
7676       }
7677     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7678       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7679       // It should be transformed during dag combiner except when the condition
7680       // is set by a arithmetics with overflow node.
7681       X86::CondCode CCode =
7682         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7683       CCode = X86::GetOppositeBranchCondition(CCode);
7684       CC = DAG.getConstant(CCode, MVT::i8);
7685       Cond = Cond.getOperand(0).getOperand(1);
7686       addTest = false;
7687     }
7688   }
7689
7690   if (addTest) {
7691     // Look pass the truncate.
7692     if (Cond.getOpcode() == ISD::TRUNCATE)
7693       Cond = Cond.getOperand(0);
7694
7695     // We know the result of AND is compared against zero. Try to match
7696     // it to BT.
7697     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7698       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7699       if (NewSetCC.getNode()) {
7700         CC = NewSetCC.getOperand(0);
7701         Cond = NewSetCC.getOperand(1);
7702         addTest = false;
7703       }
7704     }
7705   }
7706
7707   if (addTest) {
7708     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7709     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7710   }
7711   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7712                      Chain, Dest, CC, Cond);
7713 }
7714
7715
7716 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7717 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7718 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7719 // that the guard pages used by the OS virtual memory manager are allocated in
7720 // correct sequence.
7721 SDValue
7722 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7723                                            SelectionDAG &DAG) const {
7724   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7725          "This should be used only on Windows targets");
7726   DebugLoc dl = Op.getDebugLoc();
7727
7728   // Get the inputs.
7729   SDValue Chain = Op.getOperand(0);
7730   SDValue Size  = Op.getOperand(1);
7731   // FIXME: Ensure alignment here
7732
7733   SDValue Flag;
7734
7735   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7736
7737   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7738   Flag = Chain.getValue(1);
7739
7740   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7741
7742   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7743   Flag = Chain.getValue(1);
7744
7745   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7746
7747   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7748   return DAG.getMergeValues(Ops1, 2, dl);
7749 }
7750
7751 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7752   MachineFunction &MF = DAG.getMachineFunction();
7753   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7754
7755   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7756   DebugLoc DL = Op.getDebugLoc();
7757
7758   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7759     // vastart just stores the address of the VarArgsFrameIndex slot into the
7760     // memory location argument.
7761     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7762                                    getPointerTy());
7763     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7764                         MachinePointerInfo(SV), false, false, 0);
7765   }
7766
7767   // __va_list_tag:
7768   //   gp_offset         (0 - 6 * 8)
7769   //   fp_offset         (48 - 48 + 8 * 16)
7770   //   overflow_arg_area (point to parameters coming in memory).
7771   //   reg_save_area
7772   SmallVector<SDValue, 8> MemOps;
7773   SDValue FIN = Op.getOperand(1);
7774   // Store gp_offset
7775   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7776                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7777                                                MVT::i32),
7778                                FIN, MachinePointerInfo(SV), false, false, 0);
7779   MemOps.push_back(Store);
7780
7781   // Store fp_offset
7782   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7783                     FIN, DAG.getIntPtrConstant(4));
7784   Store = DAG.getStore(Op.getOperand(0), DL,
7785                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7786                                        MVT::i32),
7787                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7788   MemOps.push_back(Store);
7789
7790   // Store ptr to overflow_arg_area
7791   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7792                     FIN, DAG.getIntPtrConstant(4));
7793   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7794                                     getPointerTy());
7795   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7796                        MachinePointerInfo(SV, 8),
7797                        false, false, 0);
7798   MemOps.push_back(Store);
7799
7800   // Store ptr to reg_save_area.
7801   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7802                     FIN, DAG.getIntPtrConstant(8));
7803   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7804                                     getPointerTy());
7805   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7806                        MachinePointerInfo(SV, 16), false, false, 0);
7807   MemOps.push_back(Store);
7808   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7809                      &MemOps[0], MemOps.size());
7810 }
7811
7812 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7813   assert(Subtarget->is64Bit() &&
7814          "LowerVAARG only handles 64-bit va_arg!");
7815   assert((Subtarget->isTargetLinux() ||
7816           Subtarget->isTargetDarwin()) &&
7817           "Unhandled target in LowerVAARG");
7818   assert(Op.getNode()->getNumOperands() == 4);
7819   SDValue Chain = Op.getOperand(0);
7820   SDValue SrcPtr = Op.getOperand(1);
7821   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7822   unsigned Align = Op.getConstantOperandVal(3);
7823   DebugLoc dl = Op.getDebugLoc();
7824
7825   EVT ArgVT = Op.getNode()->getValueType(0);
7826   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7827   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7828   uint8_t ArgMode;
7829
7830   // Decide which area this value should be read from.
7831   // TODO: Implement the AMD64 ABI in its entirety. This simple
7832   // selection mechanism works only for the basic types.
7833   if (ArgVT == MVT::f80) {
7834     llvm_unreachable("va_arg for f80 not yet implemented");
7835   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7836     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7837   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7838     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7839   } else {
7840     llvm_unreachable("Unhandled argument type in LowerVAARG");
7841   }
7842
7843   if (ArgMode == 2) {
7844     // Sanity Check: Make sure using fp_offset makes sense.
7845     assert(!UseSoftFloat &&
7846            !(DAG.getMachineFunction()
7847                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7848            Subtarget->hasXMM());
7849   }
7850
7851   // Insert VAARG_64 node into the DAG
7852   // VAARG_64 returns two values: Variable Argument Address, Chain
7853   SmallVector<SDValue, 11> InstOps;
7854   InstOps.push_back(Chain);
7855   InstOps.push_back(SrcPtr);
7856   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7857   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7858   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7859   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7860   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7861                                           VTs, &InstOps[0], InstOps.size(),
7862                                           MVT::i64,
7863                                           MachinePointerInfo(SV),
7864                                           /*Align=*/0,
7865                                           /*Volatile=*/false,
7866                                           /*ReadMem=*/true,
7867                                           /*WriteMem=*/true);
7868   Chain = VAARG.getValue(1);
7869
7870   // Load the next argument and return it
7871   return DAG.getLoad(ArgVT, dl,
7872                      Chain,
7873                      VAARG,
7874                      MachinePointerInfo(),
7875                      false, false, 0);
7876 }
7877
7878 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7879   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7880   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7881   SDValue Chain = Op.getOperand(0);
7882   SDValue DstPtr = Op.getOperand(1);
7883   SDValue SrcPtr = Op.getOperand(2);
7884   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7885   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7886   DebugLoc DL = Op.getDebugLoc();
7887
7888   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7889                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7890                        false,
7891                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7892 }
7893
7894 SDValue
7895 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7896   DebugLoc dl = Op.getDebugLoc();
7897   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7898   switch (IntNo) {
7899   default: return SDValue();    // Don't custom lower most intrinsics.
7900   // Comparison intrinsics.
7901   case Intrinsic::x86_sse_comieq_ss:
7902   case Intrinsic::x86_sse_comilt_ss:
7903   case Intrinsic::x86_sse_comile_ss:
7904   case Intrinsic::x86_sse_comigt_ss:
7905   case Intrinsic::x86_sse_comige_ss:
7906   case Intrinsic::x86_sse_comineq_ss:
7907   case Intrinsic::x86_sse_ucomieq_ss:
7908   case Intrinsic::x86_sse_ucomilt_ss:
7909   case Intrinsic::x86_sse_ucomile_ss:
7910   case Intrinsic::x86_sse_ucomigt_ss:
7911   case Intrinsic::x86_sse_ucomige_ss:
7912   case Intrinsic::x86_sse_ucomineq_ss:
7913   case Intrinsic::x86_sse2_comieq_sd:
7914   case Intrinsic::x86_sse2_comilt_sd:
7915   case Intrinsic::x86_sse2_comile_sd:
7916   case Intrinsic::x86_sse2_comigt_sd:
7917   case Intrinsic::x86_sse2_comige_sd:
7918   case Intrinsic::x86_sse2_comineq_sd:
7919   case Intrinsic::x86_sse2_ucomieq_sd:
7920   case Intrinsic::x86_sse2_ucomilt_sd:
7921   case Intrinsic::x86_sse2_ucomile_sd:
7922   case Intrinsic::x86_sse2_ucomigt_sd:
7923   case Intrinsic::x86_sse2_ucomige_sd:
7924   case Intrinsic::x86_sse2_ucomineq_sd: {
7925     unsigned Opc = 0;
7926     ISD::CondCode CC = ISD::SETCC_INVALID;
7927     switch (IntNo) {
7928     default: break;
7929     case Intrinsic::x86_sse_comieq_ss:
7930     case Intrinsic::x86_sse2_comieq_sd:
7931       Opc = X86ISD::COMI;
7932       CC = ISD::SETEQ;
7933       break;
7934     case Intrinsic::x86_sse_comilt_ss:
7935     case Intrinsic::x86_sse2_comilt_sd:
7936       Opc = X86ISD::COMI;
7937       CC = ISD::SETLT;
7938       break;
7939     case Intrinsic::x86_sse_comile_ss:
7940     case Intrinsic::x86_sse2_comile_sd:
7941       Opc = X86ISD::COMI;
7942       CC = ISD::SETLE;
7943       break;
7944     case Intrinsic::x86_sse_comigt_ss:
7945     case Intrinsic::x86_sse2_comigt_sd:
7946       Opc = X86ISD::COMI;
7947       CC = ISD::SETGT;
7948       break;
7949     case Intrinsic::x86_sse_comige_ss:
7950     case Intrinsic::x86_sse2_comige_sd:
7951       Opc = X86ISD::COMI;
7952       CC = ISD::SETGE;
7953       break;
7954     case Intrinsic::x86_sse_comineq_ss:
7955     case Intrinsic::x86_sse2_comineq_sd:
7956       Opc = X86ISD::COMI;
7957       CC = ISD::SETNE;
7958       break;
7959     case Intrinsic::x86_sse_ucomieq_ss:
7960     case Intrinsic::x86_sse2_ucomieq_sd:
7961       Opc = X86ISD::UCOMI;
7962       CC = ISD::SETEQ;
7963       break;
7964     case Intrinsic::x86_sse_ucomilt_ss:
7965     case Intrinsic::x86_sse2_ucomilt_sd:
7966       Opc = X86ISD::UCOMI;
7967       CC = ISD::SETLT;
7968       break;
7969     case Intrinsic::x86_sse_ucomile_ss:
7970     case Intrinsic::x86_sse2_ucomile_sd:
7971       Opc = X86ISD::UCOMI;
7972       CC = ISD::SETLE;
7973       break;
7974     case Intrinsic::x86_sse_ucomigt_ss:
7975     case Intrinsic::x86_sse2_ucomigt_sd:
7976       Opc = X86ISD::UCOMI;
7977       CC = ISD::SETGT;
7978       break;
7979     case Intrinsic::x86_sse_ucomige_ss:
7980     case Intrinsic::x86_sse2_ucomige_sd:
7981       Opc = X86ISD::UCOMI;
7982       CC = ISD::SETGE;
7983       break;
7984     case Intrinsic::x86_sse_ucomineq_ss:
7985     case Intrinsic::x86_sse2_ucomineq_sd:
7986       Opc = X86ISD::UCOMI;
7987       CC = ISD::SETNE;
7988       break;
7989     }
7990
7991     SDValue LHS = Op.getOperand(1);
7992     SDValue RHS = Op.getOperand(2);
7993     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7994     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7995     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7996     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7997                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7998     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7999   }
8000   // ptest and testp intrinsics. The intrinsic these come from are designed to
8001   // return an integer value, not just an instruction so lower it to the ptest
8002   // or testp pattern and a setcc for the result.
8003   case Intrinsic::x86_sse41_ptestz:
8004   case Intrinsic::x86_sse41_ptestc:
8005   case Intrinsic::x86_sse41_ptestnzc:
8006   case Intrinsic::x86_avx_ptestz_256:
8007   case Intrinsic::x86_avx_ptestc_256:
8008   case Intrinsic::x86_avx_ptestnzc_256:
8009   case Intrinsic::x86_avx_vtestz_ps:
8010   case Intrinsic::x86_avx_vtestc_ps:
8011   case Intrinsic::x86_avx_vtestnzc_ps:
8012   case Intrinsic::x86_avx_vtestz_pd:
8013   case Intrinsic::x86_avx_vtestc_pd:
8014   case Intrinsic::x86_avx_vtestnzc_pd:
8015   case Intrinsic::x86_avx_vtestz_ps_256:
8016   case Intrinsic::x86_avx_vtestc_ps_256:
8017   case Intrinsic::x86_avx_vtestnzc_ps_256:
8018   case Intrinsic::x86_avx_vtestz_pd_256:
8019   case Intrinsic::x86_avx_vtestc_pd_256:
8020   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8021     bool IsTestPacked = false;
8022     unsigned X86CC = 0;
8023     switch (IntNo) {
8024     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8025     case Intrinsic::x86_avx_vtestz_ps:
8026     case Intrinsic::x86_avx_vtestz_pd:
8027     case Intrinsic::x86_avx_vtestz_ps_256:
8028     case Intrinsic::x86_avx_vtestz_pd_256:
8029       IsTestPacked = true; // Fallthrough
8030     case Intrinsic::x86_sse41_ptestz:
8031     case Intrinsic::x86_avx_ptestz_256:
8032       // ZF = 1
8033       X86CC = X86::COND_E;
8034       break;
8035     case Intrinsic::x86_avx_vtestc_ps:
8036     case Intrinsic::x86_avx_vtestc_pd:
8037     case Intrinsic::x86_avx_vtestc_ps_256:
8038     case Intrinsic::x86_avx_vtestc_pd_256:
8039       IsTestPacked = true; // Fallthrough
8040     case Intrinsic::x86_sse41_ptestc:
8041     case Intrinsic::x86_avx_ptestc_256:
8042       // CF = 1
8043       X86CC = X86::COND_B;
8044       break;
8045     case Intrinsic::x86_avx_vtestnzc_ps:
8046     case Intrinsic::x86_avx_vtestnzc_pd:
8047     case Intrinsic::x86_avx_vtestnzc_ps_256:
8048     case Intrinsic::x86_avx_vtestnzc_pd_256:
8049       IsTestPacked = true; // Fallthrough
8050     case Intrinsic::x86_sse41_ptestnzc:
8051     case Intrinsic::x86_avx_ptestnzc_256:
8052       // ZF and CF = 0
8053       X86CC = X86::COND_A;
8054       break;
8055     }
8056
8057     SDValue LHS = Op.getOperand(1);
8058     SDValue RHS = Op.getOperand(2);
8059     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8060     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8061     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8062     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8063     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8064   }
8065
8066   // Fix vector shift instructions where the last operand is a non-immediate
8067   // i32 value.
8068   case Intrinsic::x86_sse2_pslli_w:
8069   case Intrinsic::x86_sse2_pslli_d:
8070   case Intrinsic::x86_sse2_pslli_q:
8071   case Intrinsic::x86_sse2_psrli_w:
8072   case Intrinsic::x86_sse2_psrli_d:
8073   case Intrinsic::x86_sse2_psrli_q:
8074   case Intrinsic::x86_sse2_psrai_w:
8075   case Intrinsic::x86_sse2_psrai_d:
8076   case Intrinsic::x86_mmx_pslli_w:
8077   case Intrinsic::x86_mmx_pslli_d:
8078   case Intrinsic::x86_mmx_pslli_q:
8079   case Intrinsic::x86_mmx_psrli_w:
8080   case Intrinsic::x86_mmx_psrli_d:
8081   case Intrinsic::x86_mmx_psrli_q:
8082   case Intrinsic::x86_mmx_psrai_w:
8083   case Intrinsic::x86_mmx_psrai_d: {
8084     SDValue ShAmt = Op.getOperand(2);
8085     if (isa<ConstantSDNode>(ShAmt))
8086       return SDValue();
8087
8088     unsigned NewIntNo = 0;
8089     EVT ShAmtVT = MVT::v4i32;
8090     switch (IntNo) {
8091     case Intrinsic::x86_sse2_pslli_w:
8092       NewIntNo = Intrinsic::x86_sse2_psll_w;
8093       break;
8094     case Intrinsic::x86_sse2_pslli_d:
8095       NewIntNo = Intrinsic::x86_sse2_psll_d;
8096       break;
8097     case Intrinsic::x86_sse2_pslli_q:
8098       NewIntNo = Intrinsic::x86_sse2_psll_q;
8099       break;
8100     case Intrinsic::x86_sse2_psrli_w:
8101       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8102       break;
8103     case Intrinsic::x86_sse2_psrli_d:
8104       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8105       break;
8106     case Intrinsic::x86_sse2_psrli_q:
8107       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8108       break;
8109     case Intrinsic::x86_sse2_psrai_w:
8110       NewIntNo = Intrinsic::x86_sse2_psra_w;
8111       break;
8112     case Intrinsic::x86_sse2_psrai_d:
8113       NewIntNo = Intrinsic::x86_sse2_psra_d;
8114       break;
8115     default: {
8116       ShAmtVT = MVT::v2i32;
8117       switch (IntNo) {
8118       case Intrinsic::x86_mmx_pslli_w:
8119         NewIntNo = Intrinsic::x86_mmx_psll_w;
8120         break;
8121       case Intrinsic::x86_mmx_pslli_d:
8122         NewIntNo = Intrinsic::x86_mmx_psll_d;
8123         break;
8124       case Intrinsic::x86_mmx_pslli_q:
8125         NewIntNo = Intrinsic::x86_mmx_psll_q;
8126         break;
8127       case Intrinsic::x86_mmx_psrli_w:
8128         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8129         break;
8130       case Intrinsic::x86_mmx_psrli_d:
8131         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8132         break;
8133       case Intrinsic::x86_mmx_psrli_q:
8134         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8135         break;
8136       case Intrinsic::x86_mmx_psrai_w:
8137         NewIntNo = Intrinsic::x86_mmx_psra_w;
8138         break;
8139       case Intrinsic::x86_mmx_psrai_d:
8140         NewIntNo = Intrinsic::x86_mmx_psra_d;
8141         break;
8142       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8143       }
8144       break;
8145     }
8146     }
8147
8148     // The vector shift intrinsics with scalars uses 32b shift amounts but
8149     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8150     // to be zero.
8151     SDValue ShOps[4];
8152     ShOps[0] = ShAmt;
8153     ShOps[1] = DAG.getConstant(0, MVT::i32);
8154     if (ShAmtVT == MVT::v4i32) {
8155       ShOps[2] = DAG.getUNDEF(MVT::i32);
8156       ShOps[3] = DAG.getUNDEF(MVT::i32);
8157       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8158     } else {
8159       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8160 // FIXME this must be lowered to get rid of the invalid type.
8161     }
8162
8163     EVT VT = Op.getValueType();
8164     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8165     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8166                        DAG.getConstant(NewIntNo, MVT::i32),
8167                        Op.getOperand(1), ShAmt);
8168   }
8169   }
8170 }
8171
8172 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8173                                            SelectionDAG &DAG) const {
8174   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8175   MFI->setReturnAddressIsTaken(true);
8176
8177   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8178   DebugLoc dl = Op.getDebugLoc();
8179
8180   if (Depth > 0) {
8181     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8182     SDValue Offset =
8183       DAG.getConstant(TD->getPointerSize(),
8184                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8185     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8186                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8187                                    FrameAddr, Offset),
8188                        MachinePointerInfo(), false, false, 0);
8189   }
8190
8191   // Just load the return address.
8192   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8193   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8194                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8195 }
8196
8197 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8198   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8199   MFI->setFrameAddressIsTaken(true);
8200
8201   EVT VT = Op.getValueType();
8202   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8203   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8204   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8205   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8206   while (Depth--)
8207     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8208                             MachinePointerInfo(),
8209                             false, false, 0);
8210   return FrameAddr;
8211 }
8212
8213 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8214                                                      SelectionDAG &DAG) const {
8215   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8216 }
8217
8218 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8219   MachineFunction &MF = DAG.getMachineFunction();
8220   SDValue Chain     = Op.getOperand(0);
8221   SDValue Offset    = Op.getOperand(1);
8222   SDValue Handler   = Op.getOperand(2);
8223   DebugLoc dl       = Op.getDebugLoc();
8224
8225   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8226                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8227                                      getPointerTy());
8228   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8229
8230   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8231                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8232   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8233   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8234                        false, false, 0);
8235   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8236   MF.getRegInfo().addLiveOut(StoreAddrReg);
8237
8238   return DAG.getNode(X86ISD::EH_RETURN, dl,
8239                      MVT::Other,
8240                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8241 }
8242
8243 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8244                                              SelectionDAG &DAG) const {
8245   SDValue Root = Op.getOperand(0);
8246   SDValue Trmp = Op.getOperand(1); // trampoline
8247   SDValue FPtr = Op.getOperand(2); // nested function
8248   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8249   DebugLoc dl  = Op.getDebugLoc();
8250
8251   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8252
8253   if (Subtarget->is64Bit()) {
8254     SDValue OutChains[6];
8255
8256     // Large code-model.
8257     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8258     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8259
8260     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8261     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8262
8263     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8264
8265     // Load the pointer to the nested function into R11.
8266     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8267     SDValue Addr = Trmp;
8268     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8269                                 Addr, MachinePointerInfo(TrmpAddr),
8270                                 false, false, 0);
8271
8272     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8273                        DAG.getConstant(2, MVT::i64));
8274     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8275                                 MachinePointerInfo(TrmpAddr, 2),
8276                                 false, false, 2);
8277
8278     // Load the 'nest' parameter value into R10.
8279     // R10 is specified in X86CallingConv.td
8280     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8281     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8282                        DAG.getConstant(10, MVT::i64));
8283     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8284                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8285                                 false, false, 0);
8286
8287     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8288                        DAG.getConstant(12, MVT::i64));
8289     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8290                                 MachinePointerInfo(TrmpAddr, 12),
8291                                 false, false, 2);
8292
8293     // Jump to the nested function.
8294     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8295     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8296                        DAG.getConstant(20, MVT::i64));
8297     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8298                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8299                                 false, false, 0);
8300
8301     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8302     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8303                        DAG.getConstant(22, MVT::i64));
8304     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8305                                 MachinePointerInfo(TrmpAddr, 22),
8306                                 false, false, 0);
8307
8308     SDValue Ops[] =
8309       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8310     return DAG.getMergeValues(Ops, 2, dl);
8311   } else {
8312     const Function *Func =
8313       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8314     CallingConv::ID CC = Func->getCallingConv();
8315     unsigned NestReg;
8316
8317     switch (CC) {
8318     default:
8319       llvm_unreachable("Unsupported calling convention");
8320     case CallingConv::C:
8321     case CallingConv::X86_StdCall: {
8322       // Pass 'nest' parameter in ECX.
8323       // Must be kept in sync with X86CallingConv.td
8324       NestReg = X86::ECX;
8325
8326       // Check that ECX wasn't needed by an 'inreg' parameter.
8327       const FunctionType *FTy = Func->getFunctionType();
8328       const AttrListPtr &Attrs = Func->getAttributes();
8329
8330       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8331         unsigned InRegCount = 0;
8332         unsigned Idx = 1;
8333
8334         for (FunctionType::param_iterator I = FTy->param_begin(),
8335              E = FTy->param_end(); I != E; ++I, ++Idx)
8336           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8337             // FIXME: should only count parameters that are lowered to integers.
8338             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8339
8340         if (InRegCount > 2) {
8341           report_fatal_error("Nest register in use - reduce number of inreg"
8342                              " parameters!");
8343         }
8344       }
8345       break;
8346     }
8347     case CallingConv::X86_FastCall:
8348     case CallingConv::X86_ThisCall:
8349     case CallingConv::Fast:
8350       // Pass 'nest' parameter in EAX.
8351       // Must be kept in sync with X86CallingConv.td
8352       NestReg = X86::EAX;
8353       break;
8354     }
8355
8356     SDValue OutChains[4];
8357     SDValue Addr, Disp;
8358
8359     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8360                        DAG.getConstant(10, MVT::i32));
8361     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8362
8363     // This is storing the opcode for MOV32ri.
8364     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8365     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8366     OutChains[0] = DAG.getStore(Root, dl,
8367                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8368                                 Trmp, MachinePointerInfo(TrmpAddr),
8369                                 false, false, 0);
8370
8371     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8372                        DAG.getConstant(1, MVT::i32));
8373     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8374                                 MachinePointerInfo(TrmpAddr, 1),
8375                                 false, false, 1);
8376
8377     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8378     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8379                        DAG.getConstant(5, MVT::i32));
8380     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8381                                 MachinePointerInfo(TrmpAddr, 5),
8382                                 false, false, 1);
8383
8384     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8385                        DAG.getConstant(6, MVT::i32));
8386     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8387                                 MachinePointerInfo(TrmpAddr, 6),
8388                                 false, false, 1);
8389
8390     SDValue Ops[] =
8391       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8392     return DAG.getMergeValues(Ops, 2, dl);
8393   }
8394 }
8395
8396 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8397                                             SelectionDAG &DAG) const {
8398   /*
8399    The rounding mode is in bits 11:10 of FPSR, and has the following
8400    settings:
8401      00 Round to nearest
8402      01 Round to -inf
8403      10 Round to +inf
8404      11 Round to 0
8405
8406   FLT_ROUNDS, on the other hand, expects the following:
8407     -1 Undefined
8408      0 Round to 0
8409      1 Round to nearest
8410      2 Round to +inf
8411      3 Round to -inf
8412
8413   To perform the conversion, we do:
8414     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8415   */
8416
8417   MachineFunction &MF = DAG.getMachineFunction();
8418   const TargetMachine &TM = MF.getTarget();
8419   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8420   unsigned StackAlignment = TFI.getStackAlignment();
8421   EVT VT = Op.getValueType();
8422   DebugLoc DL = Op.getDebugLoc();
8423
8424   // Save FP Control Word to stack slot
8425   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8426   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8427
8428
8429   MachineMemOperand *MMO =
8430    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8431                            MachineMemOperand::MOStore, 2, 2);
8432
8433   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8434   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8435                                           DAG.getVTList(MVT::Other),
8436                                           Ops, 2, MVT::i16, MMO);
8437
8438   // Load FP Control Word from stack slot
8439   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8440                             MachinePointerInfo(), false, false, 0);
8441
8442   // Transform as necessary
8443   SDValue CWD1 =
8444     DAG.getNode(ISD::SRL, DL, MVT::i16,
8445                 DAG.getNode(ISD::AND, DL, MVT::i16,
8446                             CWD, DAG.getConstant(0x800, MVT::i16)),
8447                 DAG.getConstant(11, MVT::i8));
8448   SDValue CWD2 =
8449     DAG.getNode(ISD::SRL, DL, MVT::i16,
8450                 DAG.getNode(ISD::AND, DL, MVT::i16,
8451                             CWD, DAG.getConstant(0x400, MVT::i16)),
8452                 DAG.getConstant(9, MVT::i8));
8453
8454   SDValue RetVal =
8455     DAG.getNode(ISD::AND, DL, MVT::i16,
8456                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8457                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8458                             DAG.getConstant(1, MVT::i16)),
8459                 DAG.getConstant(3, MVT::i16));
8460
8461
8462   return DAG.getNode((VT.getSizeInBits() < 16 ?
8463                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8464 }
8465
8466 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8467   EVT VT = Op.getValueType();
8468   EVT OpVT = VT;
8469   unsigned NumBits = VT.getSizeInBits();
8470   DebugLoc dl = Op.getDebugLoc();
8471
8472   Op = Op.getOperand(0);
8473   if (VT == MVT::i8) {
8474     // Zero extend to i32 since there is not an i8 bsr.
8475     OpVT = MVT::i32;
8476     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8477   }
8478
8479   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8480   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8481   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8482
8483   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8484   SDValue Ops[] = {
8485     Op,
8486     DAG.getConstant(NumBits+NumBits-1, OpVT),
8487     DAG.getConstant(X86::COND_E, MVT::i8),
8488     Op.getValue(1)
8489   };
8490   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8491
8492   // Finally xor with NumBits-1.
8493   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8494
8495   if (VT == MVT::i8)
8496     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8497   return Op;
8498 }
8499
8500 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8501   EVT VT = Op.getValueType();
8502   EVT OpVT = VT;
8503   unsigned NumBits = VT.getSizeInBits();
8504   DebugLoc dl = Op.getDebugLoc();
8505
8506   Op = Op.getOperand(0);
8507   if (VT == MVT::i8) {
8508     OpVT = MVT::i32;
8509     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8510   }
8511
8512   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8513   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8514   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8515
8516   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8517   SDValue Ops[] = {
8518     Op,
8519     DAG.getConstant(NumBits, OpVT),
8520     DAG.getConstant(X86::COND_E, MVT::i8),
8521     Op.getValue(1)
8522   };
8523   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8524
8525   if (VT == MVT::i8)
8526     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8527   return Op;
8528 }
8529
8530 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8531   EVT VT = Op.getValueType();
8532   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8533   DebugLoc dl = Op.getDebugLoc();
8534
8535   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8536   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8537   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8538   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8539   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8540   //
8541   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8542   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8543   //  return AloBlo + AloBhi + AhiBlo;
8544
8545   SDValue A = Op.getOperand(0);
8546   SDValue B = Op.getOperand(1);
8547
8548   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8549                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8550                        A, DAG.getConstant(32, MVT::i32));
8551   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8552                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8553                        B, DAG.getConstant(32, MVT::i32));
8554   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8555                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8556                        A, B);
8557   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8558                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8559                        A, Bhi);
8560   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8561                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8562                        Ahi, B);
8563   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8564                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8565                        AloBhi, DAG.getConstant(32, MVT::i32));
8566   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8567                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8568                        AhiBlo, DAG.getConstant(32, MVT::i32));
8569   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8570   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8571   return Res;
8572 }
8573
8574 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8575   EVT VT = Op.getValueType();
8576   DebugLoc dl = Op.getDebugLoc();
8577   SDValue R = Op.getOperand(0);
8578
8579   LLVMContext *Context = DAG.getContext();
8580
8581   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8582
8583   if (VT == MVT::v4i32) {
8584     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8585                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8586                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8587
8588     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8589
8590     std::vector<Constant*> CV(4, CI);
8591     Constant *C = ConstantVector::get(CV);
8592     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8593     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8594                                  MachinePointerInfo::getConstantPool(),
8595                                  false, false, 16);
8596
8597     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8598     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8599     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8600     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8601   }
8602   if (VT == MVT::v16i8) {
8603     // a = a << 5;
8604     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8605                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8606                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8607
8608     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8609     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8610
8611     std::vector<Constant*> CVM1(16, CM1);
8612     std::vector<Constant*> CVM2(16, CM2);
8613     Constant *C = ConstantVector::get(CVM1);
8614     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8615     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8616                             MachinePointerInfo::getConstantPool(),
8617                             false, false, 16);
8618
8619     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8620     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8621     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8622                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8623                     DAG.getConstant(4, MVT::i32));
8624     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8625     // a += a
8626     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8627
8628     C = ConstantVector::get(CVM2);
8629     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8630     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8631                     MachinePointerInfo::getConstantPool(),
8632                     false, false, 16);
8633
8634     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8635     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8636     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8637                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8638                     DAG.getConstant(2, MVT::i32));
8639     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8640     // a += a
8641     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8642
8643     // return pblendv(r, r+r, a);
8644     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8645                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8646     return R;
8647   }
8648   return SDValue();
8649 }
8650
8651 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8652   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8653   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8654   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8655   // has only one use.
8656   SDNode *N = Op.getNode();
8657   SDValue LHS = N->getOperand(0);
8658   SDValue RHS = N->getOperand(1);
8659   unsigned BaseOp = 0;
8660   unsigned Cond = 0;
8661   DebugLoc DL = Op.getDebugLoc();
8662   switch (Op.getOpcode()) {
8663   default: llvm_unreachable("Unknown ovf instruction!");
8664   case ISD::SADDO:
8665     // A subtract of one will be selected as a INC. Note that INC doesn't
8666     // set CF, so we can't do this for UADDO.
8667     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8668       if (C->getAPIntValue() == 1) {
8669         BaseOp = X86ISD::INC;
8670         Cond = X86::COND_O;
8671         break;
8672       }
8673     BaseOp = X86ISD::ADD;
8674     Cond = X86::COND_O;
8675     break;
8676   case ISD::UADDO:
8677     BaseOp = X86ISD::ADD;
8678     Cond = X86::COND_B;
8679     break;
8680   case ISD::SSUBO:
8681     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8682     // set CF, so we can't do this for USUBO.
8683     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8684       if (C->getAPIntValue() == 1) {
8685         BaseOp = X86ISD::DEC;
8686         Cond = X86::COND_O;
8687         break;
8688       }
8689     BaseOp = X86ISD::SUB;
8690     Cond = X86::COND_O;
8691     break;
8692   case ISD::USUBO:
8693     BaseOp = X86ISD::SUB;
8694     Cond = X86::COND_B;
8695     break;
8696   case ISD::SMULO:
8697     BaseOp = X86ISD::SMUL;
8698     Cond = X86::COND_O;
8699     break;
8700   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8701     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8702                                  MVT::i32);
8703     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8704
8705     SDValue SetCC =
8706       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8707                   DAG.getConstant(X86::COND_O, MVT::i32),
8708                   SDValue(Sum.getNode(), 2));
8709
8710     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8711     return Sum;
8712   }
8713   }
8714
8715   // Also sets EFLAGS.
8716   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8717   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8718
8719   SDValue SetCC =
8720     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8721                 DAG.getConstant(Cond, MVT::i32),
8722                 SDValue(Sum.getNode(), 1));
8723
8724   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8725   return Sum;
8726 }
8727
8728 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8729   DebugLoc dl = Op.getDebugLoc();
8730
8731   if (!Subtarget->hasSSE2()) {
8732     SDValue Chain = Op.getOperand(0);
8733     SDValue Zero = DAG.getConstant(0,
8734                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8735     SDValue Ops[] = {
8736       DAG.getRegister(X86::ESP, MVT::i32), // Base
8737       DAG.getTargetConstant(1, MVT::i8),   // Scale
8738       DAG.getRegister(0, MVT::i32),        // Index
8739       DAG.getTargetConstant(0, MVT::i32),  // Disp
8740       DAG.getRegister(0, MVT::i32),        // Segment.
8741       Zero,
8742       Chain
8743     };
8744     SDNode *Res =
8745       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8746                           array_lengthof(Ops));
8747     return SDValue(Res, 0);
8748   }
8749
8750   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8751   if (!isDev)
8752     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8753
8754   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8755   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8756   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8757   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8758
8759   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8760   if (!Op1 && !Op2 && !Op3 && Op4)
8761     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8762
8763   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8764   if (Op1 && !Op2 && !Op3 && !Op4)
8765     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8766
8767   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8768   //           (MFENCE)>;
8769   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8770 }
8771
8772 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8773   EVT T = Op.getValueType();
8774   DebugLoc DL = Op.getDebugLoc();
8775   unsigned Reg = 0;
8776   unsigned size = 0;
8777   switch(T.getSimpleVT().SimpleTy) {
8778   default:
8779     assert(false && "Invalid value type!");
8780   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8781   case MVT::i16: Reg = X86::AX;  size = 2; break;
8782   case MVT::i32: Reg = X86::EAX; size = 4; break;
8783   case MVT::i64:
8784     assert(Subtarget->is64Bit() && "Node not type legal!");
8785     Reg = X86::RAX; size = 8;
8786     break;
8787   }
8788   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8789                                     Op.getOperand(2), SDValue());
8790   SDValue Ops[] = { cpIn.getValue(0),
8791                     Op.getOperand(1),
8792                     Op.getOperand(3),
8793                     DAG.getTargetConstant(size, MVT::i8),
8794                     cpIn.getValue(1) };
8795   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8796   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8797   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8798                                            Ops, 5, T, MMO);
8799   SDValue cpOut =
8800     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8801   return cpOut;
8802 }
8803
8804 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8805                                                  SelectionDAG &DAG) const {
8806   assert(Subtarget->is64Bit() && "Result not type legalized?");
8807   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8808   SDValue TheChain = Op.getOperand(0);
8809   DebugLoc dl = Op.getDebugLoc();
8810   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8811   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8812   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8813                                    rax.getValue(2));
8814   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8815                             DAG.getConstant(32, MVT::i8));
8816   SDValue Ops[] = {
8817     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8818     rdx.getValue(1)
8819   };
8820   return DAG.getMergeValues(Ops, 2, dl);
8821 }
8822
8823 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8824                                             SelectionDAG &DAG) const {
8825   EVT SrcVT = Op.getOperand(0).getValueType();
8826   EVT DstVT = Op.getValueType();
8827   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8828          Subtarget->hasMMX() && "Unexpected custom BITCAST");
8829   assert((DstVT == MVT::i64 ||
8830           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8831          "Unexpected custom BITCAST");
8832   // i64 <=> MMX conversions are Legal.
8833   if (SrcVT==MVT::i64 && DstVT.isVector())
8834     return Op;
8835   if (DstVT==MVT::i64 && SrcVT.isVector())
8836     return Op;
8837   // MMX <=> MMX conversions are Legal.
8838   if (SrcVT.isVector() && DstVT.isVector())
8839     return Op;
8840   // All other conversions need to be expanded.
8841   return SDValue();
8842 }
8843
8844 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8845   SDNode *Node = Op.getNode();
8846   DebugLoc dl = Node->getDebugLoc();
8847   EVT T = Node->getValueType(0);
8848   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8849                               DAG.getConstant(0, T), Node->getOperand(2));
8850   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8851                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8852                        Node->getOperand(0),
8853                        Node->getOperand(1), negOp,
8854                        cast<AtomicSDNode>(Node)->getSrcValue(),
8855                        cast<AtomicSDNode>(Node)->getAlignment());
8856 }
8857
8858 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8859   EVT VT = Op.getNode()->getValueType(0);
8860
8861   // Let legalize expand this if it isn't a legal type yet.
8862   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8863     return SDValue();
8864
8865   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8866
8867   unsigned Opc;
8868   bool ExtraOp = false;
8869   switch (Op.getOpcode()) {
8870   default: assert(0 && "Invalid code");
8871   case ISD::ADDC: Opc = X86ISD::ADD; break;
8872   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8873   case ISD::SUBC: Opc = X86ISD::SUB; break;
8874   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8875   }
8876
8877   if (!ExtraOp)
8878     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8879                        Op.getOperand(1));
8880   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8881                      Op.getOperand(1), Op.getOperand(2));
8882 }
8883
8884 /// LowerOperation - Provide custom lowering hooks for some operations.
8885 ///
8886 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8887   switch (Op.getOpcode()) {
8888   default: llvm_unreachable("Should not custom lower this!");
8889   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8890   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8891   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8892   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8893   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8894   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8895   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8896   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8897   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
8898   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
8899   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8900   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8901   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8902   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8903   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8904   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8905   case ISD::SHL_PARTS:
8906   case ISD::SRA_PARTS:
8907   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8908   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8909   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8910   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8911   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8912   case ISD::FABS:               return LowerFABS(Op, DAG);
8913   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8914   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8915   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8916   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8917   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8918   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8919   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8920   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8921   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8922   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8923   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8924   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8925   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8926   case ISD::FRAME_TO_ARGS_OFFSET:
8927                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8928   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8929   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8930   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8931   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8932   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8933   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8934   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8935   case ISD::SHL:                return LowerSHL(Op, DAG);
8936   case ISD::SADDO:
8937   case ISD::UADDO:
8938   case ISD::SSUBO:
8939   case ISD::USUBO:
8940   case ISD::SMULO:
8941   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8942   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8943   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
8944   case ISD::ADDC:
8945   case ISD::ADDE:
8946   case ISD::SUBC:
8947   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8948   }
8949 }
8950
8951 void X86TargetLowering::
8952 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8953                         SelectionDAG &DAG, unsigned NewOp) const {
8954   EVT T = Node->getValueType(0);
8955   DebugLoc dl = Node->getDebugLoc();
8956   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8957
8958   SDValue Chain = Node->getOperand(0);
8959   SDValue In1 = Node->getOperand(1);
8960   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8961                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8962   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8963                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8964   SDValue Ops[] = { Chain, In1, In2L, In2H };
8965   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8966   SDValue Result =
8967     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8968                             cast<MemSDNode>(Node)->getMemOperand());
8969   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8970   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8971   Results.push_back(Result.getValue(2));
8972 }
8973
8974 /// ReplaceNodeResults - Replace a node with an illegal result type
8975 /// with a new node built out of custom code.
8976 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8977                                            SmallVectorImpl<SDValue>&Results,
8978                                            SelectionDAG &DAG) const {
8979   DebugLoc dl = N->getDebugLoc();
8980   switch (N->getOpcode()) {
8981   default:
8982     assert(false && "Do not know how to custom type legalize this operation!");
8983     return;
8984   case ISD::ADDC:
8985   case ISD::ADDE:
8986   case ISD::SUBC:
8987   case ISD::SUBE:
8988     // We don't want to expand or promote these.
8989     return;
8990   case ISD::FP_TO_SINT: {
8991     std::pair<SDValue,SDValue> Vals =
8992         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8993     SDValue FIST = Vals.first, StackSlot = Vals.second;
8994     if (FIST.getNode() != 0) {
8995       EVT VT = N->getValueType(0);
8996       // Return a load from the stack slot.
8997       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8998                                     MachinePointerInfo(), false, false, 0));
8999     }
9000     return;
9001   }
9002   case ISD::READCYCLECOUNTER: {
9003     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9004     SDValue TheChain = N->getOperand(0);
9005     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9006     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9007                                      rd.getValue(1));
9008     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9009                                      eax.getValue(2));
9010     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9011     SDValue Ops[] = { eax, edx };
9012     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9013     Results.push_back(edx.getValue(1));
9014     return;
9015   }
9016   case ISD::ATOMIC_CMP_SWAP: {
9017     EVT T = N->getValueType(0);
9018     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9019     SDValue cpInL, cpInH;
9020     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9021                         DAG.getConstant(0, MVT::i32));
9022     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9023                         DAG.getConstant(1, MVT::i32));
9024     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9025     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9026                              cpInL.getValue(1));
9027     SDValue swapInL, swapInH;
9028     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9029                           DAG.getConstant(0, MVT::i32));
9030     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9031                           DAG.getConstant(1, MVT::i32));
9032     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9033                                cpInH.getValue(1));
9034     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9035                                swapInL.getValue(1));
9036     SDValue Ops[] = { swapInH.getValue(0),
9037                       N->getOperand(1),
9038                       swapInH.getValue(1) };
9039     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9040     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9041     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9042                                              Ops, 3, T, MMO);
9043     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9044                                         MVT::i32, Result.getValue(1));
9045     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9046                                         MVT::i32, cpOutL.getValue(2));
9047     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9048     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9049     Results.push_back(cpOutH.getValue(1));
9050     return;
9051   }
9052   case ISD::ATOMIC_LOAD_ADD:
9053     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9054     return;
9055   case ISD::ATOMIC_LOAD_AND:
9056     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9057     return;
9058   case ISD::ATOMIC_LOAD_NAND:
9059     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9060     return;
9061   case ISD::ATOMIC_LOAD_OR:
9062     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9063     return;
9064   case ISD::ATOMIC_LOAD_SUB:
9065     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9066     return;
9067   case ISD::ATOMIC_LOAD_XOR:
9068     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9069     return;
9070   case ISD::ATOMIC_SWAP:
9071     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9072     return;
9073   }
9074 }
9075
9076 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9077   switch (Opcode) {
9078   default: return NULL;
9079   case X86ISD::BSF:                return "X86ISD::BSF";
9080   case X86ISD::BSR:                return "X86ISD::BSR";
9081   case X86ISD::SHLD:               return "X86ISD::SHLD";
9082   case X86ISD::SHRD:               return "X86ISD::SHRD";
9083   case X86ISD::FAND:               return "X86ISD::FAND";
9084   case X86ISD::FOR:                return "X86ISD::FOR";
9085   case X86ISD::FXOR:               return "X86ISD::FXOR";
9086   case X86ISD::FSRL:               return "X86ISD::FSRL";
9087   case X86ISD::FILD:               return "X86ISD::FILD";
9088   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9089   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9090   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9091   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9092   case X86ISD::FLD:                return "X86ISD::FLD";
9093   case X86ISD::FST:                return "X86ISD::FST";
9094   case X86ISD::CALL:               return "X86ISD::CALL";
9095   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9096   case X86ISD::BT:                 return "X86ISD::BT";
9097   case X86ISD::CMP:                return "X86ISD::CMP";
9098   case X86ISD::COMI:               return "X86ISD::COMI";
9099   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9100   case X86ISD::SETCC:              return "X86ISD::SETCC";
9101   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9102   case X86ISD::CMOV:               return "X86ISD::CMOV";
9103   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9104   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9105   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9106   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9107   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9108   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9109   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9110   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9111   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9112   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9113   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9114   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9115   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9116   case X86ISD::PANDN:              return "X86ISD::PANDN";
9117   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9118   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9119   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9120   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9121   case X86ISD::FMAX:               return "X86ISD::FMAX";
9122   case X86ISD::FMIN:               return "X86ISD::FMIN";
9123   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9124   case X86ISD::FRCP:               return "X86ISD::FRCP";
9125   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9126   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9127   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9128   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9129   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9130   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9131   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9132   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9133   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9134   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9135   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9136   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9137   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9138   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9139   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9140   case X86ISD::VSHL:               return "X86ISD::VSHL";
9141   case X86ISD::VSRL:               return "X86ISD::VSRL";
9142   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9143   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9144   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9145   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9146   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9147   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9148   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9149   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9150   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9151   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9152   case X86ISD::ADD:                return "X86ISD::ADD";
9153   case X86ISD::SUB:                return "X86ISD::SUB";
9154   case X86ISD::ADC:                return "X86ISD::ADC";
9155   case X86ISD::SBB:                return "X86ISD::SBB";
9156   case X86ISD::SMUL:               return "X86ISD::SMUL";
9157   case X86ISD::UMUL:               return "X86ISD::UMUL";
9158   case X86ISD::INC:                return "X86ISD::INC";
9159   case X86ISD::DEC:                return "X86ISD::DEC";
9160   case X86ISD::OR:                 return "X86ISD::OR";
9161   case X86ISD::XOR:                return "X86ISD::XOR";
9162   case X86ISD::AND:                return "X86ISD::AND";
9163   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9164   case X86ISD::PTEST:              return "X86ISD::PTEST";
9165   case X86ISD::TESTP:              return "X86ISD::TESTP";
9166   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9167   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9168   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9169   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9170   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9171   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9172   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9173   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9174   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9175   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9176   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9177   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9178   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9179   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9180   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9181   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9182   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9183   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9184   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9185   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9186   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9187   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9188   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9189   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9190   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9191   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9192   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9193   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9194   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9195   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9196   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9197   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9198   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9199   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9200   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9201   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9202   }
9203 }
9204
9205 // isLegalAddressingMode - Return true if the addressing mode represented
9206 // by AM is legal for this target, for a load/store of the specified type.
9207 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9208                                               const Type *Ty) const {
9209   // X86 supports extremely general addressing modes.
9210   CodeModel::Model M = getTargetMachine().getCodeModel();
9211   Reloc::Model R = getTargetMachine().getRelocationModel();
9212
9213   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9214   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9215     return false;
9216
9217   if (AM.BaseGV) {
9218     unsigned GVFlags =
9219       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9220
9221     // If a reference to this global requires an extra load, we can't fold it.
9222     if (isGlobalStubReference(GVFlags))
9223       return false;
9224
9225     // If BaseGV requires a register for the PIC base, we cannot also have a
9226     // BaseReg specified.
9227     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9228       return false;
9229
9230     // If lower 4G is not available, then we must use rip-relative addressing.
9231     if ((M != CodeModel::Small || R != Reloc::Static) &&
9232         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9233       return false;
9234   }
9235
9236   switch (AM.Scale) {
9237   case 0:
9238   case 1:
9239   case 2:
9240   case 4:
9241   case 8:
9242     // These scales always work.
9243     break;
9244   case 3:
9245   case 5:
9246   case 9:
9247     // These scales are formed with basereg+scalereg.  Only accept if there is
9248     // no basereg yet.
9249     if (AM.HasBaseReg)
9250       return false;
9251     break;
9252   default:  // Other stuff never works.
9253     return false;
9254   }
9255
9256   return true;
9257 }
9258
9259
9260 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9261   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9262     return false;
9263   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9264   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9265   if (NumBits1 <= NumBits2)
9266     return false;
9267   return true;
9268 }
9269
9270 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9271   if (!VT1.isInteger() || !VT2.isInteger())
9272     return false;
9273   unsigned NumBits1 = VT1.getSizeInBits();
9274   unsigned NumBits2 = VT2.getSizeInBits();
9275   if (NumBits1 <= NumBits2)
9276     return false;
9277   return true;
9278 }
9279
9280 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9281   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9282   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9283 }
9284
9285 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9286   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9287   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9288 }
9289
9290 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9291   // i16 instructions are longer (0x66 prefix) and potentially slower.
9292   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9293 }
9294
9295 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9296 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9297 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9298 /// are assumed to be legal.
9299 bool
9300 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9301                                       EVT VT) const {
9302   // Very little shuffling can be done for 64-bit vectors right now.
9303   if (VT.getSizeInBits() == 64)
9304     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9305
9306   // FIXME: pshufb, blends, shifts.
9307   return (VT.getVectorNumElements() == 2 ||
9308           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9309           isMOVLMask(M, VT) ||
9310           isSHUFPMask(M, VT) ||
9311           isPSHUFDMask(M, VT) ||
9312           isPSHUFHWMask(M, VT) ||
9313           isPSHUFLWMask(M, VT) ||
9314           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9315           isUNPCKLMask(M, VT) ||
9316           isUNPCKHMask(M, VT) ||
9317           isUNPCKL_v_undef_Mask(M, VT) ||
9318           isUNPCKH_v_undef_Mask(M, VT));
9319 }
9320
9321 bool
9322 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9323                                           EVT VT) const {
9324   unsigned NumElts = VT.getVectorNumElements();
9325   // FIXME: This collection of masks seems suspect.
9326   if (NumElts == 2)
9327     return true;
9328   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9329     return (isMOVLMask(Mask, VT)  ||
9330             isCommutedMOVLMask(Mask, VT, true) ||
9331             isSHUFPMask(Mask, VT) ||
9332             isCommutedSHUFPMask(Mask, VT));
9333   }
9334   return false;
9335 }
9336
9337 //===----------------------------------------------------------------------===//
9338 //                           X86 Scheduler Hooks
9339 //===----------------------------------------------------------------------===//
9340
9341 // private utility function
9342 MachineBasicBlock *
9343 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9344                                                        MachineBasicBlock *MBB,
9345                                                        unsigned regOpc,
9346                                                        unsigned immOpc,
9347                                                        unsigned LoadOpc,
9348                                                        unsigned CXchgOpc,
9349                                                        unsigned notOpc,
9350                                                        unsigned EAXreg,
9351                                                        TargetRegisterClass *RC,
9352                                                        bool invSrc) const {
9353   // For the atomic bitwise operator, we generate
9354   //   thisMBB:
9355   //   newMBB:
9356   //     ld  t1 = [bitinstr.addr]
9357   //     op  t2 = t1, [bitinstr.val]
9358   //     mov EAX = t1
9359   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9360   //     bz  newMBB
9361   //     fallthrough -->nextMBB
9362   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9363   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9364   MachineFunction::iterator MBBIter = MBB;
9365   ++MBBIter;
9366
9367   /// First build the CFG
9368   MachineFunction *F = MBB->getParent();
9369   MachineBasicBlock *thisMBB = MBB;
9370   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9371   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9372   F->insert(MBBIter, newMBB);
9373   F->insert(MBBIter, nextMBB);
9374
9375   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9376   nextMBB->splice(nextMBB->begin(), thisMBB,
9377                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9378                   thisMBB->end());
9379   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9380
9381   // Update thisMBB to fall through to newMBB
9382   thisMBB->addSuccessor(newMBB);
9383
9384   // newMBB jumps to itself and fall through to nextMBB
9385   newMBB->addSuccessor(nextMBB);
9386   newMBB->addSuccessor(newMBB);
9387
9388   // Insert instructions into newMBB based on incoming instruction
9389   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9390          "unexpected number of operands");
9391   DebugLoc dl = bInstr->getDebugLoc();
9392   MachineOperand& destOper = bInstr->getOperand(0);
9393   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9394   int numArgs = bInstr->getNumOperands() - 1;
9395   for (int i=0; i < numArgs; ++i)
9396     argOpers[i] = &bInstr->getOperand(i+1);
9397
9398   // x86 address has 4 operands: base, index, scale, and displacement
9399   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9400   int valArgIndx = lastAddrIndx + 1;
9401
9402   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9403   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9404   for (int i=0; i <= lastAddrIndx; ++i)
9405     (*MIB).addOperand(*argOpers[i]);
9406
9407   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9408   if (invSrc) {
9409     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9410   }
9411   else
9412     tt = t1;
9413
9414   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9415   assert((argOpers[valArgIndx]->isReg() ||
9416           argOpers[valArgIndx]->isImm()) &&
9417          "invalid operand");
9418   if (argOpers[valArgIndx]->isReg())
9419     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9420   else
9421     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9422   MIB.addReg(tt);
9423   (*MIB).addOperand(*argOpers[valArgIndx]);
9424
9425   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9426   MIB.addReg(t1);
9427
9428   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9429   for (int i=0; i <= lastAddrIndx; ++i)
9430     (*MIB).addOperand(*argOpers[i]);
9431   MIB.addReg(t2);
9432   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9433   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9434                     bInstr->memoperands_end());
9435
9436   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9437   MIB.addReg(EAXreg);
9438
9439   // insert branch
9440   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9441
9442   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9443   return nextMBB;
9444 }
9445
9446 // private utility function:  64 bit atomics on 32 bit host.
9447 MachineBasicBlock *
9448 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9449                                                        MachineBasicBlock *MBB,
9450                                                        unsigned regOpcL,
9451                                                        unsigned regOpcH,
9452                                                        unsigned immOpcL,
9453                                                        unsigned immOpcH,
9454                                                        bool invSrc) const {
9455   // For the atomic bitwise operator, we generate
9456   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9457   //     ld t1,t2 = [bitinstr.addr]
9458   //   newMBB:
9459   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9460   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9461   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9462   //     mov ECX, EBX <- t5, t6
9463   //     mov EAX, EDX <- t1, t2
9464   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9465   //     mov t3, t4 <- EAX, EDX
9466   //     bz  newMBB
9467   //     result in out1, out2
9468   //     fallthrough -->nextMBB
9469
9470   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9471   const unsigned LoadOpc = X86::MOV32rm;
9472   const unsigned NotOpc = X86::NOT32r;
9473   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9474   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9475   MachineFunction::iterator MBBIter = MBB;
9476   ++MBBIter;
9477
9478   /// First build the CFG
9479   MachineFunction *F = MBB->getParent();
9480   MachineBasicBlock *thisMBB = MBB;
9481   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9482   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9483   F->insert(MBBIter, newMBB);
9484   F->insert(MBBIter, nextMBB);
9485
9486   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9487   nextMBB->splice(nextMBB->begin(), thisMBB,
9488                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9489                   thisMBB->end());
9490   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9491
9492   // Update thisMBB to fall through to newMBB
9493   thisMBB->addSuccessor(newMBB);
9494
9495   // newMBB jumps to itself and fall through to nextMBB
9496   newMBB->addSuccessor(nextMBB);
9497   newMBB->addSuccessor(newMBB);
9498
9499   DebugLoc dl = bInstr->getDebugLoc();
9500   // Insert instructions into newMBB based on incoming instruction
9501   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9502   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9503          "unexpected number of operands");
9504   MachineOperand& dest1Oper = bInstr->getOperand(0);
9505   MachineOperand& dest2Oper = bInstr->getOperand(1);
9506   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9507   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9508     argOpers[i] = &bInstr->getOperand(i+2);
9509
9510     // We use some of the operands multiple times, so conservatively just
9511     // clear any kill flags that might be present.
9512     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9513       argOpers[i]->setIsKill(false);
9514   }
9515
9516   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9517   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9518
9519   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9520   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9521   for (int i=0; i <= lastAddrIndx; ++i)
9522     (*MIB).addOperand(*argOpers[i]);
9523   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9524   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9525   // add 4 to displacement.
9526   for (int i=0; i <= lastAddrIndx-2; ++i)
9527     (*MIB).addOperand(*argOpers[i]);
9528   MachineOperand newOp3 = *(argOpers[3]);
9529   if (newOp3.isImm())
9530     newOp3.setImm(newOp3.getImm()+4);
9531   else
9532     newOp3.setOffset(newOp3.getOffset()+4);
9533   (*MIB).addOperand(newOp3);
9534   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9535
9536   // t3/4 are defined later, at the bottom of the loop
9537   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9538   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9539   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9540     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9541   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9542     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9543
9544   // The subsequent operations should be using the destination registers of
9545   //the PHI instructions.
9546   if (invSrc) {
9547     t1 = F->getRegInfo().createVirtualRegister(RC);
9548     t2 = F->getRegInfo().createVirtualRegister(RC);
9549     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9550     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9551   } else {
9552     t1 = dest1Oper.getReg();
9553     t2 = dest2Oper.getReg();
9554   }
9555
9556   int valArgIndx = lastAddrIndx + 1;
9557   assert((argOpers[valArgIndx]->isReg() ||
9558           argOpers[valArgIndx]->isImm()) &&
9559          "invalid operand");
9560   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9561   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9562   if (argOpers[valArgIndx]->isReg())
9563     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9564   else
9565     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9566   if (regOpcL != X86::MOV32rr)
9567     MIB.addReg(t1);
9568   (*MIB).addOperand(*argOpers[valArgIndx]);
9569   assert(argOpers[valArgIndx + 1]->isReg() ==
9570          argOpers[valArgIndx]->isReg());
9571   assert(argOpers[valArgIndx + 1]->isImm() ==
9572          argOpers[valArgIndx]->isImm());
9573   if (argOpers[valArgIndx + 1]->isReg())
9574     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9575   else
9576     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9577   if (regOpcH != X86::MOV32rr)
9578     MIB.addReg(t2);
9579   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9580
9581   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9582   MIB.addReg(t1);
9583   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9584   MIB.addReg(t2);
9585
9586   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9587   MIB.addReg(t5);
9588   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9589   MIB.addReg(t6);
9590
9591   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9592   for (int i=0; i <= lastAddrIndx; ++i)
9593     (*MIB).addOperand(*argOpers[i]);
9594
9595   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9596   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9597                     bInstr->memoperands_end());
9598
9599   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9600   MIB.addReg(X86::EAX);
9601   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9602   MIB.addReg(X86::EDX);
9603
9604   // insert branch
9605   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9606
9607   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9608   return nextMBB;
9609 }
9610
9611 // private utility function
9612 MachineBasicBlock *
9613 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9614                                                       MachineBasicBlock *MBB,
9615                                                       unsigned cmovOpc) const {
9616   // For the atomic min/max operator, we generate
9617   //   thisMBB:
9618   //   newMBB:
9619   //     ld t1 = [min/max.addr]
9620   //     mov t2 = [min/max.val]
9621   //     cmp  t1, t2
9622   //     cmov[cond] t2 = t1
9623   //     mov EAX = t1
9624   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9625   //     bz   newMBB
9626   //     fallthrough -->nextMBB
9627   //
9628   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9629   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9630   MachineFunction::iterator MBBIter = MBB;
9631   ++MBBIter;
9632
9633   /// First build the CFG
9634   MachineFunction *F = MBB->getParent();
9635   MachineBasicBlock *thisMBB = MBB;
9636   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9637   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9638   F->insert(MBBIter, newMBB);
9639   F->insert(MBBIter, nextMBB);
9640
9641   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9642   nextMBB->splice(nextMBB->begin(), thisMBB,
9643                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9644                   thisMBB->end());
9645   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9646
9647   // Update thisMBB to fall through to newMBB
9648   thisMBB->addSuccessor(newMBB);
9649
9650   // newMBB jumps to newMBB and fall through to nextMBB
9651   newMBB->addSuccessor(nextMBB);
9652   newMBB->addSuccessor(newMBB);
9653
9654   DebugLoc dl = mInstr->getDebugLoc();
9655   // Insert instructions into newMBB based on incoming instruction
9656   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9657          "unexpected number of operands");
9658   MachineOperand& destOper = mInstr->getOperand(0);
9659   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9660   int numArgs = mInstr->getNumOperands() - 1;
9661   for (int i=0; i < numArgs; ++i)
9662     argOpers[i] = &mInstr->getOperand(i+1);
9663
9664   // x86 address has 4 operands: base, index, scale, and displacement
9665   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9666   int valArgIndx = lastAddrIndx + 1;
9667
9668   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9669   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9670   for (int i=0; i <= lastAddrIndx; ++i)
9671     (*MIB).addOperand(*argOpers[i]);
9672
9673   // We only support register and immediate values
9674   assert((argOpers[valArgIndx]->isReg() ||
9675           argOpers[valArgIndx]->isImm()) &&
9676          "invalid operand");
9677
9678   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9679   if (argOpers[valArgIndx]->isReg())
9680     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9681   else
9682     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9683   (*MIB).addOperand(*argOpers[valArgIndx]);
9684
9685   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9686   MIB.addReg(t1);
9687
9688   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9689   MIB.addReg(t1);
9690   MIB.addReg(t2);
9691
9692   // Generate movc
9693   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9694   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9695   MIB.addReg(t2);
9696   MIB.addReg(t1);
9697
9698   // Cmp and exchange if none has modified the memory location
9699   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9700   for (int i=0; i <= lastAddrIndx; ++i)
9701     (*MIB).addOperand(*argOpers[i]);
9702   MIB.addReg(t3);
9703   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9704   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9705                     mInstr->memoperands_end());
9706
9707   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9708   MIB.addReg(X86::EAX);
9709
9710   // insert branch
9711   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9712
9713   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9714   return nextMBB;
9715 }
9716
9717 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9718 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9719 // in the .td file.
9720 MachineBasicBlock *
9721 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9722                             unsigned numArgs, bool memArg) const {
9723   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9724          "Target must have SSE4.2 or AVX features enabled");
9725
9726   DebugLoc dl = MI->getDebugLoc();
9727   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9728   unsigned Opc;
9729   if (!Subtarget->hasAVX()) {
9730     if (memArg)
9731       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9732     else
9733       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9734   } else {
9735     if (memArg)
9736       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9737     else
9738       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9739   }
9740
9741   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9742   for (unsigned i = 0; i < numArgs; ++i) {
9743     MachineOperand &Op = MI->getOperand(i+1);
9744     if (!(Op.isReg() && Op.isImplicit()))
9745       MIB.addOperand(Op);
9746   }
9747   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9748     .addReg(X86::XMM0);
9749
9750   MI->eraseFromParent();
9751   return BB;
9752 }
9753
9754 MachineBasicBlock *
9755 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9756   DebugLoc dl = MI->getDebugLoc();
9757   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9758
9759   // Address into RAX/EAX, other two args into ECX, EDX.
9760   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9761   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9762   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9763   for (int i = 0; i < X86::AddrNumOperands; ++i)
9764     MIB.addOperand(MI->getOperand(i));
9765
9766   unsigned ValOps = X86::AddrNumOperands;
9767   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9768     .addReg(MI->getOperand(ValOps).getReg());
9769   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9770     .addReg(MI->getOperand(ValOps+1).getReg());
9771
9772   // The instruction doesn't actually take any operands though.
9773   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9774
9775   MI->eraseFromParent(); // The pseudo is gone now.
9776   return BB;
9777 }
9778
9779 MachineBasicBlock *
9780 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9781   DebugLoc dl = MI->getDebugLoc();
9782   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9783
9784   // First arg in ECX, the second in EAX.
9785   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9786     .addReg(MI->getOperand(0).getReg());
9787   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9788     .addReg(MI->getOperand(1).getReg());
9789
9790   // The instruction doesn't actually take any operands though.
9791   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9792
9793   MI->eraseFromParent(); // The pseudo is gone now.
9794   return BB;
9795 }
9796
9797 MachineBasicBlock *
9798 X86TargetLowering::EmitVAARG64WithCustomInserter(
9799                    MachineInstr *MI,
9800                    MachineBasicBlock *MBB) const {
9801   // Emit va_arg instruction on X86-64.
9802
9803   // Operands to this pseudo-instruction:
9804   // 0  ) Output        : destination address (reg)
9805   // 1-5) Input         : va_list address (addr, i64mem)
9806   // 6  ) ArgSize       : Size (in bytes) of vararg type
9807   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9808   // 8  ) Align         : Alignment of type
9809   // 9  ) EFLAGS (implicit-def)
9810
9811   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9812   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9813
9814   unsigned DestReg = MI->getOperand(0).getReg();
9815   MachineOperand &Base = MI->getOperand(1);
9816   MachineOperand &Scale = MI->getOperand(2);
9817   MachineOperand &Index = MI->getOperand(3);
9818   MachineOperand &Disp = MI->getOperand(4);
9819   MachineOperand &Segment = MI->getOperand(5);
9820   unsigned ArgSize = MI->getOperand(6).getImm();
9821   unsigned ArgMode = MI->getOperand(7).getImm();
9822   unsigned Align = MI->getOperand(8).getImm();
9823
9824   // Memory Reference
9825   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9826   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9827   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9828
9829   // Machine Information
9830   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9831   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9832   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9833   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9834   DebugLoc DL = MI->getDebugLoc();
9835
9836   // struct va_list {
9837   //   i32   gp_offset
9838   //   i32   fp_offset
9839   //   i64   overflow_area (address)
9840   //   i64   reg_save_area (address)
9841   // }
9842   // sizeof(va_list) = 24
9843   // alignment(va_list) = 8
9844
9845   unsigned TotalNumIntRegs = 6;
9846   unsigned TotalNumXMMRegs = 8;
9847   bool UseGPOffset = (ArgMode == 1);
9848   bool UseFPOffset = (ArgMode == 2);
9849   unsigned MaxOffset = TotalNumIntRegs * 8 +
9850                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9851
9852   /* Align ArgSize to a multiple of 8 */
9853   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9854   bool NeedsAlign = (Align > 8);
9855
9856   MachineBasicBlock *thisMBB = MBB;
9857   MachineBasicBlock *overflowMBB;
9858   MachineBasicBlock *offsetMBB;
9859   MachineBasicBlock *endMBB;
9860
9861   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9862   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9863   unsigned OffsetReg = 0;
9864
9865   if (!UseGPOffset && !UseFPOffset) {
9866     // If we only pull from the overflow region, we don't create a branch.
9867     // We don't need to alter control flow.
9868     OffsetDestReg = 0; // unused
9869     OverflowDestReg = DestReg;
9870
9871     offsetMBB = NULL;
9872     overflowMBB = thisMBB;
9873     endMBB = thisMBB;
9874   } else {
9875     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9876     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9877     // If not, pull from overflow_area. (branch to overflowMBB)
9878     //
9879     //       thisMBB
9880     //         |     .
9881     //         |        .
9882     //     offsetMBB   overflowMBB
9883     //         |        .
9884     //         |     .
9885     //        endMBB
9886
9887     // Registers for the PHI in endMBB
9888     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9889     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9890
9891     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9892     MachineFunction *MF = MBB->getParent();
9893     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9894     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9895     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9896
9897     MachineFunction::iterator MBBIter = MBB;
9898     ++MBBIter;
9899
9900     // Insert the new basic blocks
9901     MF->insert(MBBIter, offsetMBB);
9902     MF->insert(MBBIter, overflowMBB);
9903     MF->insert(MBBIter, endMBB);
9904
9905     // Transfer the remainder of MBB and its successor edges to endMBB.
9906     endMBB->splice(endMBB->begin(), thisMBB,
9907                     llvm::next(MachineBasicBlock::iterator(MI)),
9908                     thisMBB->end());
9909     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9910
9911     // Make offsetMBB and overflowMBB successors of thisMBB
9912     thisMBB->addSuccessor(offsetMBB);
9913     thisMBB->addSuccessor(overflowMBB);
9914
9915     // endMBB is a successor of both offsetMBB and overflowMBB
9916     offsetMBB->addSuccessor(endMBB);
9917     overflowMBB->addSuccessor(endMBB);
9918
9919     // Load the offset value into a register
9920     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9921     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9922       .addOperand(Base)
9923       .addOperand(Scale)
9924       .addOperand(Index)
9925       .addDisp(Disp, UseFPOffset ? 4 : 0)
9926       .addOperand(Segment)
9927       .setMemRefs(MMOBegin, MMOEnd);
9928
9929     // Check if there is enough room left to pull this argument.
9930     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9931       .addReg(OffsetReg)
9932       .addImm(MaxOffset + 8 - ArgSizeA8);
9933
9934     // Branch to "overflowMBB" if offset >= max
9935     // Fall through to "offsetMBB" otherwise
9936     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9937       .addMBB(overflowMBB);
9938   }
9939
9940   // In offsetMBB, emit code to use the reg_save_area.
9941   if (offsetMBB) {
9942     assert(OffsetReg != 0);
9943
9944     // Read the reg_save_area address.
9945     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9946     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9947       .addOperand(Base)
9948       .addOperand(Scale)
9949       .addOperand(Index)
9950       .addDisp(Disp, 16)
9951       .addOperand(Segment)
9952       .setMemRefs(MMOBegin, MMOEnd);
9953
9954     // Zero-extend the offset
9955     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9956       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9957         .addImm(0)
9958         .addReg(OffsetReg)
9959         .addImm(X86::sub_32bit);
9960
9961     // Add the offset to the reg_save_area to get the final address.
9962     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9963       .addReg(OffsetReg64)
9964       .addReg(RegSaveReg);
9965
9966     // Compute the offset for the next argument
9967     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9968     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9969       .addReg(OffsetReg)
9970       .addImm(UseFPOffset ? 16 : 8);
9971
9972     // Store it back into the va_list.
9973     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9974       .addOperand(Base)
9975       .addOperand(Scale)
9976       .addOperand(Index)
9977       .addDisp(Disp, UseFPOffset ? 4 : 0)
9978       .addOperand(Segment)
9979       .addReg(NextOffsetReg)
9980       .setMemRefs(MMOBegin, MMOEnd);
9981
9982     // Jump to endMBB
9983     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9984       .addMBB(endMBB);
9985   }
9986
9987   //
9988   // Emit code to use overflow area
9989   //
9990
9991   // Load the overflow_area address into a register.
9992   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9993   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9994     .addOperand(Base)
9995     .addOperand(Scale)
9996     .addOperand(Index)
9997     .addDisp(Disp, 8)
9998     .addOperand(Segment)
9999     .setMemRefs(MMOBegin, MMOEnd);
10000
10001   // If we need to align it, do so. Otherwise, just copy the address
10002   // to OverflowDestReg.
10003   if (NeedsAlign) {
10004     // Align the overflow address
10005     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10006     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10007
10008     // aligned_addr = (addr + (align-1)) & ~(align-1)
10009     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10010       .addReg(OverflowAddrReg)
10011       .addImm(Align-1);
10012
10013     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10014       .addReg(TmpReg)
10015       .addImm(~(uint64_t)(Align-1));
10016   } else {
10017     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10018       .addReg(OverflowAddrReg);
10019   }
10020
10021   // Compute the next overflow address after this argument.
10022   // (the overflow address should be kept 8-byte aligned)
10023   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10024   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10025     .addReg(OverflowDestReg)
10026     .addImm(ArgSizeA8);
10027
10028   // Store the new overflow address.
10029   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10030     .addOperand(Base)
10031     .addOperand(Scale)
10032     .addOperand(Index)
10033     .addDisp(Disp, 8)
10034     .addOperand(Segment)
10035     .addReg(NextAddrReg)
10036     .setMemRefs(MMOBegin, MMOEnd);
10037
10038   // If we branched, emit the PHI to the front of endMBB.
10039   if (offsetMBB) {
10040     BuildMI(*endMBB, endMBB->begin(), DL,
10041             TII->get(X86::PHI), DestReg)
10042       .addReg(OffsetDestReg).addMBB(offsetMBB)
10043       .addReg(OverflowDestReg).addMBB(overflowMBB);
10044   }
10045
10046   // Erase the pseudo instruction
10047   MI->eraseFromParent();
10048
10049   return endMBB;
10050 }
10051
10052 MachineBasicBlock *
10053 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10054                                                  MachineInstr *MI,
10055                                                  MachineBasicBlock *MBB) const {
10056   // Emit code to save XMM registers to the stack. The ABI says that the
10057   // number of registers to save is given in %al, so it's theoretically
10058   // possible to do an indirect jump trick to avoid saving all of them,
10059   // however this code takes a simpler approach and just executes all
10060   // of the stores if %al is non-zero. It's less code, and it's probably
10061   // easier on the hardware branch predictor, and stores aren't all that
10062   // expensive anyway.
10063
10064   // Create the new basic blocks. One block contains all the XMM stores,
10065   // and one block is the final destination regardless of whether any
10066   // stores were performed.
10067   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10068   MachineFunction *F = MBB->getParent();
10069   MachineFunction::iterator MBBIter = MBB;
10070   ++MBBIter;
10071   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10072   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10073   F->insert(MBBIter, XMMSaveMBB);
10074   F->insert(MBBIter, EndMBB);
10075
10076   // Transfer the remainder of MBB and its successor edges to EndMBB.
10077   EndMBB->splice(EndMBB->begin(), MBB,
10078                  llvm::next(MachineBasicBlock::iterator(MI)),
10079                  MBB->end());
10080   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10081
10082   // The original block will now fall through to the XMM save block.
10083   MBB->addSuccessor(XMMSaveMBB);
10084   // The XMMSaveMBB will fall through to the end block.
10085   XMMSaveMBB->addSuccessor(EndMBB);
10086
10087   // Now add the instructions.
10088   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10089   DebugLoc DL = MI->getDebugLoc();
10090
10091   unsigned CountReg = MI->getOperand(0).getReg();
10092   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10093   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10094
10095   if (!Subtarget->isTargetWin64()) {
10096     // If %al is 0, branch around the XMM save block.
10097     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10098     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10099     MBB->addSuccessor(EndMBB);
10100   }
10101
10102   // In the XMM save block, save all the XMM argument registers.
10103   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10104     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10105     MachineMemOperand *MMO =
10106       F->getMachineMemOperand(
10107           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10108         MachineMemOperand::MOStore,
10109         /*Size=*/16, /*Align=*/16);
10110     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10111       .addFrameIndex(RegSaveFrameIndex)
10112       .addImm(/*Scale=*/1)
10113       .addReg(/*IndexReg=*/0)
10114       .addImm(/*Disp=*/Offset)
10115       .addReg(/*Segment=*/0)
10116       .addReg(MI->getOperand(i).getReg())
10117       .addMemOperand(MMO);
10118   }
10119
10120   MI->eraseFromParent();   // The pseudo instruction is gone now.
10121
10122   return EndMBB;
10123 }
10124
10125 MachineBasicBlock *
10126 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10127                                      MachineBasicBlock *BB) const {
10128   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10129   DebugLoc DL = MI->getDebugLoc();
10130
10131   // To "insert" a SELECT_CC instruction, we actually have to insert the
10132   // diamond control-flow pattern.  The incoming instruction knows the
10133   // destination vreg to set, the condition code register to branch on, the
10134   // true/false values to select between, and a branch opcode to use.
10135   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10136   MachineFunction::iterator It = BB;
10137   ++It;
10138
10139   //  thisMBB:
10140   //  ...
10141   //   TrueVal = ...
10142   //   cmpTY ccX, r1, r2
10143   //   bCC copy1MBB
10144   //   fallthrough --> copy0MBB
10145   MachineBasicBlock *thisMBB = BB;
10146   MachineFunction *F = BB->getParent();
10147   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10148   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10149   F->insert(It, copy0MBB);
10150   F->insert(It, sinkMBB);
10151
10152   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10153   // live into the sink and copy blocks.
10154   const MachineFunction *MF = BB->getParent();
10155   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10156   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10157
10158   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10159     const MachineOperand &MO = MI->getOperand(I);
10160     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10161     unsigned Reg = MO.getReg();
10162     if (Reg != X86::EFLAGS) continue;
10163     copy0MBB->addLiveIn(Reg);
10164     sinkMBB->addLiveIn(Reg);
10165   }
10166
10167   // Transfer the remainder of BB and its successor edges to sinkMBB.
10168   sinkMBB->splice(sinkMBB->begin(), BB,
10169                   llvm::next(MachineBasicBlock::iterator(MI)),
10170                   BB->end());
10171   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10172
10173   // Add the true and fallthrough blocks as its successors.
10174   BB->addSuccessor(copy0MBB);
10175   BB->addSuccessor(sinkMBB);
10176
10177   // Create the conditional branch instruction.
10178   unsigned Opc =
10179     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10180   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10181
10182   //  copy0MBB:
10183   //   %FalseValue = ...
10184   //   # fallthrough to sinkMBB
10185   copy0MBB->addSuccessor(sinkMBB);
10186
10187   //  sinkMBB:
10188   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10189   //  ...
10190   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10191           TII->get(X86::PHI), MI->getOperand(0).getReg())
10192     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10193     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10194
10195   MI->eraseFromParent();   // The pseudo instruction is gone now.
10196   return sinkMBB;
10197 }
10198
10199 MachineBasicBlock *
10200 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10201                                           MachineBasicBlock *BB) const {
10202   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10203   DebugLoc DL = MI->getDebugLoc();
10204
10205   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10206   // non-trivial part is impdef of ESP.
10207   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10208   // mingw-w64.
10209
10210   const char *StackProbeSymbol =
10211       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10212
10213   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10214     .addExternalSymbol(StackProbeSymbol)
10215     .addReg(X86::EAX, RegState::Implicit)
10216     .addReg(X86::ESP, RegState::Implicit)
10217     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10218     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10219     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10220
10221   MI->eraseFromParent();   // The pseudo instruction is gone now.
10222   return BB;
10223 }
10224
10225 MachineBasicBlock *
10226 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10227                                       MachineBasicBlock *BB) const {
10228   // This is pretty easy.  We're taking the value that we received from
10229   // our load from the relocation, sticking it in either RDI (x86-64)
10230   // or EAX and doing an indirect call.  The return value will then
10231   // be in the normal return register.
10232   const X86InstrInfo *TII
10233     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10234   DebugLoc DL = MI->getDebugLoc();
10235   MachineFunction *F = BB->getParent();
10236
10237   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10238   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10239
10240   if (Subtarget->is64Bit()) {
10241     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10242                                       TII->get(X86::MOV64rm), X86::RDI)
10243     .addReg(X86::RIP)
10244     .addImm(0).addReg(0)
10245     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10246                       MI->getOperand(3).getTargetFlags())
10247     .addReg(0);
10248     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10249     addDirectMem(MIB, X86::RDI);
10250   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10251     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10252                                       TII->get(X86::MOV32rm), X86::EAX)
10253     .addReg(0)
10254     .addImm(0).addReg(0)
10255     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10256                       MI->getOperand(3).getTargetFlags())
10257     .addReg(0);
10258     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10259     addDirectMem(MIB, X86::EAX);
10260   } else {
10261     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10262                                       TII->get(X86::MOV32rm), X86::EAX)
10263     .addReg(TII->getGlobalBaseReg(F))
10264     .addImm(0).addReg(0)
10265     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10266                       MI->getOperand(3).getTargetFlags())
10267     .addReg(0);
10268     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10269     addDirectMem(MIB, X86::EAX);
10270   }
10271
10272   MI->eraseFromParent(); // The pseudo instruction is gone now.
10273   return BB;
10274 }
10275
10276 MachineBasicBlock *
10277 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10278                                                MachineBasicBlock *BB) const {
10279   switch (MI->getOpcode()) {
10280   default: assert(false && "Unexpected instr type to insert");
10281   case X86::TAILJMPd64:
10282   case X86::TAILJMPr64:
10283   case X86::TAILJMPm64:
10284     assert(!"TAILJMP64 would not be touched here.");
10285   case X86::TCRETURNdi64:
10286   case X86::TCRETURNri64:
10287   case X86::TCRETURNmi64:
10288     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10289     // On AMD64, additional defs should be added before register allocation.
10290     if (!Subtarget->isTargetWin64()) {
10291       MI->addRegisterDefined(X86::RSI);
10292       MI->addRegisterDefined(X86::RDI);
10293       MI->addRegisterDefined(X86::XMM6);
10294       MI->addRegisterDefined(X86::XMM7);
10295       MI->addRegisterDefined(X86::XMM8);
10296       MI->addRegisterDefined(X86::XMM9);
10297       MI->addRegisterDefined(X86::XMM10);
10298       MI->addRegisterDefined(X86::XMM11);
10299       MI->addRegisterDefined(X86::XMM12);
10300       MI->addRegisterDefined(X86::XMM13);
10301       MI->addRegisterDefined(X86::XMM14);
10302       MI->addRegisterDefined(X86::XMM15);
10303     }
10304     return BB;
10305   case X86::WIN_ALLOCA:
10306     return EmitLoweredWinAlloca(MI, BB);
10307   case X86::TLSCall_32:
10308   case X86::TLSCall_64:
10309     return EmitLoweredTLSCall(MI, BB);
10310   case X86::CMOV_GR8:
10311   case X86::CMOV_FR32:
10312   case X86::CMOV_FR64:
10313   case X86::CMOV_V4F32:
10314   case X86::CMOV_V2F64:
10315   case X86::CMOV_V2I64:
10316   case X86::CMOV_GR16:
10317   case X86::CMOV_GR32:
10318   case X86::CMOV_RFP32:
10319   case X86::CMOV_RFP64:
10320   case X86::CMOV_RFP80:
10321     return EmitLoweredSelect(MI, BB);
10322
10323   case X86::FP32_TO_INT16_IN_MEM:
10324   case X86::FP32_TO_INT32_IN_MEM:
10325   case X86::FP32_TO_INT64_IN_MEM:
10326   case X86::FP64_TO_INT16_IN_MEM:
10327   case X86::FP64_TO_INT32_IN_MEM:
10328   case X86::FP64_TO_INT64_IN_MEM:
10329   case X86::FP80_TO_INT16_IN_MEM:
10330   case X86::FP80_TO_INT32_IN_MEM:
10331   case X86::FP80_TO_INT64_IN_MEM: {
10332     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10333     DebugLoc DL = MI->getDebugLoc();
10334
10335     // Change the floating point control register to use "round towards zero"
10336     // mode when truncating to an integer value.
10337     MachineFunction *F = BB->getParent();
10338     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10339     addFrameReference(BuildMI(*BB, MI, DL,
10340                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10341
10342     // Load the old value of the high byte of the control word...
10343     unsigned OldCW =
10344       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10345     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10346                       CWFrameIdx);
10347
10348     // Set the high part to be round to zero...
10349     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10350       .addImm(0xC7F);
10351
10352     // Reload the modified control word now...
10353     addFrameReference(BuildMI(*BB, MI, DL,
10354                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10355
10356     // Restore the memory image of control word to original value
10357     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10358       .addReg(OldCW);
10359
10360     // Get the X86 opcode to use.
10361     unsigned Opc;
10362     switch (MI->getOpcode()) {
10363     default: llvm_unreachable("illegal opcode!");
10364     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10365     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10366     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10367     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10368     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10369     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10370     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10371     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10372     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10373     }
10374
10375     X86AddressMode AM;
10376     MachineOperand &Op = MI->getOperand(0);
10377     if (Op.isReg()) {
10378       AM.BaseType = X86AddressMode::RegBase;
10379       AM.Base.Reg = Op.getReg();
10380     } else {
10381       AM.BaseType = X86AddressMode::FrameIndexBase;
10382       AM.Base.FrameIndex = Op.getIndex();
10383     }
10384     Op = MI->getOperand(1);
10385     if (Op.isImm())
10386       AM.Scale = Op.getImm();
10387     Op = MI->getOperand(2);
10388     if (Op.isImm())
10389       AM.IndexReg = Op.getImm();
10390     Op = MI->getOperand(3);
10391     if (Op.isGlobal()) {
10392       AM.GV = Op.getGlobal();
10393     } else {
10394       AM.Disp = Op.getImm();
10395     }
10396     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10397                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10398
10399     // Reload the original control word now.
10400     addFrameReference(BuildMI(*BB, MI, DL,
10401                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10402
10403     MI->eraseFromParent();   // The pseudo instruction is gone now.
10404     return BB;
10405   }
10406     // String/text processing lowering.
10407   case X86::PCMPISTRM128REG:
10408   case X86::VPCMPISTRM128REG:
10409     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10410   case X86::PCMPISTRM128MEM:
10411   case X86::VPCMPISTRM128MEM:
10412     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10413   case X86::PCMPESTRM128REG:
10414   case X86::VPCMPESTRM128REG:
10415     return EmitPCMP(MI, BB, 5, false /* in mem */);
10416   case X86::PCMPESTRM128MEM:
10417   case X86::VPCMPESTRM128MEM:
10418     return EmitPCMP(MI, BB, 5, true /* in mem */);
10419
10420     // Thread synchronization.
10421   case X86::MONITOR:
10422     return EmitMonitor(MI, BB);
10423   case X86::MWAIT:
10424     return EmitMwait(MI, BB);
10425
10426     // Atomic Lowering.
10427   case X86::ATOMAND32:
10428     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10429                                                X86::AND32ri, X86::MOV32rm,
10430                                                X86::LCMPXCHG32,
10431                                                X86::NOT32r, X86::EAX,
10432                                                X86::GR32RegisterClass);
10433   case X86::ATOMOR32:
10434     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10435                                                X86::OR32ri, X86::MOV32rm,
10436                                                X86::LCMPXCHG32,
10437                                                X86::NOT32r, X86::EAX,
10438                                                X86::GR32RegisterClass);
10439   case X86::ATOMXOR32:
10440     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10441                                                X86::XOR32ri, X86::MOV32rm,
10442                                                X86::LCMPXCHG32,
10443                                                X86::NOT32r, X86::EAX,
10444                                                X86::GR32RegisterClass);
10445   case X86::ATOMNAND32:
10446     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10447                                                X86::AND32ri, X86::MOV32rm,
10448                                                X86::LCMPXCHG32,
10449                                                X86::NOT32r, X86::EAX,
10450                                                X86::GR32RegisterClass, true);
10451   case X86::ATOMMIN32:
10452     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10453   case X86::ATOMMAX32:
10454     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10455   case X86::ATOMUMIN32:
10456     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10457   case X86::ATOMUMAX32:
10458     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10459
10460   case X86::ATOMAND16:
10461     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10462                                                X86::AND16ri, X86::MOV16rm,
10463                                                X86::LCMPXCHG16,
10464                                                X86::NOT16r, X86::AX,
10465                                                X86::GR16RegisterClass);
10466   case X86::ATOMOR16:
10467     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10468                                                X86::OR16ri, X86::MOV16rm,
10469                                                X86::LCMPXCHG16,
10470                                                X86::NOT16r, X86::AX,
10471                                                X86::GR16RegisterClass);
10472   case X86::ATOMXOR16:
10473     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10474                                                X86::XOR16ri, X86::MOV16rm,
10475                                                X86::LCMPXCHG16,
10476                                                X86::NOT16r, X86::AX,
10477                                                X86::GR16RegisterClass);
10478   case X86::ATOMNAND16:
10479     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10480                                                X86::AND16ri, X86::MOV16rm,
10481                                                X86::LCMPXCHG16,
10482                                                X86::NOT16r, X86::AX,
10483                                                X86::GR16RegisterClass, true);
10484   case X86::ATOMMIN16:
10485     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10486   case X86::ATOMMAX16:
10487     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10488   case X86::ATOMUMIN16:
10489     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10490   case X86::ATOMUMAX16:
10491     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10492
10493   case X86::ATOMAND8:
10494     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10495                                                X86::AND8ri, X86::MOV8rm,
10496                                                X86::LCMPXCHG8,
10497                                                X86::NOT8r, X86::AL,
10498                                                X86::GR8RegisterClass);
10499   case X86::ATOMOR8:
10500     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10501                                                X86::OR8ri, X86::MOV8rm,
10502                                                X86::LCMPXCHG8,
10503                                                X86::NOT8r, X86::AL,
10504                                                X86::GR8RegisterClass);
10505   case X86::ATOMXOR8:
10506     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10507                                                X86::XOR8ri, X86::MOV8rm,
10508                                                X86::LCMPXCHG8,
10509                                                X86::NOT8r, X86::AL,
10510                                                X86::GR8RegisterClass);
10511   case X86::ATOMNAND8:
10512     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10513                                                X86::AND8ri, X86::MOV8rm,
10514                                                X86::LCMPXCHG8,
10515                                                X86::NOT8r, X86::AL,
10516                                                X86::GR8RegisterClass, true);
10517   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10518   // This group is for 64-bit host.
10519   case X86::ATOMAND64:
10520     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10521                                                X86::AND64ri32, X86::MOV64rm,
10522                                                X86::LCMPXCHG64,
10523                                                X86::NOT64r, X86::RAX,
10524                                                X86::GR64RegisterClass);
10525   case X86::ATOMOR64:
10526     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10527                                                X86::OR64ri32, X86::MOV64rm,
10528                                                X86::LCMPXCHG64,
10529                                                X86::NOT64r, X86::RAX,
10530                                                X86::GR64RegisterClass);
10531   case X86::ATOMXOR64:
10532     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10533                                                X86::XOR64ri32, X86::MOV64rm,
10534                                                X86::LCMPXCHG64,
10535                                                X86::NOT64r, X86::RAX,
10536                                                X86::GR64RegisterClass);
10537   case X86::ATOMNAND64:
10538     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10539                                                X86::AND64ri32, X86::MOV64rm,
10540                                                X86::LCMPXCHG64,
10541                                                X86::NOT64r, X86::RAX,
10542                                                X86::GR64RegisterClass, true);
10543   case X86::ATOMMIN64:
10544     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10545   case X86::ATOMMAX64:
10546     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10547   case X86::ATOMUMIN64:
10548     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10549   case X86::ATOMUMAX64:
10550     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10551
10552   // This group does 64-bit operations on a 32-bit host.
10553   case X86::ATOMAND6432:
10554     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10555                                                X86::AND32rr, X86::AND32rr,
10556                                                X86::AND32ri, X86::AND32ri,
10557                                                false);
10558   case X86::ATOMOR6432:
10559     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10560                                                X86::OR32rr, X86::OR32rr,
10561                                                X86::OR32ri, X86::OR32ri,
10562                                                false);
10563   case X86::ATOMXOR6432:
10564     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10565                                                X86::XOR32rr, X86::XOR32rr,
10566                                                X86::XOR32ri, X86::XOR32ri,
10567                                                false);
10568   case X86::ATOMNAND6432:
10569     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10570                                                X86::AND32rr, X86::AND32rr,
10571                                                X86::AND32ri, X86::AND32ri,
10572                                                true);
10573   case X86::ATOMADD6432:
10574     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10575                                                X86::ADD32rr, X86::ADC32rr,
10576                                                X86::ADD32ri, X86::ADC32ri,
10577                                                false);
10578   case X86::ATOMSUB6432:
10579     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10580                                                X86::SUB32rr, X86::SBB32rr,
10581                                                X86::SUB32ri, X86::SBB32ri,
10582                                                false);
10583   case X86::ATOMSWAP6432:
10584     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10585                                                X86::MOV32rr, X86::MOV32rr,
10586                                                X86::MOV32ri, X86::MOV32ri,
10587                                                false);
10588   case X86::VASTART_SAVE_XMM_REGS:
10589     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10590
10591   case X86::VAARG_64:
10592     return EmitVAARG64WithCustomInserter(MI, BB);
10593   }
10594 }
10595
10596 //===----------------------------------------------------------------------===//
10597 //                           X86 Optimization Hooks
10598 //===----------------------------------------------------------------------===//
10599
10600 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10601                                                        const APInt &Mask,
10602                                                        APInt &KnownZero,
10603                                                        APInt &KnownOne,
10604                                                        const SelectionDAG &DAG,
10605                                                        unsigned Depth) const {
10606   unsigned Opc = Op.getOpcode();
10607   assert((Opc >= ISD::BUILTIN_OP_END ||
10608           Opc == ISD::INTRINSIC_WO_CHAIN ||
10609           Opc == ISD::INTRINSIC_W_CHAIN ||
10610           Opc == ISD::INTRINSIC_VOID) &&
10611          "Should use MaskedValueIsZero if you don't know whether Op"
10612          " is a target node!");
10613
10614   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10615   switch (Opc) {
10616   default: break;
10617   case X86ISD::ADD:
10618   case X86ISD::SUB:
10619   case X86ISD::ADC:
10620   case X86ISD::SBB:
10621   case X86ISD::SMUL:
10622   case X86ISD::UMUL:
10623   case X86ISD::INC:
10624   case X86ISD::DEC:
10625   case X86ISD::OR:
10626   case X86ISD::XOR:
10627   case X86ISD::AND:
10628     // These nodes' second result is a boolean.
10629     if (Op.getResNo() == 0)
10630       break;
10631     // Fallthrough
10632   case X86ISD::SETCC:
10633     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10634                                        Mask.getBitWidth() - 1);
10635     break;
10636   }
10637 }
10638
10639 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10640                                                          unsigned Depth) const {
10641   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10642   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10643     return Op.getValueType().getScalarType().getSizeInBits();
10644
10645   // Fallback case.
10646   return 1;
10647 }
10648
10649 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10650 /// node is a GlobalAddress + offset.
10651 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10652                                        const GlobalValue* &GA,
10653                                        int64_t &Offset) const {
10654   if (N->getOpcode() == X86ISD::Wrapper) {
10655     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10656       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10657       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10658       return true;
10659     }
10660   }
10661   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10662 }
10663
10664 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10665 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10666 /// if the load addresses are consecutive, non-overlapping, and in the right
10667 /// order.
10668 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10669                                      TargetLowering::DAGCombinerInfo &DCI) {
10670   DebugLoc dl = N->getDebugLoc();
10671   EVT VT = N->getValueType(0);
10672
10673   if (VT.getSizeInBits() != 128)
10674     return SDValue();
10675
10676   // Don't create instructions with illegal types after legalize types has run.
10677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10678   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10679     return SDValue();
10680
10681   SmallVector<SDValue, 16> Elts;
10682   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10683     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10684
10685   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10686 }
10687
10688 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10689 /// generation and convert it from being a bunch of shuffles and extracts
10690 /// to a simple store and scalar loads to extract the elements.
10691 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10692                                                 const TargetLowering &TLI) {
10693   SDValue InputVector = N->getOperand(0);
10694
10695   // Only operate on vectors of 4 elements, where the alternative shuffling
10696   // gets to be more expensive.
10697   if (InputVector.getValueType() != MVT::v4i32)
10698     return SDValue();
10699
10700   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10701   // single use which is a sign-extend or zero-extend, and all elements are
10702   // used.
10703   SmallVector<SDNode *, 4> Uses;
10704   unsigned ExtractedElements = 0;
10705   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10706        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10707     if (UI.getUse().getResNo() != InputVector.getResNo())
10708       return SDValue();
10709
10710     SDNode *Extract = *UI;
10711     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10712       return SDValue();
10713
10714     if (Extract->getValueType(0) != MVT::i32)
10715       return SDValue();
10716     if (!Extract->hasOneUse())
10717       return SDValue();
10718     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10719         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10720       return SDValue();
10721     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10722       return SDValue();
10723
10724     // Record which element was extracted.
10725     ExtractedElements |=
10726       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10727
10728     Uses.push_back(Extract);
10729   }
10730
10731   // If not all the elements were used, this may not be worthwhile.
10732   if (ExtractedElements != 15)
10733     return SDValue();
10734
10735   // Ok, we've now decided to do the transformation.
10736   DebugLoc dl = InputVector.getDebugLoc();
10737
10738   // Store the value to a temporary stack slot.
10739   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10740   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10741                             MachinePointerInfo(), false, false, 0);
10742
10743   // Replace each use (extract) with a load of the appropriate element.
10744   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10745        UE = Uses.end(); UI != UE; ++UI) {
10746     SDNode *Extract = *UI;
10747
10748     // Compute the element's address.
10749     SDValue Idx = Extract->getOperand(1);
10750     unsigned EltSize =
10751         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10752     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10753     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10754
10755     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10756                                      StackPtr, OffsetVal);
10757
10758     // Load the scalar.
10759     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10760                                      ScalarAddr, MachinePointerInfo(),
10761                                      false, false, 0);
10762
10763     // Replace the exact with the load.
10764     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10765   }
10766
10767   // The replacement was made in place; don't return anything.
10768   return SDValue();
10769 }
10770
10771 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10772 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10773                                     const X86Subtarget *Subtarget) {
10774   DebugLoc DL = N->getDebugLoc();
10775   SDValue Cond = N->getOperand(0);
10776   // Get the LHS/RHS of the select.
10777   SDValue LHS = N->getOperand(1);
10778   SDValue RHS = N->getOperand(2);
10779
10780   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10781   // instructions match the semantics of the common C idiom x<y?x:y but not
10782   // x<=y?x:y, because of how they handle negative zero (which can be
10783   // ignored in unsafe-math mode).
10784   if (Subtarget->hasSSE2() &&
10785       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10786       Cond.getOpcode() == ISD::SETCC) {
10787     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10788
10789     unsigned Opcode = 0;
10790     // Check for x CC y ? x : y.
10791     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10792         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10793       switch (CC) {
10794       default: break;
10795       case ISD::SETULT:
10796         // Converting this to a min would handle NaNs incorrectly, and swapping
10797         // the operands would cause it to handle comparisons between positive
10798         // and negative zero incorrectly.
10799         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10800           if (!UnsafeFPMath &&
10801               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10802             break;
10803           std::swap(LHS, RHS);
10804         }
10805         Opcode = X86ISD::FMIN;
10806         break;
10807       case ISD::SETOLE:
10808         // Converting this to a min would handle comparisons between positive
10809         // and negative zero incorrectly.
10810         if (!UnsafeFPMath &&
10811             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10812           break;
10813         Opcode = X86ISD::FMIN;
10814         break;
10815       case ISD::SETULE:
10816         // Converting this to a min would handle both negative zeros and NaNs
10817         // incorrectly, but we can swap the operands to fix both.
10818         std::swap(LHS, RHS);
10819       case ISD::SETOLT:
10820       case ISD::SETLT:
10821       case ISD::SETLE:
10822         Opcode = X86ISD::FMIN;
10823         break;
10824
10825       case ISD::SETOGE:
10826         // Converting this to a max would handle comparisons between positive
10827         // and negative zero incorrectly.
10828         if (!UnsafeFPMath &&
10829             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10830           break;
10831         Opcode = X86ISD::FMAX;
10832         break;
10833       case ISD::SETUGT:
10834         // Converting this to a max would handle NaNs incorrectly, and swapping
10835         // the operands would cause it to handle comparisons between positive
10836         // and negative zero incorrectly.
10837         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10838           if (!UnsafeFPMath &&
10839               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10840             break;
10841           std::swap(LHS, RHS);
10842         }
10843         Opcode = X86ISD::FMAX;
10844         break;
10845       case ISD::SETUGE:
10846         // Converting this to a max would handle both negative zeros and NaNs
10847         // incorrectly, but we can swap the operands to fix both.
10848         std::swap(LHS, RHS);
10849       case ISD::SETOGT:
10850       case ISD::SETGT:
10851       case ISD::SETGE:
10852         Opcode = X86ISD::FMAX;
10853         break;
10854       }
10855     // Check for x CC y ? y : x -- a min/max with reversed arms.
10856     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10857                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10858       switch (CC) {
10859       default: break;
10860       case ISD::SETOGE:
10861         // Converting this to a min would handle comparisons between positive
10862         // and negative zero incorrectly, and swapping the operands would
10863         // cause it to handle NaNs incorrectly.
10864         if (!UnsafeFPMath &&
10865             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10866           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10867             break;
10868           std::swap(LHS, RHS);
10869         }
10870         Opcode = X86ISD::FMIN;
10871         break;
10872       case ISD::SETUGT:
10873         // Converting this to a min would handle NaNs incorrectly.
10874         if (!UnsafeFPMath &&
10875             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10876           break;
10877         Opcode = X86ISD::FMIN;
10878         break;
10879       case ISD::SETUGE:
10880         // Converting this to a min would handle both negative zeros and NaNs
10881         // incorrectly, but we can swap the operands to fix both.
10882         std::swap(LHS, RHS);
10883       case ISD::SETOGT:
10884       case ISD::SETGT:
10885       case ISD::SETGE:
10886         Opcode = X86ISD::FMIN;
10887         break;
10888
10889       case ISD::SETULT:
10890         // Converting this to a max would handle NaNs incorrectly.
10891         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10892           break;
10893         Opcode = X86ISD::FMAX;
10894         break;
10895       case ISD::SETOLE:
10896         // Converting this to a max would handle comparisons between positive
10897         // and negative zero incorrectly, and swapping the operands would
10898         // cause it to handle NaNs incorrectly.
10899         if (!UnsafeFPMath &&
10900             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10901           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10902             break;
10903           std::swap(LHS, RHS);
10904         }
10905         Opcode = X86ISD::FMAX;
10906         break;
10907       case ISD::SETULE:
10908         // Converting this to a max would handle both negative zeros and NaNs
10909         // incorrectly, but we can swap the operands to fix both.
10910         std::swap(LHS, RHS);
10911       case ISD::SETOLT:
10912       case ISD::SETLT:
10913       case ISD::SETLE:
10914         Opcode = X86ISD::FMAX;
10915         break;
10916       }
10917     }
10918
10919     if (Opcode)
10920       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10921   }
10922
10923   // If this is a select between two integer constants, try to do some
10924   // optimizations.
10925   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10926     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10927       // Don't do this for crazy integer types.
10928       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10929         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10930         // so that TrueC (the true value) is larger than FalseC.
10931         bool NeedsCondInvert = false;
10932
10933         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10934             // Efficiently invertible.
10935             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10936              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10937               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10938           NeedsCondInvert = true;
10939           std::swap(TrueC, FalseC);
10940         }
10941
10942         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10943         if (FalseC->getAPIntValue() == 0 &&
10944             TrueC->getAPIntValue().isPowerOf2()) {
10945           if (NeedsCondInvert) // Invert the condition if needed.
10946             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10947                                DAG.getConstant(1, Cond.getValueType()));
10948
10949           // Zero extend the condition if needed.
10950           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10951
10952           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10953           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10954                              DAG.getConstant(ShAmt, MVT::i8));
10955         }
10956
10957         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10958         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10959           if (NeedsCondInvert) // Invert the condition if needed.
10960             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10961                                DAG.getConstant(1, Cond.getValueType()));
10962
10963           // Zero extend the condition if needed.
10964           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10965                              FalseC->getValueType(0), Cond);
10966           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10967                              SDValue(FalseC, 0));
10968         }
10969
10970         // Optimize cases that will turn into an LEA instruction.  This requires
10971         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10972         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10973           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10974           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10975
10976           bool isFastMultiplier = false;
10977           if (Diff < 10) {
10978             switch ((unsigned char)Diff) {
10979               default: break;
10980               case 1:  // result = add base, cond
10981               case 2:  // result = lea base(    , cond*2)
10982               case 3:  // result = lea base(cond, cond*2)
10983               case 4:  // result = lea base(    , cond*4)
10984               case 5:  // result = lea base(cond, cond*4)
10985               case 8:  // result = lea base(    , cond*8)
10986               case 9:  // result = lea base(cond, cond*8)
10987                 isFastMultiplier = true;
10988                 break;
10989             }
10990           }
10991
10992           if (isFastMultiplier) {
10993             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10994             if (NeedsCondInvert) // Invert the condition if needed.
10995               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10996                                  DAG.getConstant(1, Cond.getValueType()));
10997
10998             // Zero extend the condition if needed.
10999             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11000                                Cond);
11001             // Scale the condition by the difference.
11002             if (Diff != 1)
11003               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11004                                  DAG.getConstant(Diff, Cond.getValueType()));
11005
11006             // Add the base if non-zero.
11007             if (FalseC->getAPIntValue() != 0)
11008               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11009                                  SDValue(FalseC, 0));
11010             return Cond;
11011           }
11012         }
11013       }
11014   }
11015
11016   return SDValue();
11017 }
11018
11019 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11020 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11021                                   TargetLowering::DAGCombinerInfo &DCI) {
11022   DebugLoc DL = N->getDebugLoc();
11023
11024   // If the flag operand isn't dead, don't touch this CMOV.
11025   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11026     return SDValue();
11027
11028   // If this is a select between two integer constants, try to do some
11029   // optimizations.  Note that the operands are ordered the opposite of SELECT
11030   // operands.
11031   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11032     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11033       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11034       // larger than FalseC (the false value).
11035       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11036
11037       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11038         CC = X86::GetOppositeBranchCondition(CC);
11039         std::swap(TrueC, FalseC);
11040       }
11041
11042       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11043       // This is efficient for any integer data type (including i8/i16) and
11044       // shift amount.
11045       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11046         SDValue Cond = N->getOperand(3);
11047         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11048                            DAG.getConstant(CC, MVT::i8), Cond);
11049
11050         // Zero extend the condition if needed.
11051         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11052
11053         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11054         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11055                            DAG.getConstant(ShAmt, MVT::i8));
11056         if (N->getNumValues() == 2)  // Dead flag value?
11057           return DCI.CombineTo(N, Cond, SDValue());
11058         return Cond;
11059       }
11060
11061       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11062       // for any integer data type, including i8/i16.
11063       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11064         SDValue Cond = N->getOperand(3);
11065         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11066                            DAG.getConstant(CC, MVT::i8), Cond);
11067
11068         // Zero extend the condition if needed.
11069         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11070                            FalseC->getValueType(0), Cond);
11071         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11072                            SDValue(FalseC, 0));
11073
11074         if (N->getNumValues() == 2)  // Dead flag value?
11075           return DCI.CombineTo(N, Cond, SDValue());
11076         return Cond;
11077       }
11078
11079       // Optimize cases that will turn into an LEA instruction.  This requires
11080       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11081       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11082         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11083         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11084
11085         bool isFastMultiplier = false;
11086         if (Diff < 10) {
11087           switch ((unsigned char)Diff) {
11088           default: break;
11089           case 1:  // result = add base, cond
11090           case 2:  // result = lea base(    , cond*2)
11091           case 3:  // result = lea base(cond, cond*2)
11092           case 4:  // result = lea base(    , cond*4)
11093           case 5:  // result = lea base(cond, cond*4)
11094           case 8:  // result = lea base(    , cond*8)
11095           case 9:  // result = lea base(cond, cond*8)
11096             isFastMultiplier = true;
11097             break;
11098           }
11099         }
11100
11101         if (isFastMultiplier) {
11102           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11103           SDValue Cond = N->getOperand(3);
11104           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11105                              DAG.getConstant(CC, MVT::i8), Cond);
11106           // Zero extend the condition if needed.
11107           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11108                              Cond);
11109           // Scale the condition by the difference.
11110           if (Diff != 1)
11111             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11112                                DAG.getConstant(Diff, Cond.getValueType()));
11113
11114           // Add the base if non-zero.
11115           if (FalseC->getAPIntValue() != 0)
11116             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11117                                SDValue(FalseC, 0));
11118           if (N->getNumValues() == 2)  // Dead flag value?
11119             return DCI.CombineTo(N, Cond, SDValue());
11120           return Cond;
11121         }
11122       }
11123     }
11124   }
11125   return SDValue();
11126 }
11127
11128
11129 /// PerformMulCombine - Optimize a single multiply with constant into two
11130 /// in order to implement it with two cheaper instructions, e.g.
11131 /// LEA + SHL, LEA + LEA.
11132 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11133                                  TargetLowering::DAGCombinerInfo &DCI) {
11134   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11135     return SDValue();
11136
11137   EVT VT = N->getValueType(0);
11138   if (VT != MVT::i64)
11139     return SDValue();
11140
11141   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11142   if (!C)
11143     return SDValue();
11144   uint64_t MulAmt = C->getZExtValue();
11145   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11146     return SDValue();
11147
11148   uint64_t MulAmt1 = 0;
11149   uint64_t MulAmt2 = 0;
11150   if ((MulAmt % 9) == 0) {
11151     MulAmt1 = 9;
11152     MulAmt2 = MulAmt / 9;
11153   } else if ((MulAmt % 5) == 0) {
11154     MulAmt1 = 5;
11155     MulAmt2 = MulAmt / 5;
11156   } else if ((MulAmt % 3) == 0) {
11157     MulAmt1 = 3;
11158     MulAmt2 = MulAmt / 3;
11159   }
11160   if (MulAmt2 &&
11161       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11162     DebugLoc DL = N->getDebugLoc();
11163
11164     if (isPowerOf2_64(MulAmt2) &&
11165         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11166       // If second multiplifer is pow2, issue it first. We want the multiply by
11167       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11168       // is an add.
11169       std::swap(MulAmt1, MulAmt2);
11170
11171     SDValue NewMul;
11172     if (isPowerOf2_64(MulAmt1))
11173       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11174                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11175     else
11176       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11177                            DAG.getConstant(MulAmt1, VT));
11178
11179     if (isPowerOf2_64(MulAmt2))
11180       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11181                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11182     else
11183       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11184                            DAG.getConstant(MulAmt2, VT));
11185
11186     // Do not add new nodes to DAG combiner worklist.
11187     DCI.CombineTo(N, NewMul, false);
11188   }
11189   return SDValue();
11190 }
11191
11192 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11193   SDValue N0 = N->getOperand(0);
11194   SDValue N1 = N->getOperand(1);
11195   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11196   EVT VT = N0.getValueType();
11197
11198   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11199   // since the result of setcc_c is all zero's or all ones.
11200   if (N1C && N0.getOpcode() == ISD::AND &&
11201       N0.getOperand(1).getOpcode() == ISD::Constant) {
11202     SDValue N00 = N0.getOperand(0);
11203     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11204         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11205           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11206          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11207       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11208       APInt ShAmt = N1C->getAPIntValue();
11209       Mask = Mask.shl(ShAmt);
11210       if (Mask != 0)
11211         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11212                            N00, DAG.getConstant(Mask, VT));
11213     }
11214   }
11215
11216   return SDValue();
11217 }
11218
11219 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11220 ///                       when possible.
11221 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11222                                    const X86Subtarget *Subtarget) {
11223   EVT VT = N->getValueType(0);
11224   if (!VT.isVector() && VT.isInteger() &&
11225       N->getOpcode() == ISD::SHL)
11226     return PerformSHLCombine(N, DAG);
11227
11228   // On X86 with SSE2 support, we can transform this to a vector shift if
11229   // all elements are shifted by the same amount.  We can't do this in legalize
11230   // because the a constant vector is typically transformed to a constant pool
11231   // so we have no knowledge of the shift amount.
11232   if (!Subtarget->hasSSE2())
11233     return SDValue();
11234
11235   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11236     return SDValue();
11237
11238   SDValue ShAmtOp = N->getOperand(1);
11239   EVT EltVT = VT.getVectorElementType();
11240   DebugLoc DL = N->getDebugLoc();
11241   SDValue BaseShAmt = SDValue();
11242   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11243     unsigned NumElts = VT.getVectorNumElements();
11244     unsigned i = 0;
11245     for (; i != NumElts; ++i) {
11246       SDValue Arg = ShAmtOp.getOperand(i);
11247       if (Arg.getOpcode() == ISD::UNDEF) continue;
11248       BaseShAmt = Arg;
11249       break;
11250     }
11251     for (; i != NumElts; ++i) {
11252       SDValue Arg = ShAmtOp.getOperand(i);
11253       if (Arg.getOpcode() == ISD::UNDEF) continue;
11254       if (Arg != BaseShAmt) {
11255         return SDValue();
11256       }
11257     }
11258   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11259              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11260     SDValue InVec = ShAmtOp.getOperand(0);
11261     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11262       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11263       unsigned i = 0;
11264       for (; i != NumElts; ++i) {
11265         SDValue Arg = InVec.getOperand(i);
11266         if (Arg.getOpcode() == ISD::UNDEF) continue;
11267         BaseShAmt = Arg;
11268         break;
11269       }
11270     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11271        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11272          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11273          if (C->getZExtValue() == SplatIdx)
11274            BaseShAmt = InVec.getOperand(1);
11275        }
11276     }
11277     if (BaseShAmt.getNode() == 0)
11278       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11279                               DAG.getIntPtrConstant(0));
11280   } else
11281     return SDValue();
11282
11283   // The shift amount is an i32.
11284   if (EltVT.bitsGT(MVT::i32))
11285     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11286   else if (EltVT.bitsLT(MVT::i32))
11287     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11288
11289   // The shift amount is identical so we can do a vector shift.
11290   SDValue  ValOp = N->getOperand(0);
11291   switch (N->getOpcode()) {
11292   default:
11293     llvm_unreachable("Unknown shift opcode!");
11294     break;
11295   case ISD::SHL:
11296     if (VT == MVT::v2i64)
11297       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11298                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11299                          ValOp, BaseShAmt);
11300     if (VT == MVT::v4i32)
11301       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11302                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11303                          ValOp, BaseShAmt);
11304     if (VT == MVT::v8i16)
11305       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11306                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11307                          ValOp, BaseShAmt);
11308     break;
11309   case ISD::SRA:
11310     if (VT == MVT::v4i32)
11311       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11312                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11313                          ValOp, BaseShAmt);
11314     if (VT == MVT::v8i16)
11315       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11316                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11317                          ValOp, BaseShAmt);
11318     break;
11319   case ISD::SRL:
11320     if (VT == MVT::v2i64)
11321       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11322                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11323                          ValOp, BaseShAmt);
11324     if (VT == MVT::v4i32)
11325       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11326                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11327                          ValOp, BaseShAmt);
11328     if (VT ==  MVT::v8i16)
11329       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11330                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11331                          ValOp, BaseShAmt);
11332     break;
11333   }
11334   return SDValue();
11335 }
11336
11337
11338 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11339                                  TargetLowering::DAGCombinerInfo &DCI,
11340                                  const X86Subtarget *Subtarget) {
11341   if (DCI.isBeforeLegalizeOps())
11342     return SDValue();
11343
11344   // Want to form PANDN nodes, in the hopes of then easily combining them with
11345   // OR and AND nodes to form PBLEND/PSIGN.
11346   EVT VT = N->getValueType(0);
11347   if (VT != MVT::v2i64)
11348     return SDValue();
11349
11350   SDValue N0 = N->getOperand(0);
11351   SDValue N1 = N->getOperand(1);
11352   DebugLoc DL = N->getDebugLoc();
11353
11354   // Check LHS for vnot
11355   if (N0.getOpcode() == ISD::XOR &&
11356       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11357     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11358
11359   // Check RHS for vnot
11360   if (N1.getOpcode() == ISD::XOR &&
11361       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11362     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11363
11364   return SDValue();
11365 }
11366
11367 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11368                                 TargetLowering::DAGCombinerInfo &DCI,
11369                                 const X86Subtarget *Subtarget) {
11370   if (DCI.isBeforeLegalizeOps())
11371     return SDValue();
11372
11373   EVT VT = N->getValueType(0);
11374   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11375     return SDValue();
11376
11377   SDValue N0 = N->getOperand(0);
11378   SDValue N1 = N->getOperand(1);
11379
11380   // look for psign/blend
11381   if (Subtarget->hasSSSE3()) {
11382     if (VT == MVT::v2i64) {
11383       // Canonicalize pandn to RHS
11384       if (N0.getOpcode() == X86ISD::PANDN)
11385         std::swap(N0, N1);
11386       // or (and (m, x), (pandn m, y))
11387       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11388         SDValue Mask = N1.getOperand(0);
11389         SDValue X    = N1.getOperand(1);
11390         SDValue Y;
11391         if (N0.getOperand(0) == Mask)
11392           Y = N0.getOperand(1);
11393         if (N0.getOperand(1) == Mask)
11394           Y = N0.getOperand(0);
11395
11396         // Check to see if the mask appeared in both the AND and PANDN and
11397         if (!Y.getNode())
11398           return SDValue();
11399
11400         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11401         if (Mask.getOpcode() != ISD::BITCAST ||
11402             X.getOpcode() != ISD::BITCAST ||
11403             Y.getOpcode() != ISD::BITCAST)
11404           return SDValue();
11405
11406         // Look through mask bitcast.
11407         Mask = Mask.getOperand(0);
11408         EVT MaskVT = Mask.getValueType();
11409
11410         // Validate that the Mask operand is a vector sra node.  The sra node
11411         // will be an intrinsic.
11412         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11413           return SDValue();
11414
11415         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11416         // there is no psrai.b
11417         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11418         case Intrinsic::x86_sse2_psrai_w:
11419         case Intrinsic::x86_sse2_psrai_d:
11420           break;
11421         default: return SDValue();
11422         }
11423
11424         // Check that the SRA is all signbits.
11425         SDValue SraC = Mask.getOperand(2);
11426         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11427         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11428         if ((SraAmt + 1) != EltBits)
11429           return SDValue();
11430
11431         DebugLoc DL = N->getDebugLoc();
11432
11433         // Now we know we at least have a plendvb with the mask val.  See if
11434         // we can form a psignb/w/d.
11435         // psign = x.type == y.type == mask.type && y = sub(0, x);
11436         X = X.getOperand(0);
11437         Y = Y.getOperand(0);
11438         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11439             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11440             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11441           unsigned Opc = 0;
11442           switch (EltBits) {
11443           case 8: Opc = X86ISD::PSIGNB; break;
11444           case 16: Opc = X86ISD::PSIGNW; break;
11445           case 32: Opc = X86ISD::PSIGND; break;
11446           default: break;
11447           }
11448           if (Opc) {
11449             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11450             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11451           }
11452         }
11453         // PBLENDVB only available on SSE 4.1
11454         if (!Subtarget->hasSSE41())
11455           return SDValue();
11456
11457         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11458         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11459         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11460         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11461         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11462       }
11463     }
11464   }
11465
11466   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11467   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11468     std::swap(N0, N1);
11469   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11470     return SDValue();
11471   if (!N0.hasOneUse() || !N1.hasOneUse())
11472     return SDValue();
11473
11474   SDValue ShAmt0 = N0.getOperand(1);
11475   if (ShAmt0.getValueType() != MVT::i8)
11476     return SDValue();
11477   SDValue ShAmt1 = N1.getOperand(1);
11478   if (ShAmt1.getValueType() != MVT::i8)
11479     return SDValue();
11480   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11481     ShAmt0 = ShAmt0.getOperand(0);
11482   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11483     ShAmt1 = ShAmt1.getOperand(0);
11484
11485   DebugLoc DL = N->getDebugLoc();
11486   unsigned Opc = X86ISD::SHLD;
11487   SDValue Op0 = N0.getOperand(0);
11488   SDValue Op1 = N1.getOperand(0);
11489   if (ShAmt0.getOpcode() == ISD::SUB) {
11490     Opc = X86ISD::SHRD;
11491     std::swap(Op0, Op1);
11492     std::swap(ShAmt0, ShAmt1);
11493   }
11494
11495   unsigned Bits = VT.getSizeInBits();
11496   if (ShAmt1.getOpcode() == ISD::SUB) {
11497     SDValue Sum = ShAmt1.getOperand(0);
11498     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11499       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11500       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11501         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11502       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11503         return DAG.getNode(Opc, DL, VT,
11504                            Op0, Op1,
11505                            DAG.getNode(ISD::TRUNCATE, DL,
11506                                        MVT::i8, ShAmt0));
11507     }
11508   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11509     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11510     if (ShAmt0C &&
11511         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11512       return DAG.getNode(Opc, DL, VT,
11513                          N0.getOperand(0), N1.getOperand(0),
11514                          DAG.getNode(ISD::TRUNCATE, DL,
11515                                        MVT::i8, ShAmt0));
11516   }
11517
11518   return SDValue();
11519 }
11520
11521 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11522 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11523                                    const X86Subtarget *Subtarget) {
11524   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11525   // the FP state in cases where an emms may be missing.
11526   // A preferable solution to the general problem is to figure out the right
11527   // places to insert EMMS.  This qualifies as a quick hack.
11528
11529   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11530   StoreSDNode *St = cast<StoreSDNode>(N);
11531   EVT VT = St->getValue().getValueType();
11532   if (VT.getSizeInBits() != 64)
11533     return SDValue();
11534
11535   const Function *F = DAG.getMachineFunction().getFunction();
11536   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11537   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11538     && Subtarget->hasSSE2();
11539   if ((VT.isVector() ||
11540        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11541       isa<LoadSDNode>(St->getValue()) &&
11542       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11543       St->getChain().hasOneUse() && !St->isVolatile()) {
11544     SDNode* LdVal = St->getValue().getNode();
11545     LoadSDNode *Ld = 0;
11546     int TokenFactorIndex = -1;
11547     SmallVector<SDValue, 8> Ops;
11548     SDNode* ChainVal = St->getChain().getNode();
11549     // Must be a store of a load.  We currently handle two cases:  the load
11550     // is a direct child, and it's under an intervening TokenFactor.  It is
11551     // possible to dig deeper under nested TokenFactors.
11552     if (ChainVal == LdVal)
11553       Ld = cast<LoadSDNode>(St->getChain());
11554     else if (St->getValue().hasOneUse() &&
11555              ChainVal->getOpcode() == ISD::TokenFactor) {
11556       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11557         if (ChainVal->getOperand(i).getNode() == LdVal) {
11558           TokenFactorIndex = i;
11559           Ld = cast<LoadSDNode>(St->getValue());
11560         } else
11561           Ops.push_back(ChainVal->getOperand(i));
11562       }
11563     }
11564
11565     if (!Ld || !ISD::isNormalLoad(Ld))
11566       return SDValue();
11567
11568     // If this is not the MMX case, i.e. we are just turning i64 load/store
11569     // into f64 load/store, avoid the transformation if there are multiple
11570     // uses of the loaded value.
11571     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11572       return SDValue();
11573
11574     DebugLoc LdDL = Ld->getDebugLoc();
11575     DebugLoc StDL = N->getDebugLoc();
11576     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11577     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11578     // pair instead.
11579     if (Subtarget->is64Bit() || F64IsLegal) {
11580       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11581       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11582                                   Ld->getPointerInfo(), Ld->isVolatile(),
11583                                   Ld->isNonTemporal(), Ld->getAlignment());
11584       SDValue NewChain = NewLd.getValue(1);
11585       if (TokenFactorIndex != -1) {
11586         Ops.push_back(NewChain);
11587         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11588                                Ops.size());
11589       }
11590       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11591                           St->getPointerInfo(),
11592                           St->isVolatile(), St->isNonTemporal(),
11593                           St->getAlignment());
11594     }
11595
11596     // Otherwise, lower to two pairs of 32-bit loads / stores.
11597     SDValue LoAddr = Ld->getBasePtr();
11598     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11599                                  DAG.getConstant(4, MVT::i32));
11600
11601     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11602                                Ld->getPointerInfo(),
11603                                Ld->isVolatile(), Ld->isNonTemporal(),
11604                                Ld->getAlignment());
11605     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11606                                Ld->getPointerInfo().getWithOffset(4),
11607                                Ld->isVolatile(), Ld->isNonTemporal(),
11608                                MinAlign(Ld->getAlignment(), 4));
11609
11610     SDValue NewChain = LoLd.getValue(1);
11611     if (TokenFactorIndex != -1) {
11612       Ops.push_back(LoLd);
11613       Ops.push_back(HiLd);
11614       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11615                              Ops.size());
11616     }
11617
11618     LoAddr = St->getBasePtr();
11619     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11620                          DAG.getConstant(4, MVT::i32));
11621
11622     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11623                                 St->getPointerInfo(),
11624                                 St->isVolatile(), St->isNonTemporal(),
11625                                 St->getAlignment());
11626     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11627                                 St->getPointerInfo().getWithOffset(4),
11628                                 St->isVolatile(),
11629                                 St->isNonTemporal(),
11630                                 MinAlign(St->getAlignment(), 4));
11631     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11632   }
11633   return SDValue();
11634 }
11635
11636 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11637 /// X86ISD::FXOR nodes.
11638 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11639   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11640   // F[X]OR(0.0, x) -> x
11641   // F[X]OR(x, 0.0) -> x
11642   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11643     if (C->getValueAPF().isPosZero())
11644       return N->getOperand(1);
11645   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11646     if (C->getValueAPF().isPosZero())
11647       return N->getOperand(0);
11648   return SDValue();
11649 }
11650
11651 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11652 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11653   // FAND(0.0, x) -> 0.0
11654   // FAND(x, 0.0) -> 0.0
11655   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11656     if (C->getValueAPF().isPosZero())
11657       return N->getOperand(0);
11658   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11659     if (C->getValueAPF().isPosZero())
11660       return N->getOperand(1);
11661   return SDValue();
11662 }
11663
11664 static SDValue PerformBTCombine(SDNode *N,
11665                                 SelectionDAG &DAG,
11666                                 TargetLowering::DAGCombinerInfo &DCI) {
11667   // BT ignores high bits in the bit index operand.
11668   SDValue Op1 = N->getOperand(1);
11669   if (Op1.hasOneUse()) {
11670     unsigned BitWidth = Op1.getValueSizeInBits();
11671     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11672     APInt KnownZero, KnownOne;
11673     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11674                                           !DCI.isBeforeLegalizeOps());
11675     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11676     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11677         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11678       DCI.CommitTargetLoweringOpt(TLO);
11679   }
11680   return SDValue();
11681 }
11682
11683 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11684   SDValue Op = N->getOperand(0);
11685   if (Op.getOpcode() == ISD::BITCAST)
11686     Op = Op.getOperand(0);
11687   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11688   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11689       VT.getVectorElementType().getSizeInBits() ==
11690       OpVT.getVectorElementType().getSizeInBits()) {
11691     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11692   }
11693   return SDValue();
11694 }
11695
11696 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11697   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11698   //           (and (i32 x86isd::setcc_carry), 1)
11699   // This eliminates the zext. This transformation is necessary because
11700   // ISD::SETCC is always legalized to i8.
11701   DebugLoc dl = N->getDebugLoc();
11702   SDValue N0 = N->getOperand(0);
11703   EVT VT = N->getValueType(0);
11704   if (N0.getOpcode() == ISD::AND &&
11705       N0.hasOneUse() &&
11706       N0.getOperand(0).hasOneUse()) {
11707     SDValue N00 = N0.getOperand(0);
11708     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11709       return SDValue();
11710     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11711     if (!C || C->getZExtValue() != 1)
11712       return SDValue();
11713     return DAG.getNode(ISD::AND, dl, VT,
11714                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11715                                    N00.getOperand(0), N00.getOperand(1)),
11716                        DAG.getConstant(1, VT));
11717   }
11718
11719   return SDValue();
11720 }
11721
11722 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11723 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11724   unsigned X86CC = N->getConstantOperandVal(0);
11725   SDValue EFLAG = N->getOperand(1);
11726   DebugLoc DL = N->getDebugLoc();
11727
11728   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11729   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11730   // cases.
11731   if (X86CC == X86::COND_B)
11732     return DAG.getNode(ISD::AND, DL, MVT::i8,
11733                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11734                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11735                        DAG.getConstant(1, MVT::i8));
11736
11737   return SDValue();
11738 }
11739
11740 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11741 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11742                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11743   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11744   // the result is either zero or one (depending on the input carry bit).
11745   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11746   if (X86::isZeroNode(N->getOperand(0)) &&
11747       X86::isZeroNode(N->getOperand(1)) &&
11748       // We don't have a good way to replace an EFLAGS use, so only do this when
11749       // dead right now.
11750       SDValue(N, 1).use_empty()) {
11751     DebugLoc DL = N->getDebugLoc();
11752     EVT VT = N->getValueType(0);
11753     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11754     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11755                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11756                                            DAG.getConstant(X86::COND_B,MVT::i8),
11757                                            N->getOperand(2)),
11758                                DAG.getConstant(1, VT));
11759     return DCI.CombineTo(N, Res1, CarryOut);
11760   }
11761
11762   return SDValue();
11763 }
11764
11765 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11766 //      (add Y, (setne X, 0)) -> sbb -1, Y
11767 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11768 //      (sub (setne X, 0), Y) -> adc -1, Y
11769 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11770   DebugLoc DL = N->getDebugLoc();
11771
11772   // Look through ZExts.
11773   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11774   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11775     return SDValue();
11776
11777   SDValue SetCC = Ext.getOperand(0);
11778   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11779     return SDValue();
11780
11781   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11782   if (CC != X86::COND_E && CC != X86::COND_NE)
11783     return SDValue();
11784
11785   SDValue Cmp = SetCC.getOperand(1);
11786   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11787       !X86::isZeroNode(Cmp.getOperand(1)) ||
11788       !Cmp.getOperand(0).getValueType().isInteger())
11789     return SDValue();
11790
11791   SDValue CmpOp0 = Cmp.getOperand(0);
11792   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11793                                DAG.getConstant(1, CmpOp0.getValueType()));
11794
11795   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11796   if (CC == X86::COND_NE)
11797     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11798                        DL, OtherVal.getValueType(), OtherVal,
11799                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11800   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11801                      DL, OtherVal.getValueType(), OtherVal,
11802                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11803 }
11804
11805 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11806                                              DAGCombinerInfo &DCI) const {
11807   SelectionDAG &DAG = DCI.DAG;
11808   switch (N->getOpcode()) {
11809   default: break;
11810   case ISD::EXTRACT_VECTOR_ELT:
11811     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11812   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11813   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11814   case ISD::ADD:
11815   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
11816   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
11817   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11818   case ISD::SHL:
11819   case ISD::SRA:
11820   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11821   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11822   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11823   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11824   case X86ISD::FXOR:
11825   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11826   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11827   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11828   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11829   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11830   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
11831   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11832   case X86ISD::SHUFPD:
11833   case X86ISD::PALIGN:
11834   case X86ISD::PUNPCKHBW:
11835   case X86ISD::PUNPCKHWD:
11836   case X86ISD::PUNPCKHDQ:
11837   case X86ISD::PUNPCKHQDQ:
11838   case X86ISD::UNPCKHPS:
11839   case X86ISD::UNPCKHPD:
11840   case X86ISD::PUNPCKLBW:
11841   case X86ISD::PUNPCKLWD:
11842   case X86ISD::PUNPCKLDQ:
11843   case X86ISD::PUNPCKLQDQ:
11844   case X86ISD::UNPCKLPS:
11845   case X86ISD::UNPCKLPD:
11846   case X86ISD::MOVHLPS:
11847   case X86ISD::MOVLHPS:
11848   case X86ISD::PSHUFD:
11849   case X86ISD::PSHUFHW:
11850   case X86ISD::PSHUFLW:
11851   case X86ISD::MOVSS:
11852   case X86ISD::MOVSD:
11853   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11854   }
11855
11856   return SDValue();
11857 }
11858
11859 /// isTypeDesirableForOp - Return true if the target has native support for
11860 /// the specified value type and it is 'desirable' to use the type for the
11861 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11862 /// instruction encodings are longer and some i16 instructions are slow.
11863 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11864   if (!isTypeLegal(VT))
11865     return false;
11866   if (VT != MVT::i16)
11867     return true;
11868
11869   switch (Opc) {
11870   default:
11871     return true;
11872   case ISD::LOAD:
11873   case ISD::SIGN_EXTEND:
11874   case ISD::ZERO_EXTEND:
11875   case ISD::ANY_EXTEND:
11876   case ISD::SHL:
11877   case ISD::SRL:
11878   case ISD::SUB:
11879   case ISD::ADD:
11880   case ISD::MUL:
11881   case ISD::AND:
11882   case ISD::OR:
11883   case ISD::XOR:
11884     return false;
11885   }
11886 }
11887
11888 /// IsDesirableToPromoteOp - This method query the target whether it is
11889 /// beneficial for dag combiner to promote the specified node. If true, it
11890 /// should return the desired promotion type by reference.
11891 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11892   EVT VT = Op.getValueType();
11893   if (VT != MVT::i16)
11894     return false;
11895
11896   bool Promote = false;
11897   bool Commute = false;
11898   switch (Op.getOpcode()) {
11899   default: break;
11900   case ISD::LOAD: {
11901     LoadSDNode *LD = cast<LoadSDNode>(Op);
11902     // If the non-extending load has a single use and it's not live out, then it
11903     // might be folded.
11904     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11905                                                      Op.hasOneUse()*/) {
11906       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11907              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11908         // The only case where we'd want to promote LOAD (rather then it being
11909         // promoted as an operand is when it's only use is liveout.
11910         if (UI->getOpcode() != ISD::CopyToReg)
11911           return false;
11912       }
11913     }
11914     Promote = true;
11915     break;
11916   }
11917   case ISD::SIGN_EXTEND:
11918   case ISD::ZERO_EXTEND:
11919   case ISD::ANY_EXTEND:
11920     Promote = true;
11921     break;
11922   case ISD::SHL:
11923   case ISD::SRL: {
11924     SDValue N0 = Op.getOperand(0);
11925     // Look out for (store (shl (load), x)).
11926     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11927       return false;
11928     Promote = true;
11929     break;
11930   }
11931   case ISD::ADD:
11932   case ISD::MUL:
11933   case ISD::AND:
11934   case ISD::OR:
11935   case ISD::XOR:
11936     Commute = true;
11937     // fallthrough
11938   case ISD::SUB: {
11939     SDValue N0 = Op.getOperand(0);
11940     SDValue N1 = Op.getOperand(1);
11941     if (!Commute && MayFoldLoad(N1))
11942       return false;
11943     // Avoid disabling potential load folding opportunities.
11944     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11945       return false;
11946     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11947       return false;
11948     Promote = true;
11949   }
11950   }
11951
11952   PVT = MVT::i32;
11953   return Promote;
11954 }
11955
11956 //===----------------------------------------------------------------------===//
11957 //                           X86 Inline Assembly Support
11958 //===----------------------------------------------------------------------===//
11959
11960 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11961   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11962
11963   std::string AsmStr = IA->getAsmString();
11964
11965   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11966   SmallVector<StringRef, 4> AsmPieces;
11967   SplitString(AsmStr, AsmPieces, ";\n");
11968
11969   switch (AsmPieces.size()) {
11970   default: return false;
11971   case 1:
11972     AsmStr = AsmPieces[0];
11973     AsmPieces.clear();
11974     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11975
11976     // FIXME: this should verify that we are targetting a 486 or better.  If not,
11977     // we will turn this bswap into something that will be lowered to logical ops
11978     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11979     // so don't worry about this.
11980     // bswap $0
11981     if (AsmPieces.size() == 2 &&
11982         (AsmPieces[0] == "bswap" ||
11983          AsmPieces[0] == "bswapq" ||
11984          AsmPieces[0] == "bswapl") &&
11985         (AsmPieces[1] == "$0" ||
11986          AsmPieces[1] == "${0:q}")) {
11987       // No need to check constraints, nothing other than the equivalent of
11988       // "=r,0" would be valid here.
11989       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11990       if (!Ty || Ty->getBitWidth() % 16 != 0)
11991         return false;
11992       return IntrinsicLowering::LowerToByteSwap(CI);
11993     }
11994     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11995     if (CI->getType()->isIntegerTy(16) &&
11996         AsmPieces.size() == 3 &&
11997         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11998         AsmPieces[1] == "$$8," &&
11999         AsmPieces[2] == "${0:w}" &&
12000         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12001       AsmPieces.clear();
12002       const std::string &ConstraintsStr = IA->getConstraintString();
12003       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12004       std::sort(AsmPieces.begin(), AsmPieces.end());
12005       if (AsmPieces.size() == 4 &&
12006           AsmPieces[0] == "~{cc}" &&
12007           AsmPieces[1] == "~{dirflag}" &&
12008           AsmPieces[2] == "~{flags}" &&
12009           AsmPieces[3] == "~{fpsr}") {
12010         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12011         if (!Ty || Ty->getBitWidth() % 16 != 0)
12012           return false;
12013         return IntrinsicLowering::LowerToByteSwap(CI);
12014       }
12015     }
12016     break;
12017   case 3:
12018     if (CI->getType()->isIntegerTy(32) &&
12019         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12020       SmallVector<StringRef, 4> Words;
12021       SplitString(AsmPieces[0], Words, " \t,");
12022       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12023           Words[2] == "${0:w}") {
12024         Words.clear();
12025         SplitString(AsmPieces[1], Words, " \t,");
12026         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12027             Words[2] == "$0") {
12028           Words.clear();
12029           SplitString(AsmPieces[2], Words, " \t,");
12030           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12031               Words[2] == "${0:w}") {
12032             AsmPieces.clear();
12033             const std::string &ConstraintsStr = IA->getConstraintString();
12034             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12035             std::sort(AsmPieces.begin(), AsmPieces.end());
12036             if (AsmPieces.size() == 4 &&
12037                 AsmPieces[0] == "~{cc}" &&
12038                 AsmPieces[1] == "~{dirflag}" &&
12039                 AsmPieces[2] == "~{flags}" &&
12040                 AsmPieces[3] == "~{fpsr}") {
12041               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12042               if (!Ty || Ty->getBitWidth() % 16 != 0)
12043                 return false;
12044               return IntrinsicLowering::LowerToByteSwap(CI);
12045             }
12046           }
12047         }
12048       }
12049     }
12050
12051     if (CI->getType()->isIntegerTy(64)) {
12052       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12053       if (Constraints.size() >= 2 &&
12054           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12055           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12056         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12057         SmallVector<StringRef, 4> Words;
12058         SplitString(AsmPieces[0], Words, " \t");
12059         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12060           Words.clear();
12061           SplitString(AsmPieces[1], Words, " \t");
12062           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12063             Words.clear();
12064             SplitString(AsmPieces[2], Words, " \t,");
12065             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12066                 Words[2] == "%edx") {
12067               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12068               if (!Ty || Ty->getBitWidth() % 16 != 0)
12069                 return false;
12070               return IntrinsicLowering::LowerToByteSwap(CI);
12071             }
12072           }
12073         }
12074       }
12075     }
12076     break;
12077   }
12078   return false;
12079 }
12080
12081
12082
12083 /// getConstraintType - Given a constraint letter, return the type of
12084 /// constraint it is for this target.
12085 X86TargetLowering::ConstraintType
12086 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12087   if (Constraint.size() == 1) {
12088     switch (Constraint[0]) {
12089     case 'R':
12090     case 'q':
12091     case 'Q':
12092     case 'f':
12093     case 't':
12094     case 'u':
12095     case 'y':
12096     case 'x':
12097     case 'Y':
12098       return C_RegisterClass;
12099     case 'a':
12100     case 'b':
12101     case 'c':
12102     case 'd':
12103     case 'S':
12104     case 'D':
12105     case 'A':
12106       return C_Register;
12107     case 'I':
12108     case 'J':
12109     case 'K':
12110     case 'L':
12111     case 'M':
12112     case 'N':
12113     case 'G':
12114     case 'C':
12115     case 'e':
12116     case 'Z':
12117       return C_Other;
12118     default:
12119       break;
12120     }
12121   }
12122   return TargetLowering::getConstraintType(Constraint);
12123 }
12124
12125 /// Examine constraint type and operand type and determine a weight value.
12126 /// This object must already have been set up with the operand type
12127 /// and the current alternative constraint selected.
12128 TargetLowering::ConstraintWeight
12129   X86TargetLowering::getSingleConstraintMatchWeight(
12130     AsmOperandInfo &info, const char *constraint) const {
12131   ConstraintWeight weight = CW_Invalid;
12132   Value *CallOperandVal = info.CallOperandVal;
12133     // If we don't have a value, we can't do a match,
12134     // but allow it at the lowest weight.
12135   if (CallOperandVal == NULL)
12136     return CW_Default;
12137   const Type *type = CallOperandVal->getType();
12138   // Look at the constraint type.
12139   switch (*constraint) {
12140   default:
12141     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12142   case 'R':
12143   case 'q':
12144   case 'Q':
12145   case 'a':
12146   case 'b':
12147   case 'c':
12148   case 'd':
12149   case 'S':
12150   case 'D':
12151   case 'A':
12152     if (CallOperandVal->getType()->isIntegerTy())
12153       weight = CW_SpecificReg;
12154     break;
12155   case 'f':
12156   case 't':
12157   case 'u':
12158       if (type->isFloatingPointTy())
12159         weight = CW_SpecificReg;
12160       break;
12161   case 'y':
12162       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12163         weight = CW_SpecificReg;
12164       break;
12165   case 'x':
12166   case 'Y':
12167     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12168       weight = CW_Register;
12169     break;
12170   case 'I':
12171     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12172       if (C->getZExtValue() <= 31)
12173         weight = CW_Constant;
12174     }
12175     break;
12176   case 'J':
12177     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12178       if (C->getZExtValue() <= 63)
12179         weight = CW_Constant;
12180     }
12181     break;
12182   case 'K':
12183     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12184       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12185         weight = CW_Constant;
12186     }
12187     break;
12188   case 'L':
12189     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12190       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12191         weight = CW_Constant;
12192     }
12193     break;
12194   case 'M':
12195     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12196       if (C->getZExtValue() <= 3)
12197         weight = CW_Constant;
12198     }
12199     break;
12200   case 'N':
12201     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12202       if (C->getZExtValue() <= 0xff)
12203         weight = CW_Constant;
12204     }
12205     break;
12206   case 'G':
12207   case 'C':
12208     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12209       weight = CW_Constant;
12210     }
12211     break;
12212   case 'e':
12213     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12214       if ((C->getSExtValue() >= -0x80000000LL) &&
12215           (C->getSExtValue() <= 0x7fffffffLL))
12216         weight = CW_Constant;
12217     }
12218     break;
12219   case 'Z':
12220     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12221       if (C->getZExtValue() <= 0xffffffff)
12222         weight = CW_Constant;
12223     }
12224     break;
12225   }
12226   return weight;
12227 }
12228
12229 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12230 /// with another that has more specific requirements based on the type of the
12231 /// corresponding operand.
12232 const char *X86TargetLowering::
12233 LowerXConstraint(EVT ConstraintVT) const {
12234   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12235   // 'f' like normal targets.
12236   if (ConstraintVT.isFloatingPoint()) {
12237     if (Subtarget->hasXMMInt())
12238       return "Y";
12239     if (Subtarget->hasXMM())
12240       return "x";
12241   }
12242
12243   return TargetLowering::LowerXConstraint(ConstraintVT);
12244 }
12245
12246 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12247 /// vector.  If it is invalid, don't add anything to Ops.
12248 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12249                                                      char Constraint,
12250                                                      std::vector<SDValue>&Ops,
12251                                                      SelectionDAG &DAG) const {
12252   SDValue Result(0, 0);
12253
12254   switch (Constraint) {
12255   default: break;
12256   case 'I':
12257     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12258       if (C->getZExtValue() <= 31) {
12259         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12260         break;
12261       }
12262     }
12263     return;
12264   case 'J':
12265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12266       if (C->getZExtValue() <= 63) {
12267         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12268         break;
12269       }
12270     }
12271     return;
12272   case 'K':
12273     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12274       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12275         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12276         break;
12277       }
12278     }
12279     return;
12280   case 'N':
12281     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12282       if (C->getZExtValue() <= 255) {
12283         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12284         break;
12285       }
12286     }
12287     return;
12288   case 'e': {
12289     // 32-bit signed value
12290     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12291       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12292                                            C->getSExtValue())) {
12293         // Widen to 64 bits here to get it sign extended.
12294         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12295         break;
12296       }
12297     // FIXME gcc accepts some relocatable values here too, but only in certain
12298     // memory models; it's complicated.
12299     }
12300     return;
12301   }
12302   case 'Z': {
12303     // 32-bit unsigned value
12304     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12305       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12306                                            C->getZExtValue())) {
12307         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12308         break;
12309       }
12310     }
12311     // FIXME gcc accepts some relocatable values here too, but only in certain
12312     // memory models; it's complicated.
12313     return;
12314   }
12315   case 'i': {
12316     // Literal immediates are always ok.
12317     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12318       // Widen to 64 bits here to get it sign extended.
12319       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12320       break;
12321     }
12322
12323     // In any sort of PIC mode addresses need to be computed at runtime by
12324     // adding in a register or some sort of table lookup.  These can't
12325     // be used as immediates.
12326     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12327       return;
12328
12329     // If we are in non-pic codegen mode, we allow the address of a global (with
12330     // an optional displacement) to be used with 'i'.
12331     GlobalAddressSDNode *GA = 0;
12332     int64_t Offset = 0;
12333
12334     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12335     while (1) {
12336       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12337         Offset += GA->getOffset();
12338         break;
12339       } else if (Op.getOpcode() == ISD::ADD) {
12340         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12341           Offset += C->getZExtValue();
12342           Op = Op.getOperand(0);
12343           continue;
12344         }
12345       } else if (Op.getOpcode() == ISD::SUB) {
12346         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12347           Offset += -C->getZExtValue();
12348           Op = Op.getOperand(0);
12349           continue;
12350         }
12351       }
12352
12353       // Otherwise, this isn't something we can handle, reject it.
12354       return;
12355     }
12356
12357     const GlobalValue *GV = GA->getGlobal();
12358     // If we require an extra load to get this address, as in PIC mode, we
12359     // can't accept it.
12360     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12361                                                         getTargetMachine())))
12362       return;
12363
12364     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12365                                         GA->getValueType(0), Offset);
12366     break;
12367   }
12368   }
12369
12370   if (Result.getNode()) {
12371     Ops.push_back(Result);
12372     return;
12373   }
12374   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12375 }
12376
12377 std::vector<unsigned> X86TargetLowering::
12378 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12379                                   EVT VT) const {
12380   if (Constraint.size() == 1) {
12381     // FIXME: not handling fp-stack yet!
12382     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12383     default: break;  // Unknown constraint letter
12384     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12385       if (Subtarget->is64Bit()) {
12386         if (VT == MVT::i32)
12387           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12388                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12389                                        X86::R10D,X86::R11D,X86::R12D,
12390                                        X86::R13D,X86::R14D,X86::R15D,
12391                                        X86::EBP, X86::ESP, 0);
12392         else if (VT == MVT::i16)
12393           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12394                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12395                                        X86::R10W,X86::R11W,X86::R12W,
12396                                        X86::R13W,X86::R14W,X86::R15W,
12397                                        X86::BP,  X86::SP, 0);
12398         else if (VT == MVT::i8)
12399           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12400                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12401                                        X86::R10B,X86::R11B,X86::R12B,
12402                                        X86::R13B,X86::R14B,X86::R15B,
12403                                        X86::BPL, X86::SPL, 0);
12404
12405         else if (VT == MVT::i64)
12406           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12407                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12408                                        X86::R10, X86::R11, X86::R12,
12409                                        X86::R13, X86::R14, X86::R15,
12410                                        X86::RBP, X86::RSP, 0);
12411
12412         break;
12413       }
12414       // 32-bit fallthrough
12415     case 'Q':   // Q_REGS
12416       if (VT == MVT::i32)
12417         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12418       else if (VT == MVT::i16)
12419         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12420       else if (VT == MVT::i8)
12421         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12422       else if (VT == MVT::i64)
12423         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12424       break;
12425     }
12426   }
12427
12428   return std::vector<unsigned>();
12429 }
12430
12431 std::pair<unsigned, const TargetRegisterClass*>
12432 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12433                                                 EVT VT) const {
12434   // First, see if this is a constraint that directly corresponds to an LLVM
12435   // register class.
12436   if (Constraint.size() == 1) {
12437     // GCC Constraint Letters
12438     switch (Constraint[0]) {
12439     default: break;
12440     case 'r':   // GENERAL_REGS
12441     case 'l':   // INDEX_REGS
12442       if (VT == MVT::i8)
12443         return std::make_pair(0U, X86::GR8RegisterClass);
12444       if (VT == MVT::i16)
12445         return std::make_pair(0U, X86::GR16RegisterClass);
12446       if (VT == MVT::i32 || !Subtarget->is64Bit())
12447         return std::make_pair(0U, X86::GR32RegisterClass);
12448       return std::make_pair(0U, X86::GR64RegisterClass);
12449     case 'R':   // LEGACY_REGS
12450       if (VT == MVT::i8)
12451         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12452       if (VT == MVT::i16)
12453         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12454       if (VT == MVT::i32 || !Subtarget->is64Bit())
12455         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12456       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12457     case 'f':  // FP Stack registers.
12458       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12459       // value to the correct fpstack register class.
12460       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12461         return std::make_pair(0U, X86::RFP32RegisterClass);
12462       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12463         return std::make_pair(0U, X86::RFP64RegisterClass);
12464       return std::make_pair(0U, X86::RFP80RegisterClass);
12465     case 'y':   // MMX_REGS if MMX allowed.
12466       if (!Subtarget->hasMMX()) break;
12467       return std::make_pair(0U, X86::VR64RegisterClass);
12468     case 'Y':   // SSE_REGS if SSE2 allowed
12469       if (!Subtarget->hasXMMInt()) break;
12470       // FALL THROUGH.
12471     case 'x':   // SSE_REGS if SSE1 allowed
12472       if (!Subtarget->hasXMM()) break;
12473
12474       switch (VT.getSimpleVT().SimpleTy) {
12475       default: break;
12476       // Scalar SSE types.
12477       case MVT::f32:
12478       case MVT::i32:
12479         return std::make_pair(0U, X86::FR32RegisterClass);
12480       case MVT::f64:
12481       case MVT::i64:
12482         return std::make_pair(0U, X86::FR64RegisterClass);
12483       // Vector types.
12484       case MVT::v16i8:
12485       case MVT::v8i16:
12486       case MVT::v4i32:
12487       case MVT::v2i64:
12488       case MVT::v4f32:
12489       case MVT::v2f64:
12490         return std::make_pair(0U, X86::VR128RegisterClass);
12491       }
12492       break;
12493     }
12494   }
12495
12496   // Use the default implementation in TargetLowering to convert the register
12497   // constraint into a member of a register class.
12498   std::pair<unsigned, const TargetRegisterClass*> Res;
12499   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12500
12501   // Not found as a standard register?
12502   if (Res.second == 0) {
12503     // Map st(0) -> st(7) -> ST0
12504     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12505         tolower(Constraint[1]) == 's' &&
12506         tolower(Constraint[2]) == 't' &&
12507         Constraint[3] == '(' &&
12508         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12509         Constraint[5] == ')' &&
12510         Constraint[6] == '}') {
12511
12512       Res.first = X86::ST0+Constraint[4]-'0';
12513       Res.second = X86::RFP80RegisterClass;
12514       return Res;
12515     }
12516
12517     // GCC allows "st(0)" to be called just plain "st".
12518     if (StringRef("{st}").equals_lower(Constraint)) {
12519       Res.first = X86::ST0;
12520       Res.second = X86::RFP80RegisterClass;
12521       return Res;
12522     }
12523
12524     // flags -> EFLAGS
12525     if (StringRef("{flags}").equals_lower(Constraint)) {
12526       Res.first = X86::EFLAGS;
12527       Res.second = X86::CCRRegisterClass;
12528       return Res;
12529     }
12530
12531     // 'A' means EAX + EDX.
12532     if (Constraint == "A") {
12533       Res.first = X86::EAX;
12534       Res.second = X86::GR32_ADRegisterClass;
12535       return Res;
12536     }
12537     return Res;
12538   }
12539
12540   // Otherwise, check to see if this is a register class of the wrong value
12541   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12542   // turn into {ax},{dx}.
12543   if (Res.second->hasType(VT))
12544     return Res;   // Correct type already, nothing to do.
12545
12546   // All of the single-register GCC register classes map their values onto
12547   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12548   // really want an 8-bit or 32-bit register, map to the appropriate register
12549   // class and return the appropriate register.
12550   if (Res.second == X86::GR16RegisterClass) {
12551     if (VT == MVT::i8) {
12552       unsigned DestReg = 0;
12553       switch (Res.first) {
12554       default: break;
12555       case X86::AX: DestReg = X86::AL; break;
12556       case X86::DX: DestReg = X86::DL; break;
12557       case X86::CX: DestReg = X86::CL; break;
12558       case X86::BX: DestReg = X86::BL; break;
12559       }
12560       if (DestReg) {
12561         Res.first = DestReg;
12562         Res.second = X86::GR8RegisterClass;
12563       }
12564     } else if (VT == MVT::i32) {
12565       unsigned DestReg = 0;
12566       switch (Res.first) {
12567       default: break;
12568       case X86::AX: DestReg = X86::EAX; break;
12569       case X86::DX: DestReg = X86::EDX; break;
12570       case X86::CX: DestReg = X86::ECX; break;
12571       case X86::BX: DestReg = X86::EBX; break;
12572       case X86::SI: DestReg = X86::ESI; break;
12573       case X86::DI: DestReg = X86::EDI; break;
12574       case X86::BP: DestReg = X86::EBP; break;
12575       case X86::SP: DestReg = X86::ESP; break;
12576       }
12577       if (DestReg) {
12578         Res.first = DestReg;
12579         Res.second = X86::GR32RegisterClass;
12580       }
12581     } else if (VT == MVT::i64) {
12582       unsigned DestReg = 0;
12583       switch (Res.first) {
12584       default: break;
12585       case X86::AX: DestReg = X86::RAX; break;
12586       case X86::DX: DestReg = X86::RDX; break;
12587       case X86::CX: DestReg = X86::RCX; break;
12588       case X86::BX: DestReg = X86::RBX; break;
12589       case X86::SI: DestReg = X86::RSI; break;
12590       case X86::DI: DestReg = X86::RDI; break;
12591       case X86::BP: DestReg = X86::RBP; break;
12592       case X86::SP: DestReg = X86::RSP; break;
12593       }
12594       if (DestReg) {
12595         Res.first = DestReg;
12596         Res.second = X86::GR64RegisterClass;
12597       }
12598     }
12599   } else if (Res.second == X86::FR32RegisterClass ||
12600              Res.second == X86::FR64RegisterClass ||
12601              Res.second == X86::VR128RegisterClass) {
12602     // Handle references to XMM physical registers that got mapped into the
12603     // wrong class.  This can happen with constraints like {xmm0} where the
12604     // target independent register mapper will just pick the first match it can
12605     // find, ignoring the required type.
12606     if (VT == MVT::f32)
12607       Res.second = X86::FR32RegisterClass;
12608     else if (VT == MVT::f64)
12609       Res.second = X86::FR64RegisterClass;
12610     else if (X86::VR128RegisterClass->hasType(VT))
12611       Res.second = X86::VR128RegisterClass;
12612   }
12613
12614   return Res;
12615 }